1use crate::{Supermaven, SupermavenCompletionStateId};
2use anyhow::Result;
3use edit_prediction_types::{EditPrediction, EditPredictionDelegate, EditPredictionIconSet};
4use futures::StreamExt as _;
5use gpui::{App, Context, Entity, EntityId, Task};
6use language::{Anchor, Buffer, BufferSnapshot};
7use std::{
8 ops::{AddAssign, Range},
9 path::Path,
10 sync::Arc,
11 time::Duration,
12};
13use text::{ToOffset, ToPoint};
14use ui::prelude::*;
15use unicode_segmentation::UnicodeSegmentation;
16
17pub const DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
18
19pub struct SupermavenEditPredictionDelegate {
20 supermaven: Entity<Supermaven>,
21 buffer_id: Option<EntityId>,
22 completion_id: Option<SupermavenCompletionStateId>,
23 completion_text: Option<String>,
24 file_extension: Option<String>,
25 pending_refresh: Option<Task<Result<()>>>,
26 completion_position: Option<language::Anchor>,
27}
28
29impl SupermavenEditPredictionDelegate {
30 pub fn new(supermaven: Entity<Supermaven>) -> Self {
31 Self {
32 supermaven,
33 buffer_id: None,
34 completion_id: None,
35 completion_text: None,
36 file_extension: None,
37 pending_refresh: None,
38 completion_position: None,
39 }
40 }
41}
42
43// Computes the edit prediction from the difference between the completion text.
44// This is defined by greedily matching the buffer text against the completion text.
45// Inlays are inserted for parts of the completion text that are not present in the buffer text.
46// For example, given the completion text "axbyc" and the buffer text "xy", the rendered output in the editor would be "[a]x[b]y[c]".
47// The parts in brackets are the inlays.
48fn completion_from_diff(
49 snapshot: BufferSnapshot,
50 completion_text: &str,
51 position: Anchor,
52 delete_range: Range<Anchor>,
53) -> EditPrediction {
54 let buffer_text = snapshot.text_for_range(delete_range).collect::<String>();
55
56 let mut edits: Vec<(Range<language::Anchor>, Arc<str>)> = Vec::new();
57
58 let completion_graphemes: Vec<&str> = completion_text.graphemes(true).collect();
59 let buffer_graphemes: Vec<&str> = buffer_text.graphemes(true).collect();
60
61 let mut offset = position.to_offset(&snapshot);
62
63 let mut i = 0;
64 let mut j = 0;
65 while i < completion_graphemes.len() && j < buffer_graphemes.len() {
66 // find the next instance of the buffer text in the completion text.
67 let k = completion_graphemes[i..]
68 .iter()
69 .position(|c| *c == buffer_graphemes[j]);
70 match k {
71 Some(k) => {
72 if k != 0 {
73 let offset = snapshot.anchor_after(offset);
74 // the range from the current position to item is an inlay.
75 let edit = (
76 offset..offset,
77 completion_graphemes[i..i + k].join("").into(),
78 );
79 edits.push(edit);
80 }
81 i += k + 1;
82 j += 1;
83 offset.add_assign(buffer_graphemes[j - 1].len());
84 }
85 None => {
86 // there are no more matching completions, so drop the remaining
87 // completion text as an inlay.
88 break;
89 }
90 }
91 }
92
93 if j == buffer_graphemes.len() && i < completion_graphemes.len() {
94 let offset = snapshot.anchor_after(offset);
95 // there is leftover completion text, so drop it as an inlay.
96 let edit_range = offset..offset;
97 let edit_text = completion_graphemes[i..].join("");
98 edits.push((edit_range, edit_text.into()));
99 }
100
101 EditPrediction::Local {
102 id: None,
103 edits,
104 edit_preview: None,
105 }
106}
107
108impl EditPredictionDelegate for SupermavenEditPredictionDelegate {
109 fn name() -> &'static str {
110 "supermaven"
111 }
112
113 fn display_name() -> &'static str {
114 "Supermaven"
115 }
116
117 fn show_predictions_in_menu() -> bool {
118 true
119 }
120
121 fn show_tab_accept_marker() -> bool {
122 true
123 }
124
125 fn supports_jump_to_edit() -> bool {
126 false
127 }
128
129 fn icons(&self, _cx: &App) -> EditPredictionIconSet {
130 EditPredictionIconSet::new(IconName::Supermaven)
131 .with_disabled(IconName::SupermavenDisabled)
132 .with_error(IconName::SupermavenError)
133 }
134
135 fn is_enabled(&self, _buffer: &Entity<Buffer>, _cursor_position: Anchor, cx: &App) -> bool {
136 self.supermaven.read(cx).is_enabled()
137 }
138
139 fn is_refreshing(&self, _cx: &App) -> bool {
140 self.pending_refresh.is_some() && self.completion_id.is_none()
141 }
142
143 fn refresh(
144 &mut self,
145 buffer_handle: Entity<Buffer>,
146 cursor_position: Anchor,
147 debounce: bool,
148 cx: &mut Context<Self>,
149 ) {
150 // Only make new completion requests when debounce is true (i.e., when text is typed)
151 // When debounce is false (i.e., cursor movement), we should not make new requests
152 if !debounce {
153 return;
154 }
155
156 reset_completion_cache(self, cx);
157
158 let Some(mut completion) = self.supermaven.update(cx, |supermaven, cx| {
159 supermaven.complete(&buffer_handle, cursor_position, cx)
160 }) else {
161 return;
162 };
163
164 self.pending_refresh = Some(cx.spawn(async move |this, cx| {
165 if debounce {
166 cx.background_executor().timer(DEBOUNCE_TIMEOUT).await;
167 }
168
169 while let Some(()) = completion.updates.next().await {
170 this.update(cx, |this, cx| {
171 // Get the completion text and cache it
172 if let Some(text) =
173 this.supermaven
174 .read(cx)
175 .completion(&buffer_handle, cursor_position, cx)
176 {
177 this.completion_text = Some(text.to_string());
178
179 this.completion_position = Some(cursor_position);
180 }
181
182 this.completion_id = Some(completion.id);
183 this.buffer_id = Some(buffer_handle.entity_id());
184 this.file_extension = buffer_handle.read(cx).file().and_then(|file| {
185 Some(
186 Path::new(file.file_name(cx))
187 .extension()?
188 .to_str()?
189 .to_string(),
190 )
191 });
192 cx.notify();
193 })?;
194 }
195 Ok(())
196 }));
197 }
198
199 fn accept(&mut self, _cx: &mut Context<Self>) {
200 reset_completion_cache(self, _cx);
201 }
202
203 fn discard(&mut self, _cx: &mut Context<Self>) {
204 reset_completion_cache(self, _cx);
205 }
206
207 fn suggest(
208 &mut self,
209 buffer: &Entity<Buffer>,
210 cursor_position: Anchor,
211 cx: &mut Context<Self>,
212 ) -> Option<EditPrediction> {
213 if self.buffer_id != Some(buffer.entity_id()) {
214 return None;
215 }
216
217 if self.completion_id.is_none() {
218 return None;
219 }
220
221 let completion_text = if let Some(cached_text) = &self.completion_text {
222 cached_text.as_str()
223 } else {
224 let text = self
225 .supermaven
226 .read(cx)
227 .completion(buffer, cursor_position, cx)?;
228 self.completion_text = Some(text.to_string());
229 text
230 };
231
232 // Check if the cursor is still at the same position as the completion request
233 // If we don't have a completion position stored, don't show the completion
234 if let Some(completion_position) = self.completion_position {
235 if cursor_position != completion_position {
236 return None;
237 }
238 } else {
239 return None;
240 }
241
242 let completion_text = trim_to_end_of_line_unless_leading_newline(completion_text);
243
244 let completion_text = completion_text.trim_end();
245
246 if !completion_text.trim().is_empty() {
247 let snapshot = buffer.read(cx).snapshot();
248
249 // Calculate the range from cursor to end of line correctly
250 let cursor_point = cursor_position.to_point(&snapshot);
251 let end_of_line = snapshot.anchor_after(language::Point::new(
252 cursor_point.row,
253 snapshot.line_len(cursor_point.row),
254 ));
255 let delete_range = cursor_position..end_of_line;
256
257 Some(completion_from_diff(
258 snapshot,
259 completion_text,
260 cursor_position,
261 delete_range,
262 ))
263 } else {
264 None
265 }
266 }
267}
268
269fn reset_completion_cache(
270 provider: &mut SupermavenEditPredictionDelegate,
271 _cx: &mut Context<SupermavenEditPredictionDelegate>,
272) {
273 provider.pending_refresh = None;
274 provider.completion_id = None;
275 provider.completion_text = None;
276 provider.completion_position = None;
277 provider.buffer_id = None;
278}
279
280fn trim_to_end_of_line_unless_leading_newline(text: &str) -> &str {
281 if has_leading_newline(text) {
282 text
283 } else if let Some(i) = text.find('\n') {
284 &text[..i]
285 } else {
286 text
287 }
288}
289
290fn has_leading_newline(text: &str) -> bool {
291 for c in text.chars() {
292 if c == '\n' {
293 return true;
294 }
295 if !c.is_whitespace() {
296 return false;
297 }
298 }
299 false
300}