From 26ef16199f689746998a526725a491fbb05fe45b Mon Sep 17 00:00:00 2001 From: Ted Conbeer Date: Thu, 18 Apr 2024 18:23:15 +0000 Subject: [PATCH] fix: make Document.end zero-indexed --- CHANGELOG.md | 1 + src/textual/document/_document.py | 2 +- tests/document/test_document.py | 13 +++++++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6327789eeb..a6f1f39872 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Fixed `Integer` validator missing failure description when not a number https://github.com/Textualize/textual/issues/4413 - Fixed a crash in `DataTable` if you clicked a link in the border https://github.com/Textualize/textual/issues/4410 +- Fixed an off-by-one error in the line number of the `Document.end` property https://github.com/Textualize/textual/issues/4426 ### Added diff --git a/src/textual/document/_document.py b/src/textual/document/_document.py index ca850285b5..4a63ff2054 100644 --- a/src/textual/document/_document.py +++ b/src/textual/document/_document.py @@ -351,7 +351,7 @@ def start(self) -> Location: def end(self) -> Location: """Returns the location of the end of the document.""" last_line = self._lines[-1] - return (self.line_count, len(last_line)) + return (self.line_count - 1, len(last_line)) def get_index_from_location(self, location: Location) -> int: """Given a location, returns the index from the document's text. diff --git a/tests/document/test_document.py b/tests/document/test_document.py index ad1c82b834..ebf8474c8e 100644 --- a/tests/document/test_document.py +++ b/tests/document/test_document.py @@ -137,3 +137,16 @@ def test_location_from_index(text): len(lines) - 1, len(lines[-1]), ) + + +@pytest.mark.parametrize( + "text", [TEXT, TEXT_NEWLINE, TEXT_WINDOWS, TEXT_WINDOWS_NEWLINE] +) +def test_document_end(text): + """The location is always what we expect.""" + document = Document(text) + expected_line_number = ( + len(text.splitlines()) if text.endswith("\n") else len(text.splitlines()) - 1 + ) + expected_pos = 0 if text.endswith("\n") else (len(text.splitlines()[-1])) + assert document.end == (expected_line_number, expected_pos)