From da81ff32957291cb350b1f1936b32919db6cda2e Mon Sep 17 00:00:00 2001 From: Antonio Scandurra Date: Mon, 27 Mar 2023 18:36:56 +0200 Subject: [PATCH] Optimize `CopilotState::text_for_active_completion` --- crates/editor/src/editor.rs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs index fca4321422..6b47034674 100644 --- a/crates/editor/src/editor.rs +++ b/crates/editor/src/editor.rs @@ -1030,21 +1030,22 @@ impl CopilotState { cursor: Anchor, buffer: &MultiBufferSnapshot, ) -> Option<&str> { + let cursor_offset = cursor.to_offset(buffer); let completion = self.completions.get(self.active_completion_index)?; if self.position.excerpt_id == cursor.excerpt_id && self.position.buffer_id == cursor.buffer_id - && buffer.chars_at(cursor).next().map_or(true, |ch| ch == '\n') + && (cursor_offset == buffer.len() || buffer.contains_str_at(cursor_offset, "\n")) { - let completion_position = Anchor { + let completion_offset = buffer.summary_for_anchor(&Anchor { excerpt_id: self.position.excerpt_id, buffer_id: self.position.buffer_id, text_anchor: completion.position, - }; - if completion_position.cmp(&cursor, buffer).is_le() { - let prefix = buffer - .text_for_range(completion_position..cursor) - .collect::(); - let suffix = completion.text.strip_prefix(&prefix)?; + }); + let common_prefix_len = cursor_offset.saturating_sub(completion_offset); + if common_prefix_len <= completion.text.len() + && buffer.contains_str_at(completion_offset, &completion.text[..common_prefix_len]) + { + let suffix = &completion.text[common_prefix_len..]; if !suffix.is_empty() { return Some(suffix); }