Skip to content

Commit

Permalink
Add Document.get_index(location)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidbrochart committed Sep 27, 2023
1 parent d766bb9 commit 92da0cf
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/textual/document/_document.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,18 @@ def text(self) -> str:
def newline(self) -> Newline:
"""Return the line separator used in the document."""

@abstractmethod
def get_index(self, at: Location) -> int:
"""Given a location in the document, returns the index
in the document seen as a flat string.
Args:
at: The location in the document.
Returns:
The index in the document seen as a flat string.
"""

@abstractmethod
def get_line(self, index: int) -> str:
"""Returns the line with the given index from the document.
Expand Down Expand Up @@ -320,6 +332,22 @@ def line_count(self) -> int:
"""Returns the number of lines in the document."""
return len(self._lines)

def get_index(self, at: Location) -> int:
"""Given a location in the document, returns the index
in the document seen as a flat string.
Args:
at: The location in the document.
Returns:
The index in the document seen as a flat string.
"""
row, col = at
idx = row * len(self.newline) + col
for i in range(row):
idx += len(self.get_line(i))
return idx

def get_line(self, index: int) -> str:
"""Returns the line with the given index from the document.
Expand Down

0 comments on commit 92da0cf

Please sign in to comment.