From d66c4022fbfa39f4fe34db0f2bb6bc40e1ed30b2 Mon Sep 17 00:00:00 2001 From: Sam Roeca Date: Sun, 17 May 2020 15:49:29 -0400 Subject: [PATCH] current_word_range function added to pygls_utils Makes it possible to determine the range of the word under the cursor. --- jedi_language_server/pygls_utils.py | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/jedi_language_server/pygls_utils.py b/jedi_language_server/pygls_utils.py index 7a5f70b..d3e5dd5 100644 --- a/jedi_language_server/pygls_utils.py +++ b/jedi_language_server/pygls_utils.py @@ -5,8 +5,9 @@ import functools +from typing import Optional -from pygls.types import Position +from pygls.types import Position, Range from pygls.workspace import Document _SENTINEL = object() @@ -58,3 +59,25 @@ def char_before_cursor( return document.lines[position.line][position.character - 1] except IndexError: return default + + +def current_word_range( + document: Document, position: Position +) -> Optional[Range]: + """Get the range of the word under the cursor""" + word = document.word_at_position(position) + word_len = len(word) + line: str = document.lines[position.line] + start = 0 + for _ in range(1000): # prevent infinite hanging in case we hit edge case + begin = line.find(word, start) + if begin == -1: + return None + end = begin + word_len + if begin <= position.character <= end: + return Range( + start=Position(line=position.line, character=begin), + end=Position(line=position.line, character=end), + ) + start = end + return None