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
12 changes: 6 additions & 6 deletions src/prompt_toolkit/document.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,16 +325,16 @@ def translate_row_col_to_index(self, row: int, col: int) -> int:

Negative row/col values are turned into zero.
"""
# Clamp before indexing. A negative row is a valid list index and
# would otherwise select a line from the end of the document.
if row < 0:
row = 0
try:
result = self._line_start_indexes[row]
line = self.lines[row]
except IndexError:
if row < 0:
result = self._line_start_indexes[0]
line = self.lines[0]
else:
result = self._line_start_indexes[-1]
line = self.lines[-1]
result = self._line_start_indexes[-1]
line = self.lines[-1]

result += max(0, min(col, len(line)))

Expand Down
9 changes: 9 additions & 0 deletions tests/test_document.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,15 @@ def test_translate_index_to_position(document):
assert pos == (0, 0)


def test_translate_row_col_to_index_clamps_negative_row():
# Negative rows are documented to become zero. List indexing would
# otherwise select lines from the end of the document.
document = Document("one\ntwo\nthree")
for row in (-1, -2, -3, -4):
assert document.translate_row_col_to_index(row, 0) == 0
assert document.translate_row_col_to_index(-1, 1) == 1


def test_is_cursor_at_the_end(document):
assert Document("hello", 5).is_cursor_at_the_end
assert not Document("hello", 4).is_cursor_at_the_end
Expand Down
Loading