diff --git a/src/ptpython/completer.py b/src/ptpython/completer.py index 40701ca..b15e385 100644 --- a/src/ptpython/completer.py +++ b/src/ptpython/completer.py @@ -130,10 +130,10 @@ def double_quoted_wrapper(text: str) -> str: ) def _complete_path_while_typing(self, document: Document) -> bool: - char_before_cursor = document.char_before_cursor + text = document.text_before_cursor + char_before_cursor = text[-1:] return bool( - document.text - and (char_before_cursor.isalnum() or char_before_cursor in "/.~") + text and (char_before_cursor.isalnum() or char_before_cursor in "/.~") ) def _complete_python_while_typing(self, document: Document) -> bool: diff --git a/src/ptpython/utils.py b/src/ptpython/utils.py index 92cfc2a..4b40a71 100644 --- a/src/ptpython/utils.py +++ b/src/ptpython/utils.py @@ -59,7 +59,7 @@ def has_unclosed_brackets(text: str) -> bool: def get_jedi_script_from_document( document: Document, locals: dict[str, Any], globals: dict[str, Any] -) -> Interpreter: +) -> Interpreter | None: import jedi # We keep this import in-line, to improve start-up time. # Importing Jedi is 'slow'. diff --git a/tests/test_completer_utils.py b/tests/test_completer_utils.py new file mode 100644 index 0000000..b75203c --- /dev/null +++ b/tests/test_completer_utils.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +from prompt_toolkit.document import Document + +from ptpython.completer import PythonCompleter +from ptpython.utils import get_jedi_script_from_document + + +def test_complete_path_while_typing_empty_or_whitespace() -> None: + completer = PythonCompleter( + get_globals=lambda: {}, + get_locals=lambda: {}, + enable_dictionary_completion=lambda: True, + ) + # Empty document. + assert completer._complete_path_while_typing(Document("")) is False + # Whitespace-only. + assert completer._complete_path_while_typing(Document(" ")) is False + # Newline-only. + assert completer._complete_path_while_typing(Document("\n")) is False + # Cursor at start of non-empty text. + assert completer._complete_path_while_typing(Document("hello/", cursor_position=0)) is False + + +def test_complete_path_while_typing_valid_paths() -> None: + completer = PythonCompleter( + get_globals=lambda: {}, + get_locals=lambda: {}, + enable_dictionary_completion=lambda: True, + ) + assert completer._complete_path_while_typing(Document("hello/")) is True + assert completer._complete_path_while_typing(Document("~/")) is True + assert completer._complete_path_while_typing(Document("./")) is True + + +def test_get_jedi_script_from_document_return_annotation() -> None: + assert get_jedi_script_from_document.__annotations__["return"] == "Interpreter | None"