Skip to content
Merged
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
24 changes: 24 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,16 @@ and {meth}`~libvt.contrib.syrupy.VtSnapshotExtension.configure` accept
of a drive letter. Use an explicit regex for paths inside URIs. When using
`region=`, pass the source frame to account for cropped URI text.

#### Read soft-wrapped rows as logical lines (#152)

Use {attr}`~libvt.terminal.Snapshot.unwrapped_text`,
{attr}`~libvt.terminal.Terminal.unwrapped_text`,
{attr}`~libvt.screen.Screen.unwrapped_text`, or
{attr}`~libvt.screen.RegionView.unwrapped_text` to join soft wraps while
retaining hard line breaks. Pass `unwrap=True` to
{meth}`~libvt.terminal.Snapshot.format`, {class}`~libvt.terminal.Formatter`,
or {func}`libvt.render <libvt.terminal.render>` for plain text or HTML.

### Fixes

#### Diagnose a bare PTY command (#165)
Expand Down Expand Up @@ -375,6 +385,20 @@ admits more than one cell layout. Review the changed output and update
affected expectations with
`pytest --snapshot-update`.

#### Match logical lines in terminal waits (#152)

{meth}`~libvt.aio.AsyncTerminalStream.wait_for` and
{meth}`~libvt.aio.PtySession.wait_for` match strings across soft wraps.
To match physical rows, pass a callable that inspects the captured text.

```python
# Before
await session.wait_for("hello wo\nrld")

# After
await session.wait_for(lambda snap: "hello wo\nrld" in snap.text)
```

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

`libvt` 0.0.1a5 adds rectangular grid blitting, display-column text writes, and
Expand Down
15 changes: 15 additions & 0 deletions MIGRATION
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,21 @@ frames with supported key paths in separate sections. Frames with ambiguous
display columns record those columns in a footer. Review the diff and
regenerate affected `.ambr` expectations with `pytest --snapshot-update`.

### String predicates match logical lines (#152)

{meth}`~libvt.aio.AsyncTerminalStream.wait_for` and
{meth}`~libvt.aio.PtySession.wait_for` match strings against
{attr}`~libvt.terminal.Snapshot.unwrapped_text`. Replace a string that includes
a soft-wrap boundary with a callable that inspects the physical rows.

```python
# Before
await session.wait_for("hello wo\nrld")

# After
await session.wait_for(lambda snap: "hello wo\nrld" in snap.text)
```

## libvt 0.0.1a2 (2026-11-28)

### Curated PEP 562 `libvt` root exports (#43)
Expand Down
14 changes: 9 additions & 5 deletions docs/topics/snapshots.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,11 @@ A `Snapshot` supports the same zero-based `(row, col)` indexing and slicing as
- `snap[r0:r1, c0:c1]` returns a rectangular {class}`~libvt.screen.RegionView`
that also serializes directly as a sub-grid box.
- {attr}`~libvt.terminal.Snapshot.lines` omits unwritten trailing blank cells,
whereas {attr}`~libvt.terminal.Snapshot.display_lines` pads every row to full
column width with spaces (clipping split wide characters cleanly at slice
edges):
{attr}`~libvt.terminal.Snapshot.display_lines` pads every row to full column
width with spaces (clipping split wide characters cleanly at slice edges),
and {attr}`~libvt.terminal.Snapshot.unwrapped_text` (along with full-width
{attr}`~libvt.screen.RegionView.unwrapped_text` slices) joins soft-wrapped
continuation rows while preserving hard linebreaks (`"\n"`):

```python
>>> import libvt
Expand Down Expand Up @@ -214,8 +216,10 @@ generation ({attr}`~libvt.terminal.Snapshot.cursor`,
{attr}`~libvt.terminal.Snapshot.appearance`, and
{attr}`~libvt.terminal.Snapshot.placements`), renders to plain text, VT escape
sequences, or HTML via {meth}`~libvt.terminal.Snapshot.format` and
{class}`~libvt.terminal.OutputFormat`, and exports a deterministic
JSON-compatible dictionary via {meth}`~libvt.terminal.Snapshot.to_dict`:
{class}`~libvt.terminal.OutputFormat` (passing `unwrap=True` to join
soft-wrapped rows onto a single line in `PLAIN` and `HTML`), and exports a
deterministic JSON-compatible dictionary via
{meth}`~libvt.terminal.Snapshot.to_dict`:

```python
>>> import libvt
Expand Down
11 changes: 7 additions & 4 deletions docs/topics/sync-and-asyncio.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,13 @@ stream, pass a configured {class}`~libvt.terminal.Terminal` to
{meth}`AsyncTerminalStream.wait_for() <libvt.aio.AsyncTerminalStream.wait_for>`
and {meth}`PtySession.wait_for() <libvt.aio.PtySession.wait_for>` test a
substring or callable predicate against the current committed snapshot,
then at synchronized frame and read boundaries. An unclosed `?2026` hold
expires after `sync_timeout` seconds. On timeout or premature EOF, both
raise {exc}`~libvt.exc.TerminalTimeoutError` with the boxed screen and
recent decoded input attached via `__notes__`:
then at synchronized frame and read boundaries, expiring unclosed `?2026`
holds after `sync_timeout` seconds. String predicates search
{attr}`~libvt.terminal.Snapshot.unwrapped_text`. Hard linebreaks stay `"\n"`.
Pass a callable using {attr}`~libvt.terminal.Snapshot.text` to match physical
rows. On timeout or premature EOF, both raise
{exc}`~libvt.exc.TerminalTimeoutError` with the
boxed screen and recent decoded input attached via `__notes__`:

```python
>>> import asyncio
Expand Down
34 changes: 25 additions & 9 deletions src/libvt/aio.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,11 @@ async def wait_for(
timeout: float = 2.0,
attach_note: bool = True,
) -> Snapshot:
"""Wait until *predicate* matches a committed ``Snapshot``."""
r"""Wait until *predicate* matches a committed ``Snapshot``.

``str`` predicates match against ``snapshot.unwrapped_text``. Pass a
callable using ``snapshot.text`` to test physical rows.
"""

async def aclose(self) -> object:
"""Close the session and expire any active ``?2026`` hold."""
Expand All @@ -314,6 +318,14 @@ def _write_aborted() -> OSError:
return OSError(errno.ECANCELED, message)


def _snapshot_matches(
snapshot: Snapshot, predicate: collections.abc.Callable[[Snapshot], bool] | str
) -> bool:
if isinstance(predicate, str):
return predicate in snapshot.unwrapped_text
return predicate(snapshot)


def _validate_nonneg_seconds(value: float, name: str) -> None:
if (
isinstance(value, bool)
Expand Down Expand Up @@ -1381,13 +1393,16 @@ async def wait_for(
timeout: float = 2.0,
attach_note: bool = True,
) -> Snapshot:
"""Wait until *predicate* matches :class:`~libvt.terminal.Snapshot`.
r"""Wait until *predicate* matches :class:`~libvt.terminal.Snapshot`.

Parameters
----------
predicate : collections.abc.Callable[[Snapshot], bool] | str
Callable evaluated in the waiting task at read and synchronized
frame boundaries, or a substring searched inside ``snapshot.text``.
frame boundaries, or a substring matched against
:attr:`~libvt.terminal.Snapshot.unwrapped_text` across soft-wrapped
rows. Hard linebreaks remain ``"\n"``. Use a callable with
:attr:`~libvt.terminal.Snapshot.text` to match physical rows.
timeout : float
Maximum wait duration in seconds before raising
:exc:`~libvt.exc.TerminalTimeoutError`.
Expand All @@ -1407,9 +1422,8 @@ async def wait_for(
expires.
"""
_validate_nonneg_seconds(timeout, "timeout")

check = (
(lambda snap: predicate in snap.text)
(lambda snap: _snapshot_matches(snap, predicate))
if isinstance(predicate, str)
else predicate
)
Expand Down Expand Up @@ -1972,13 +1986,16 @@ async def wait_for(
timeout: float = 2.0,
attach_note: bool = True,
) -> Snapshot:
"""Wait until *predicate* matches :class:`~libvt.terminal.Snapshot`.
r"""Wait until *predicate* matches :class:`~libvt.terminal.Snapshot`.

Parameters
----------
predicate : collections.abc.Callable[[Snapshot], bool] | str
Callable evaluated in the waiting task at read and synchronized
frame boundaries, or a substring searched inside ``snapshot.text``.
frame boundaries, or a substring matched against
:attr:`~libvt.terminal.Snapshot.unwrapped_text` across soft-wrapped
rows. Hard linebreaks remain ``"\n"``. Use a callable with
:attr:`~libvt.terminal.Snapshot.text` to match physical rows.
timeout : float
Maximum wait duration in seconds before raising
:exc:`~libvt.exc.TerminalTimeoutError`.
Expand All @@ -1997,9 +2014,8 @@ async def wait_for(
If the PTY reaches EOF/close before matching or *timeout* expires.
"""
_validate_nonneg_seconds(timeout, "timeout")

check = (
(lambda snap: predicate in snap.text)
(lambda snap: _snapshot_matches(snap, predicate))
if isinstance(predicate, str)
else predicate
)
Expand Down
127 changes: 125 additions & 2 deletions src/libvt/screen.py
Original file line number Diff line number Diff line change
Expand Up @@ -908,6 +908,34 @@ def text(self) -> str:
lines.pop()
return "\n".join(lines)

@property
def unwrapped_text(self) -> str:
r"""Return newline-joined text, unwrapping full-width soft-wrapped rows.

Full-width row slices (such as ``snap[0:5]`` or
:meth:`~libvt.terminal.Snapshot.viewport`) join contiguous
``row.wrapped`` rows without ``"\n"`` when their original right margin
is visible. The current frame determines
the slice width even when history contains rows sealed at a different
width. Column crops return :attr:`text`.

Examples
--------
>>> term = Terminal(rows=3, cols=8)
>>> term.feed(b"hello world\r\nok")
>>> snap = term.committed
>>> snap[0:2].unwrapped_text, snap[0:2, 0:4].unwrapped_text
('hello world', 'hell\nrld')
"""
columns = self.columns
if (
columns.start == 0
and columns.step == 1
and columns.stop >= self._source_width()
):
return _unwrapped_text(self._rows, visible_cols=len(columns))
return self.text

def __iter__(self) -> collections.abc.Iterator[RowView]:
"""Iterate over rows using the current rectangular extent."""
columns = self.columns
Expand Down Expand Up @@ -949,8 +977,87 @@ def __getitem__(
)


def format_rows_text(rows: collections.abc.Sequence[RowLike]) -> str:
"""Format *rows* as newline-joined text omitting trailing blank lines."""
def _row_groups(
rows: collections.abc.Sequence[RowLike],
*,
unwrap: bool,
visible_cols: int | None = None,
) -> collections.abc.Iterator[collections.abc.Sequence[RowLike]]:
start = 0
for end, row in enumerate(rows, 1):
if (
not unwrap
or not row.wrapped
or (visible_cols is not None and row.cols > visible_cols)
):
yield rows[start:end]
start = end
if start < len(rows):
yield rows[start:]


def _unwrapped_rows(
group: collections.abc.Sequence[RowLike], *, include_styles: bool
) -> collections.abc.Iterator[tuple[RowLike, int]]:
end = len(group)
while end > 0:
last = group[end - 1]
used = last.used if include_styles else last.text_used
if used:
break
end -= 1

for index, row in enumerate(group[:end]):
padding = 0
if index + 1 < end:
used = row.used if include_styles else row.text_used
# The high-water marks count the wide-wrap spacer at the right edge.
padding = max(0, row.cols - used)
yield row, padding


def _unwrapped_text(
rows: collections.abc.Sequence[RowLike], *, visible_cols: int | None = None
) -> str:
lines = (
"".join(
row.rstrip_text() + " " * padding
for row, padding in _unwrapped_rows(group, include_styles=False)
)
for group in _row_groups(rows, unwrap=True, visible_cols=visible_cols)
)
return "\n".join(lines).rstrip("\n")


def format_rows_text(
rows: collections.abc.Sequence[RowLike],
*,
unwrap: bool = False,
) -> str:
r"""Format *rows* as newline-joined text omitting trailing blank lines.

Parameters
----------
rows : collections.abc.Sequence[RowLike]
Viewport or scrollback rows to format.
unwrap : bool
When ``True``, join contiguous ``row.wrapped`` continuation rows onto
the same logical line without inserting ``"\n"``.

Returns
-------
str
Rendered text with trailing blank lines omitted.

Examples
--------
>>> term = Terminal(rows=2, cols=8)
>>> term.feed(b"hello world")
>>> term.screen.text, term.screen.unwrapped_text
('hello wo\nrld', 'hello world')
"""
if unwrap:
return _unwrapped_text(rows)
lines = [r.rstrip_text() for r in rows]
while lines and lines[-1] == "":
lines.pop()
Expand Down Expand Up @@ -1338,6 +1445,22 @@ def text(self) -> str:
"""Return visible screen text with trailing blank rows omitted."""
return format_rows_text(self._rows)

@property
def unwrapped_text(self) -> str:
r"""Return visible screen text with soft-wrapped rows joined.

Contiguous ``row.wrapped`` rows join without ``"\n"`` while hard
linebreaks stay ``"\n"`` and trailing blank rows are omitted.

Examples
--------
>>> term = Terminal(rows=3, cols=8)
>>> term.feed(b"hello world\r\nok")
>>> term.screen.unwrapped_text
'hello world\nok'
"""
return format_rows_text(self._rows, unwrap=True)

@t.overload
def __getitem__(self, key: int) -> RowView: ...

Expand Down
Loading
Loading