1use crate::{Supermaven, SupermavenCompletionStateId};
2use anyhow::Result;
3use futures::StreamExt as _;
4use gpui::{App, Context, Entity, EntityId, Task};
5use inline_completion::{Direction, InlineCompletion, InlineCompletionProvider};
6use language::{Anchor, Buffer, BufferSnapshot};
7use std::{
8 ops::{AddAssign, Range},
9 path::Path,
10 time::Duration,
11};
12use text::{ToOffset, ToPoint};
13use unicode_segmentation::UnicodeSegmentation;
14
15pub const DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
16
17pub struct SupermavenCompletionProvider {
18 supermaven: Entity<Supermaven>,
19 buffer_id: Option<EntityId>,
20 completion_id: Option<SupermavenCompletionStateId>,
21 file_extension: Option<String>,
22 pending_refresh: Option<Task<Result<()>>>,
23}
24
25impl SupermavenCompletionProvider {
26 pub fn new(supermaven: Entity<Supermaven>) -> Self {
27 Self {
28 supermaven,
29 buffer_id: None,
30 completion_id: None,
31 file_extension: None,
32 pending_refresh: None,
33 }
34 }
35}
36
37// Computes the edit prediction from the difference between the completion text.
38// this is defined by greedily matching the buffer text against the completion text, with any leftover buffer placed at the end.
39// for example, given the completion text "moo cows are cool" and the buffer text "cowsre pool", the completion state would be
40// the inlays "moo ", " a", and "cool" which will render as "[moo ]cows[ a]re [cool]pool" in the editor.
41fn completion_from_diff(
42 snapshot: BufferSnapshot,
43 completion_text: &str,
44 position: Anchor,
45 delete_range: Range<Anchor>,
46) -> InlineCompletion {
47 let buffer_text = snapshot
48 .text_for_range(delete_range.clone())
49 .collect::<String>();
50
51 let mut edits: Vec<(Range<language::Anchor>, String)> = Vec::new();
52
53 let completion_graphemes: Vec<&str> = completion_text.graphemes(true).collect();
54 let buffer_graphemes: Vec<&str> = buffer_text.graphemes(true).collect();
55
56 let mut offset = position.to_offset(&snapshot);
57
58 let mut i = 0;
59 let mut j = 0;
60 while i < completion_graphemes.len() && j < buffer_graphemes.len() {
61 // find the next instance of the buffer text in the completion text.
62 let k = completion_graphemes[i..]
63 .iter()
64 .position(|c| *c == buffer_graphemes[j]);
65 match k {
66 Some(k) => {
67 if k != 0 {
68 let offset = snapshot.anchor_after(offset);
69 // the range from the current position to item is an inlay.
70 let edit = (offset..offset, completion_graphemes[i..i + k].join(""));
71 edits.push(edit);
72 }
73 i += k + 1;
74 j += 1;
75 offset.add_assign(buffer_graphemes[j - 1].len());
76 }
77 None => {
78 // there are no more matching completions, so drop the remaining
79 // completion text as an inlay.
80 break;
81 }
82 }
83 }
84
85 if j == buffer_graphemes.len() && i < completion_graphemes.len() {
86 let offset = snapshot.anchor_after(offset);
87 // there is leftover completion text, so drop it as an inlay.
88 let edit_range = offset..offset;
89 let edit_text = completion_graphemes[i..].join("");
90 edits.push((edit_range, edit_text));
91 }
92
93 InlineCompletion {
94 edits,
95 edit_preview: None,
96 }
97}
98
99impl InlineCompletionProvider for SupermavenCompletionProvider {
100 fn name() -> &'static str {
101 "supermaven"
102 }
103
104 fn display_name() -> &'static str {
105 "Supermaven"
106 }
107
108 fn show_completions_in_menu() -> bool {
109 false
110 }
111
112 fn show_completions_in_normal_mode() -> bool {
113 false
114 }
115
116 fn is_enabled(&self, _buffer: &Entity<Buffer>, _cursor_position: Anchor, cx: &App) -> bool {
117 self.supermaven.read(cx).is_enabled()
118 }
119
120 fn is_refreshing(&self) -> bool {
121 self.pending_refresh.is_some()
122 }
123
124 fn refresh(
125 &mut self,
126 buffer_handle: Entity<Buffer>,
127 cursor_position: Anchor,
128 debounce: bool,
129 cx: &mut Context<Self>,
130 ) {
131 let Some(mut completion) = self.supermaven.update(cx, |supermaven, cx| {
132 supermaven.complete(&buffer_handle, cursor_position, cx)
133 }) else {
134 return;
135 };
136
137 self.pending_refresh = Some(cx.spawn(|this, mut cx| async move {
138 if debounce {
139 cx.background_executor().timer(DEBOUNCE_TIMEOUT).await;
140 }
141
142 while let Some(()) = completion.updates.next().await {
143 this.update(&mut cx, |this, cx| {
144 this.completion_id = Some(completion.id);
145 this.buffer_id = Some(buffer_handle.entity_id());
146 this.file_extension = buffer_handle.read(cx).file().and_then(|file| {
147 Some(
148 Path::new(file.file_name(cx))
149 .extension()?
150 .to_str()?
151 .to_string(),
152 )
153 });
154 this.pending_refresh = None;
155 cx.notify();
156 })?;
157 }
158 Ok(())
159 }));
160 }
161
162 fn cycle(
163 &mut self,
164 _buffer: Entity<Buffer>,
165 _cursor_position: Anchor,
166 _direction: Direction,
167 _cx: &mut Context<Self>,
168 ) {
169 }
170
171 fn accept(&mut self, _cx: &mut Context<Self>) {
172 self.pending_refresh = None;
173 self.completion_id = None;
174 }
175
176 fn discard(&mut self, _cx: &mut Context<Self>) {
177 self.pending_refresh = None;
178 self.completion_id = None;
179 }
180
181 fn suggest(
182 &mut self,
183 buffer: &Entity<Buffer>,
184 cursor_position: Anchor,
185 cx: &mut Context<Self>,
186 ) -> Option<InlineCompletion> {
187 let completion_text = self
188 .supermaven
189 .read(cx)
190 .completion(buffer, cursor_position, cx)?;
191
192 let completion_text = trim_to_end_of_line_unless_leading_newline(completion_text);
193
194 let completion_text = completion_text.trim_end();
195
196 if !completion_text.trim().is_empty() {
197 let snapshot = buffer.read(cx).snapshot();
198 let mut point = cursor_position.to_point(&snapshot);
199 point.column = snapshot.line_len(point.row);
200 let range = cursor_position..snapshot.anchor_after(point);
201 Some(completion_from_diff(
202 snapshot,
203 completion_text,
204 cursor_position,
205 range,
206 ))
207 } else {
208 None
209 }
210 }
211}
212
213fn trim_to_end_of_line_unless_leading_newline(text: &str) -> &str {
214 if has_leading_newline(text) {
215 text
216 } else if let Some(i) = text.find('\n') {
217 &text[..i]
218 } else {
219 text
220 }
221}
222
223fn has_leading_newline(text: &str) -> bool {
224 for c in text.chars() {
225 if c == '\n' {
226 return true;
227 }
228 if !c.is_whitespace() {
229 return false;
230 }
231 }
232 false
233}