From 76c099235b37fce974c516a0d522b4cce2efc07a Mon Sep 17 00:00:00 2001 From: Ted Conbeer Date: Fri, 19 Apr 2024 08:39:34 -0600 Subject: [PATCH] fix: make Document.end zero-indexed (#4427) Co-authored-by: Darren Burns --- CHANGELOG.md | 6 ++++++ src/textual/document/_document.py | 2 +- tests/document/test_document.py | 13 +++++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cd0139a5ef..cd62457fa5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## Unreleased + +### Fixed + +- Fixed an off-by-one error in the line number of the `Document.end` property https://github.com/Textualize/textual/issues/4426 + ## [0.57.0] - 2024-04-19 ### Fixed 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)