Skip to content
Draft
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
9 changes: 9 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@
_Notes on the upcoming release will go here._
<!-- END PLACEHOLDER - ADD NEW CHANGELOG ENTRIES BELOW THIS LINE -->

### What's new

#### Find snapshot text by cell coordinates (#133)

{meth}`~libvt.terminal.Snapshot.find_cells` returns each visible match as a
{class}`~libvt.terminal.CellSpan` with a row and a half-open column range.
Use the coordinates to click or inspect labels that include wide or
combined graphemes.

## libvt 0.0.1a5 (2026-11-30)

`libvt` 0.0.1a5 adds rectangular grid blitting, display-column text writes, and
Expand Down
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,13 @@ styles:
r0[0..11]: bold fg=green
>>> snap.viewport(offset=1).lines
('booting', 'Loading 20%')
>>> snap.find_cells("done")
(CellSpan(row=1, start=0, stop=4),)
```

Use [`Snapshot.find_cells()`][find_cells] to turn a visible label into cell
coordinates for a click, highlight, or assertion.

### Assert screen boxes inline

Most unit tests can stop at [`assert_screen_box()`][assert_screen_box], which
Expand Down Expand Up @@ -212,6 +217,7 @@ guides and API reference are at [libvt.git-pull.com](https://libvt.git-pull.com/
MIT License. See [LICENSE](LICENSE).

[feed]: https://libvt.git-pull.com/api/terminal/#libvt.terminal.Terminal.feed
[find_cells]: docs/topics/snapshots.md#locate-text-by-cell-coordinates
[committed]: https://libvt.git-pull.com/api/terminal/#libvt.terminal.Terminal.committed
[viewport]: https://libvt.git-pull.com/api/terminal/#libvt.terminal.Snapshot.viewport
[assert_screen_box]: https://libvt.git-pull.com/api/testing/#libvt.testing.assert_screen_box
Expand Down
3 changes: 2 additions & 1 deletion docs/project/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ Import specialized types and helpers from their owning submodules:
- {mod}`libvt.parser`, {mod}`libvt.screen`, and {mod}`libvt.terminal` —
streaming VT500 parser, screen grid views, incremental
{class}`~libvt.terminal.SyncToken` / {class}`~libvt.terminal.ScreenDelta`
replicas, and {class}`~libvt.terminal.Formatter`
replicas, {class}`~libvt.terminal.CellSpan` coordinates, and
{class}`~libvt.terminal.Formatter`
- {mod}`libvt.input`, {mod}`libvt.aio`, and {mod}`libvt.codec` — mode-aware
input encoders, {class}`~libvt.aio.AsyncSession` transports, and sequence
disassembly
Expand Down
19 changes: 19 additions & 0 deletions docs/topics/snapshots.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,25 @@ styles:
r0[0..2]: bold fg=green
```

## Locate text by cell coordinates

Use {meth}`~libvt.terminal.Snapshot.find_cells` to locate a label in the active
viewport. Each {class}`~libvt.terminal.CellSpan` gives a zero-based row and a
half-open column range. Use the start column for a
{class}`~libvt.input.MouseEvent`, or slice the snapshot with both columns.

```python
>>> from libvt import Terminal
>>> from libvt.input import MouseAction, MouseButton, MouseEvent
>>> term = Terminal(rows=2, cols=16)
>>> term.feed("\x1b[?1000;1006h界界界·Go".encode())
>>> (hit,) = term.committed.find_cells("Go")
>>> hit
CellSpan(row=0, start=7, stop=9)
>>> term.encode(MouseEvent(MouseButton.LEFT, MouseAction.PRESS, hit.row, hit.start))
b'\x1b[<0;8;1M'
```

## Stateless scrollback paging (`viewport()`)

Primary-screen snapshots retain frozen scrollback alongside the active
Expand Down
78 changes: 78 additions & 0 deletions src/libvt/terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -665,6 +665,24 @@ def _make_snapshot(
return snap


class CellSpan(t.NamedTuple):
"""Half-open cell range on one snapshot row.

Attributes
----------
row : int
Zero-based viewport row.
start : int
Inclusive zero-based column.
stop : int
Exclusive zero-based column.
"""

row: int
start: int
stop: int


class Snapshot:
r"""Immutable point-in-time capture of terminal screen, history, and metadata.

Expand Down Expand Up @@ -997,6 +1015,65 @@ def viewport(self, offset: int = 0) -> RegionView:
out_rows.extend(self._rows[: win_stop - h_len])
return RegionView(out_rows, range(cols))

def find_cells(self, text: str, /) -> tuple[CellSpan, ...]:
r"""Find exact text matches by cell in the active viewport.

Return zero-based, half-open spans in row and column order, including
overlaps. An empty tuple means no match. Search each row separately,
including soft-wrapped rows. Matches span complete stored graphemes
without normalization. Wide glyphs occupy two columns. Search skips
clipped wide glyphs, wrap spacers, and unwritten trailing padding.
Explicit trailing spaces and blanks before later text can match.

Parameters
----------
text : str
Literal text to match within a single row.

Returns
-------
tuple[CellSpan, ...]
Matching row and column spans in the active viewport.

Raises
------
ValueError
If *text* is empty or contains a carriage return or newline.
"""
if not text or "\r" in text or "\n" in text:
msg = "text must be nonempty and contain no carriage returns or newlines"
raise ValueError(msg)

matches: list[CellSpan] = []
for row_idx, row in enumerate(self._rows):
line = row.rstrip_text()
at = line.find(text)
if at < 0:
continue

columns = {0: 0}
col = offset = 0
limit = row.text_used
while col < limit:
grapheme = row.char_at(col)
if not grapheme:
# Wide continuations are skipped. A wrap spacer ends the row.
break
role = raw_width_bits(row.attr_at(col))
col += 2 if role == WidthRole.WIDE else 1
if col > limit:
break
offset += len(grapheme)
columns[offset] = col

while at >= 0:
end = at + len(text)
if at in columns and end in columns:
matches.append(CellSpan(row_idx, columns[at], columns[end]))
at = line.find(text, at + 1)

return tuple(matches)

@property
def lines(self) -> tuple[str, ...]:
r"""Return visible row text with unwritten trailing blank cells omitted.
Expand Down Expand Up @@ -7200,6 +7277,7 @@ def strip(data: collections.abc.Buffer | str, /) -> str:


__all__ = [
"CellSpan",
"FlightRecorder",
"Formatter",
"OutputFormat",
Expand Down
41 changes: 41 additions & 0 deletions tests/test_aio.py
Original file line number Diff line number Diff line change
Expand Up @@ -485,3 +485,44 @@ def write_eof(self) -> None:
_TlsNoEofWriter(),
) as tls_stream:
tls_stream.write_eof()


@pytest.mark.skipif(sys.platform == "win32", reason="POSIX pty required")
async def test_snapshot_find_cells_clicks_child_target() -> None:
"""The child observes a different selection from a string-index click."""
child = r"""
import sys

out = sys.stdout.buffer
out.write("\x1b[?1000;1006h\x1b[2;1H界界e\u0301界·Go".encode())
for _ in range(2):
packet = bytearray()
while (byte := sys.stdin.buffer.read(1)) != b"M":
if not byte:
raise EOFError("incomplete mouse event")
packet.extend(byte)
button, column, row = map(int, packet.removeprefix(b"\x1b[<").split(b";"))
assert button == 0
choice = "Ferry" if (row, column) == (2, 9) else "Harbor"
out.write(f"\x1b[3;1HACK {choice} row={row} col={column}\r\nDONE".encode())
"""
async with open_pty(
(sys.executable, "-u", "-c", child), tty_mode="raw", rows=5, cols=32
) as session:
snap = await session.wait_for("Go", timeout=5)
(hit,) = snap.find_cells("Go")

session.send_event(
MouseEvent(MouseButton.LEFT, MouseAction.PRESS, hit.row, hit.start)
)
selected = await session.wait_for(
lambda view: view.lines[2].startswith("ACK ") and view.lines[3] == "DONE",
timeout=5,
)
assert selected.lines[2] == "ACK Ferry row=2 col=9"

text_index = snap.lines[hit.row].index("Go")
session.send_event(
MouseEvent(MouseButton.LEFT, MouseAction.PRESS, hit.row, text_index)
)
await session.wait_for("ACK Harbor row=2 col=7", timeout=5)
44 changes: 44 additions & 0 deletions tests/test_terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -1173,3 +1173,47 @@ def test_committed_appearance_sync_hold_set_theme_2031_and_decsnm() -> None:
term.feed(b"\x1bc")
assert term.modes.is_set(Mode.DECSCNM) is False
assert term.appearance.scheme == ColorScheme.LIGHT


def test_snapshot_find_cells_matches_complete_graphemes_and_overlaps() -> None:
"""Search the captured rows in order, with offsets at cell boundaries."""
term = libvt.Terminal(rows=3, cols=12)
term.feed("界界界\r\ne\u0301👩\u200d🚀Go Go\r\nGo".encode())
snap = term.committed

assert snap.find_cells("界界") == ((0, 0, 4), (0, 2, 6))
assert snap.find_cells("Go") == ((1, 3, 5), (1, 6, 8), (2, 0, 2))
assert snap.find_cells("e\u0301👩\u200d🚀") == ((1, 0, 3),)
for text in ("e", "\u0301", "é", "👩", "🚀", "界e", "missing"):
assert snap.find_cells(text) == ()
for text in ("", "Go\nGo", "Go\rGo"):
with pytest.raises(ValueError, match="nonempty"):
snap.find_cells(text)

term.feed(b"\x1b[2J")
assert term.committed.find_cells("Go") == ()
assert len(snap.find_cells("Go")) == 3


def test_snapshot_find_cells_excludes_padding_and_split_wide_cells() -> None:
"""Search written row extents across wrapping, resizing, and scrollback."""
term = libvt.Terminal(rows=2, cols=4)
term.feed("abc界 ".encode())
snap = term.committed
assert snap[0, 3].width_role is WidthRole.SPACER_HEAD
assert snap.find_cells(" ") == ((1, 2, 3),)
assert snap.find_cells("界 ") == ((1, 0, 3),)
assert snap.find_cells("c界") == ()

term.resize(rows=2, cols=1, reflow=False)
snap = term.committed
assert snap.find_cells("界") == ()
assert snap.find_cells(" ") == ()

term = libvt.Terminal(rows=1, cols=8)
term.feed(b"past\r\n\x1b[3GGo\x1b[41m\x1b[K")
snap = term.committed
assert snap.history[0].text == "past"
assert snap.find_cells("past") == ()
assert snap.find_cells(" Go") == ((0, 0, 4),)
assert snap.find_cells("Go ") == ()
Loading