Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/prompt_toolkit/document.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,8 +257,11 @@ def _get_char_relative_to_cursor(self, offset: int = 0) -> str:
"""
Return character relative to cursor position, or empty string
"""
index = self.cursor_position + offset
if index < 0:
return ""
try:
return self.text[self.cursor_position + offset]
return self.text[index]
except IndexError:
return ""

Expand Down
21 changes: 21 additions & 0 deletions tests/test_document.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,27 @@ def test_current_char(document):
assert document.char_before_cursor == "n"


@pytest.mark.parametrize(
"text, cursor_position, current_char, char_before_cursor",
[
("", 0, "", ""),
("abc", 0, "a", ""),
("abc", 1, "b", "a"),
("abc", 3, "", "c"),
("a\n", 0, "a", ""),
("a\n", 2, "", "\n"),
("\u03bb", 0, "\u03bb", ""),
("\u03bb", 1, "", "\u03bb"),
],
)
def test_characters_at_document_boundaries(
text, cursor_position, current_char, char_before_cursor
):
document = Document(text, cursor_position)
assert document.current_char == current_char
assert document.char_before_cursor == char_before_cursor


def test_text_before_cursor(document):
assert document.text_before_cursor == "line 1\nlin"

Expand Down
Loading