supermaven_completion_provider.rs

  1use crate::{Supermaven, SupermavenCompletionStateId};
  2use anyhow::Result;
  3use futures::StreamExt as _;
  4use gpui::{AppContext, EntityId, Model, ModelContext, Task};
  5use inline_completion::{Direction, InlineCompletion, InlineCompletionProvider};
  6use language::{language_settings::all_language_settings, 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: Model<Supermaven>,
 19    buffer_id: Option<EntityId>,
 20    completion_id: Option<SupermavenCompletionStateId>,
 21    file_extension: Option<String>,
 22    pending_refresh: Task<Result<()>>,
 23}
 24
 25impl SupermavenCompletionProvider {
 26    pub fn new(supermaven: Model<Supermaven>) -> Self {
 27        Self {
 28            supermaven,
 29            buffer_id: None,
 30            completion_id: None,
 31            file_extension: None,
 32            pending_refresh: Task::ready(Ok(())),
 33        }
 34    }
 35}
 36
 37// Computes the inline completion 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 { edits }
 94}
 95
 96impl InlineCompletionProvider for SupermavenCompletionProvider {
 97    fn name() -> &'static str {
 98        "supermaven"
 99    }
100
101    fn display_name() -> &'static str {
102        "Supermaven"
103    }
104
105    fn show_completions_in_menu() -> bool {
106        false
107    }
108
109    fn is_enabled(&self, buffer: &Model<Buffer>, cursor_position: Anchor, cx: &AppContext) -> bool {
110        if !self.supermaven.read(cx).is_enabled() {
111            return false;
112        }
113
114        let buffer = buffer.read(cx);
115        let file = buffer.file();
116        let language = buffer.language_at(cursor_position);
117        let settings = all_language_settings(file, cx);
118        settings.inline_completions_enabled(language.as_ref(), file.map(|f| f.path().as_ref()), cx)
119    }
120
121    fn refresh(
122        &mut self,
123        buffer_handle: Model<Buffer>,
124        cursor_position: Anchor,
125        debounce: bool,
126        cx: &mut ModelContext<Self>,
127    ) {
128        let Some(mut completion) = self.supermaven.update(cx, |supermaven, cx| {
129            supermaven.complete(&buffer_handle, cursor_position, cx)
130        }) else {
131            return;
132        };
133
134        self.pending_refresh = cx.spawn(|this, mut cx| async move {
135            if debounce {
136                cx.background_executor().timer(DEBOUNCE_TIMEOUT).await;
137            }
138
139            while let Some(()) = completion.updates.next().await {
140                this.update(&mut cx, |this, cx| {
141                    this.completion_id = Some(completion.id);
142                    this.buffer_id = Some(buffer_handle.entity_id());
143                    this.file_extension = buffer_handle.read(cx).file().and_then(|file| {
144                        Some(
145                            Path::new(file.file_name(cx))
146                                .extension()?
147                                .to_str()?
148                                .to_string(),
149                        )
150                    });
151                    cx.notify();
152                })?;
153            }
154            Ok(())
155        });
156    }
157
158    fn cycle(
159        &mut self,
160        _buffer: Model<Buffer>,
161        _cursor_position: Anchor,
162        _direction: Direction,
163        _cx: &mut ModelContext<Self>,
164    ) {
165    }
166
167    fn accept(&mut self, _cx: &mut ModelContext<Self>) {
168        self.pending_refresh = Task::ready(Ok(()));
169        self.completion_id = None;
170    }
171
172    fn discard(&mut self, _cx: &mut ModelContext<Self>) {
173        self.pending_refresh = Task::ready(Ok(()));
174        self.completion_id = None;
175    }
176
177    fn suggest(
178        &mut self,
179        buffer: &Model<Buffer>,
180        cursor_position: Anchor,
181        cx: &mut ModelContext<Self>,
182    ) -> Option<InlineCompletion> {
183        let completion_text = self
184            .supermaven
185            .read(cx)
186            .completion(buffer, cursor_position, cx)?;
187
188        let completion_text = trim_to_end_of_line_unless_leading_newline(completion_text);
189
190        let completion_text = completion_text.trim_end();
191
192        if !completion_text.trim().is_empty() {
193            let snapshot = buffer.read(cx).snapshot();
194            let mut point = cursor_position.to_point(&snapshot);
195            point.column = snapshot.line_len(point.row);
196            let range = cursor_position..snapshot.anchor_after(point);
197            Some(completion_from_diff(
198                snapshot,
199                completion_text,
200                cursor_position,
201                range,
202            ))
203        } else {
204            None
205        }
206    }
207}
208
209fn trim_to_end_of_line_unless_leading_newline(text: &str) -> &str {
210    if has_leading_newline(text) {
211        text
212    } else if let Some(i) = text.find('\n') {
213        &text[..i]
214    } else {
215        text
216    }
217}
218
219fn has_leading_newline(text: &str) -> bool {
220    for c in text.chars() {
221        if c == '\n' {
222            return true;
223        }
224        if !c.is_whitespace() {
225            return false;
226        }
227    }
228    false
229}