editor: Do not show document highlights when selection is spanned more than word (#30602)

Smit Barmase created

Closes #27743

This PR prevents document highlighting when selection start and
selection end do not point to the same word. This is useful in cases
when you select multiple lines or multiple words, in which case you
don't really care about these LSP-specific highlights. This is the same
behavior as VSCode.


https://github.com/user-attachments/assets/f80d6ca3-d5c8-4d7b-9281-c1d6dc6a6e7b

Release Notes:

- Fixed document highlight behavior so it no longer appears when
selecting multiple words or lines, making text selection and selection
highlights more clearer.

Change summary

crates/editor/src/editor.rs | 14 +++++++++++++-
1 file changed, 13 insertions(+), 1 deletion(-)

Detailed changes

crates/editor/src/editor.rs 🔗

@@ -5758,10 +5758,22 @@ impl Editor {
         let cursor_position = newest_selection.head();
         let (cursor_buffer, cursor_buffer_position) =
             buffer.text_anchor_for_position(cursor_position, cx)?;
-        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
+        let (tail_buffer, tail_buffer_position) =
+            buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
         if cursor_buffer != tail_buffer {
             return None;
         }
+
+        let snapshot = cursor_buffer.read(cx).snapshot();
+        let (start_word_range, _) = snapshot.surrounding_word(cursor_buffer_position);
+        let (end_word_range, _) = snapshot.surrounding_word(tail_buffer_position);
+        if start_word_range != end_word_range {
+            self.document_highlights_task.take();
+            self.clear_background_highlights::<DocumentHighlightRead>(cx);
+            self.clear_background_highlights::<DocumentHighlightWrite>(cx);
+            return None;
+        }
+
         let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
         self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
             cx.background_executor()