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