From a56945af0c6085a8032eec6a0387a3d2e1247d10 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Wed, 2 Dec 2026 03:14:42 -0600 Subject: [PATCH 1/5] aio(fix[wait]): Match soft-wrapped text why: Long diagnostics must match string predicates even when terminal width wraps a word. what: - Expose soft-wrap-aware text in the screen and formatter - Check logical substrings in async stream and PTY waits - Cover wide wrapping and visible column gaps --- docs/topics/snapshots.md | 13 +-- docs/topics/sync-and-asyncio.md | 10 ++- src/libvt/aio.py | 22 +++-- src/libvt/screen.py | 88 ++++++++++++++++++- src/libvt/terminal.py | 146 +++++++++++++++++++++++++++----- tests/test_aio.py | 54 ++++++++++++ tests/test_terminal.py | 113 +++++++++++++++++++++++- 7 files changed, 407 insertions(+), 39 deletions(-) diff --git a/docs/topics/snapshots.md b/docs/topics/snapshots.md index dbc1661c..b3cdc025 100644 --- a/docs/topics/snapshots.md +++ b/docs/topics/snapshots.md @@ -117,9 +117,10 @@ 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` joins soft-wrapped + continuation rows while preserving hard linebreaks (`"\n"`): ```python >>> import libvt @@ -214,8 +215,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 diff --git a/docs/topics/sync-and-asyncio.md b/docs/topics/sync-and-asyncio.md index ead55bb0..e3e84d8e 100644 --- a/docs/topics/sync-and-asyncio.md +++ b/docs/topics/sync-and-asyncio.md @@ -87,10 +87,12 @@ stream, pass a configured {class}`~libvt.terminal.Terminal` to {meth}`AsyncTerminalStream.wait_for() ` and {meth}`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. Substring predicates match against +{attr}`Snapshot.unwrapped_text ` across +soft-wrapped rows while preserving hard linebreaks (`"\n"`). 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 diff --git a/src/libvt/aio.py b/src/libvt/aio.py index 08d37b5e..548c254d 100644 --- a/src/libvt/aio.py +++ b/src/libvt/aio.py @@ -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`` across + soft-wrapped rows while preserving hard linebreaks (``"\n"``). + """ async def aclose(self) -> object: """Close the session and expire any active ``?2026`` hold.""" @@ -1381,13 +1385,15 @@ 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 while preserving hard linebreaks (``"\n"``). timeout : float Maximum wait duration in seconds before raising :exc:`~libvt.exc.TerminalTimeoutError`. @@ -1409,7 +1415,7 @@ async def wait_for( _validate_nonneg_seconds(timeout, "timeout") check = ( - (lambda snap: predicate in snap.text) + (lambda snap: predicate in snap.unwrapped_text) if isinstance(predicate, str) else predicate ) @@ -1972,13 +1978,15 @@ 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 while preserving hard linebreaks (``"\n"``). timeout : float Maximum wait duration in seconds before raising :exc:`~libvt.exc.TerminalTimeoutError`. @@ -1999,7 +2007,7 @@ async def wait_for( _validate_nonneg_seconds(timeout, "timeout") check = ( - (lambda snap: predicate in snap.text) + (lambda snap: predicate in snap.unwrapped_text) if isinstance(predicate, str) else predicate ) diff --git a/src/libvt/screen.py b/src/libvt/screen.py index 3ef1413c..9532d4c2 100644 --- a/src/libvt/screen.py +++ b/src/libvt/screen.py @@ -949,9 +949,75 @@ def __getitem__( ) -def format_rows_text(rows: collections.abc.Sequence[RowLike]) -> str: - """Format *rows* as newline-joined text omitting trailing blank lines.""" - lines = [r.rstrip_text() for r in rows] +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') + """ + n = len(rows) + if not unwrap or n < 2 or not any(rows[i].wrapped for i in range(n - 1)): + fast_lines = [r.rstrip_text() for r in rows] + while fast_lines and fast_lines[-1] == "": + fast_lines.pop() + return "\n".join(fast_lines) + + lines: list[str] = [] + i = 0 + while i < n: + r = rows[i] + if not (r.wrapped and i + 1 < n): + lines.append(r.rstrip_text()) + i += 1 + continue + parts: list[str] = [] + pending_blanks = 0 + while True: + r = rows[i] + if r.text_used > 0: + if pending_blanks > 0: + parts.append(" " * pending_blanks) + pending_blanks = 0 + parts.append(r.rstrip_text()) + if r.wrapped and i + 1 < n: + eff_cols = ( + r.cols - 1 + if ( + r.cols > 0 + and raw_width_bits(r.attr_at(r.cols - 1)) + == int(WidthRole.SPACER_HEAD) + ) + else r.cols + ) + if r.text_used < eff_cols: + pending_blanks += eff_cols - r.text_used + i += 1 + else: + i += 1 + break + lines.append("".join(parts)) + while lines and lines[-1] == "": lines.pop() return "\n".join(lines) @@ -1338,6 +1404,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: ... diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py index 16935d9e..db3d18be 100644 --- a/src/libvt/terminal.py +++ b/src/libvt/terminal.py @@ -1074,6 +1074,22 @@ def text(self) -> str: """ return format_rows_text(self._rows) + @property + def unwrapped_text(self) -> str: + r"""Return visible snapshot 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.committed.unwrapped_text + 'hello world\nok' + """ + return format_rows_text(self._rows, unwrap=True) + @t.overload def __getitem__(self, key: int) -> RowView: ... @@ -1116,6 +1132,7 @@ def format( *, policy: Policy = DEFAULT_POLICY, profile: Profile = DEFAULT_PROFILE, + unwrap: bool = False, ) -> str: r"""Render this snapshot using :class:`Formatter`. @@ -1133,6 +1150,9 @@ def format( URI and sequence policy applied when exporting hyperlinks or VT. profile : Profile, optional Terminal profile governing width rules during export. + unwrap : bool + When ``True``, join soft-wrapped continuation rows onto a single + line in ``PLAIN`` and ``HTML`` output. Returns ------- @@ -1142,11 +1162,11 @@ def format( Examples -------- >>> from libvt.terminal import OutputFormat, Terminal - >>> term = Terminal(rows=1, cols=8) - >>> term.feed(b"\x1b[1;32mOK\x1b[0m") + >>> term = Terminal(rows=2, cols=8) + >>> term.feed(b"\x1b[1;32mhello world\x1b[0m") >>> snap = term.committed - >>> snap.format(OutputFormat.PLAIN) - 'OK' + >>> snap.format(OutputFormat.PLAIN, unwrap=True) + 'hello world' >>> " dict[str, t.Any]: @@ -1378,22 +1399,34 @@ def _vt_wrap_position( class Formatter: - r"""Serialize a :class:`Snapshot` to text, VT, or HTML. + r"""Serialize a :class:`Snapshot` to plain text, VT sequences, or HTML. Replay VT output into a fresh :class:`Terminal` of the same size and profile. See :meth:`Snapshot.format` for the VT export contract. + Attributes + ---------- + output_format : OutputFormat + Target export format (``PLAIN``, ``VT``, or ``HTML``). + policy : Policy + URI and sequence policy applied during export. + profile : Profile + Terminal profile governing width and appearance rules. + unwrap : bool + When ``True``, join soft-wrapped continuation rows onto a single line + in ``PLAIN`` and ``HTML`` output. + Examples -------- >>> from libvt.terminal import Formatter, OutputFormat, Terminal - >>> term = Terminal(rows=1, cols=8) - >>> term.feed(b"\x1b[31mERR\x1b[0m") - >>> Formatter(OutputFormat.PLAIN).format_snapshot(term.committed) - 'ERR' + >>> term = Terminal(rows=2, cols=8) + >>> term.feed(b"\x1b[31mhello world\x1b[0m") + >>> Formatter(OutputFormat.PLAIN, unwrap=True).format_snapshot(term.committed) + 'hello world' """ - __slots__ = ("output_format", "policy", "profile") + __slots__ = ("output_format", "policy", "profile", "unwrap") def __init__( self, @@ -1401,15 +1434,17 @@ def __init__( *, policy: Policy = DEFAULT_POLICY, profile: Profile = DEFAULT_PROFILE, + unwrap: bool = False, ) -> None: self.output_format = output_format self.policy = policy self.profile = profile + self.unwrap = unwrap def format_snapshot(self, snapshot: Snapshot) -> str: """Render *snapshot* in :attr:`output_format`.""" if self.output_format == OutputFormat.PLAIN: - return snapshot.text + return snapshot.unwrapped_text if self.unwrap else snapshot.text if self.output_format == OutputFormat.VT: return self._render_vt(snapshot) return self._render_html(snapshot) @@ -1655,12 +1690,72 @@ def _render_html(self, snapshot: Snapshot) -> str: UnderlineStyle.DOTTED: "dotted", UnderlineStyle.DASHED: "dashed", } - for row in snapshot._rows: - view = RowView(row) + n_rows = len(snapshot._rows) + r_idx = 0 + while r_idx < n_rows: + chain_start = r_idx + if self.unwrap: + while snapshot._rows[r_idx].wrapped and r_idx + 1 < n_rows: + r_idx += 1 + chain_end = r_idx + r_idx += 1 + + last_text_idx = -1 + if chain_end > chain_start: + for k in range(chain_end, chain_start - 1, -1): + if snapshot._rows[k].text_used > 0: + last_text_idx = k + break + + merged_runs: list[tuple[str, Style, Hyperlink | None]] = [] + for k in range(chain_start, chain_end + 1): + row = snapshot._rows[k] + for run in RowView(row).runs: + if not run.text: + continue + if ( + merged_runs + and merged_runs[-1][1] == run.style + and merged_runs[-1][2] == run.hyperlink + ): + prev_txt, _, _ = merged_runs[-1] + merged_runs[-1] = ( + prev_txt + run.text, + run.style, + run.hyperlink, + ) + else: + merged_runs.append((run.text, run.style, run.hyperlink)) + if k < last_text_idx: + eff_cols = ( + row.cols - 1 + if ( + row.cols > 0 + and raw_width_bits(row.attr_at(row.cols - 1)) + == int(WidthRole.SPACER_HEAD) + ) + else row.cols + ) + prev_used = min(eff_cols, row.used) + if prev_used < eff_cols: + gap_txt = " " * (eff_cols - prev_used) + if ( + merged_runs + and merged_runs[-1][1] == DEFAULT_STYLE + and merged_runs[-1][2] is None + ): + prev_txt, _, _ = merged_runs[-1] + merged_runs[-1] = ( + prev_txt + gap_txt, + DEFAULT_STYLE, + None, + ) + else: + merged_runs.append((gap_txt, DEFAULT_STYLE, None)) + chunks: list[str] = [] - for run in view.runs: - escaped = html.escape(run.text) - style = run.style + for run_text, style, hyperlink in merged_runs: + escaped = html.escape(run_text) css: list[str] = [] background: str | None = None if style.bold: @@ -1718,10 +1813,10 @@ def _render_html(self, snapshot: Snapshot) -> str: if css else escaped ) - if run.hyperlink is not None and ( - allow_unsafe or _is_safe_uri(run.hyperlink.uri) + if hyperlink is not None and ( + allow_unsafe or _is_safe_uri(hyperlink.uri) ): - href = html.escape(run.hyperlink.uri, quote=True) + href = html.escape(hyperlink.uri, quote=True) span = f'{span}' if style.hidden: span = f'{span}' @@ -2839,6 +2934,19 @@ def text(self) -> str: """Return visible active-screen text with trailing blank rows omitted.""" return self._screens.active.text + @property + def unwrapped_text(self) -> str: + r"""Return visible active-screen text with soft-wrapped rows joined. + + Examples + -------- + >>> term = Terminal(rows=3, cols=8) + >>> term.feed(b"hello world\r\nok") + >>> term.unwrapped_text + 'hello world\nok' + """ + return self._screens.active.unwrapped_text + @property def committed(self) -> Snapshot: r"""Return tear-free committed :class:`Snapshot` respecting ``?2026`` hold. diff --git a/tests/test_aio.py b/tests/test_aio.py index 227dcb47..1099747a 100644 --- a/tests/test_aio.py +++ b/tests/test_aio.py @@ -1645,3 +1645,57 @@ def unexpected_openpty() -> t.NoReturn: with pytest.raises(ValueError, match="unsupported parser encoding: 'latin-2'"): async with open_pty([sys.executable, "-c", "pass"], **options): pytest.fail("opened a PTY with an unsupported encoding") + + +async def test_async_terminal_stream_wait_for_soft_wrapped_substring() -> None: + """``AsyncTerminalStream.wait_for`` matches strings split across soft wraps.""" + reader = asyncio.StreamReader() + reader.feed_data( + b"fatal: could not read Username for 'http://127.0.0.1:44765': " + b"terminal prompts disabled\r\n", + ) + reader.feed_eof() + async with AsyncTerminalStream( + reader, + terminal=libvt.Terminal(rows=3, cols=80), + ) as stream: + snap = await stream.wait_for("terminal prompts disabled", timeout=0.2) + assert snap[0].wrapped is True + assert "terminal prompts di\nsabled" in snap.text + assert "terminal prompts disabled" in snap.unwrapped_text + + hard_reader = asyncio.StreamReader() + hard_reader.feed_data(b"alpha\r\nbeta\r\n") + hard_reader.feed_eof() + async with AsyncTerminalStream( + hard_reader, + terminal=libvt.Terminal(rows=3, cols=20), + ) as hard_stream: + hard_snap = await hard_stream.wait_for("alpha\nbeta", timeout=0.2) + assert hard_snap.unwrapped_text == "alpha\nbeta" + with pytest.raises(TerminalTimeoutError): + await hard_stream.wait_for("alphabeta", timeout=0.05, attach_note=False) + + +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX pty required") +async def test_open_pty_wait_for_soft_wrapped_substring() -> None: + """``PtySession.wait_for`` matches strings split across soft-wrapped PTY rows.""" + child_code = ( + "import sys\n" + "sys.stdout.write(" + "\"fatal: could not read Username for 'http://127.0.0.1:44765': " + 'terminal prompts disabled\\nnext-line\\n"' + ")\n" + "sys.stdout.flush()\n" + ) + async with open_pty( + (sys.executable, "-u", "-c", child_code), + rows=4, + cols=80, + ) as pty_sess: + snap = await pty_sess.wait_for("terminal prompts disabled", timeout=3.0) + await pty_sess.wait_for("next-line", timeout=3.0) + final_snap = pty_sess.terminal.committed + assert snap[0].wrapped is True + assert "terminal prompts disabled" in final_snap.unwrapped_text + assert "disablednext-line" not in final_snap.unwrapped_text diff --git a/tests/test_terminal.py b/tests/test_terminal.py index 0e851f43..1ac87ef9 100644 --- a/tests/test_terminal.py +++ b/tests/test_terminal.py @@ -37,10 +37,11 @@ LINUX_CONSOLE_PROFILE, XTERM_PROFILE, ) -from libvt.screen import CursorShape, RowView, ScrollRegion +from libvt.screen import CursorShape, RowView, ScrollRegion, format_rows_text from libvt.style import AnsiColor, Hyperlink from libvt.terminal import ( FlightRecorder, + Formatter, OutputFormat, ResyncReason, ScreenDelta, @@ -1667,3 +1668,113 @@ def test_backward_tab_uses_the_host_wrap_latch(profile: Profile, keeps: bool) -> assert (terminal.cursor.col, terminal.cursor.pending_wrap) == (8, keeps) terminal.feed(b"X") assert terminal.lines == (("123456789abz", "X") if keeps else ("12345678Xabz", "")) + + +def test_unwrapped_text_and_formatter_unwrap() -> None: + """``unwrapped_text`` and ``Formatter(unwrap=True)`` join soft-wrapped chains.""" + # 1. ASCII mid-word wrap + styled/hyperlink HTML coalescing across wrap boundary. + term = libvt.Terminal(rows=3, cols=8) + term.feed(b"hello world") + snap = term.committed + assert term.text == "hello wo\nrld" + assert term.unwrapped_text == "hello world" + assert term.screen.unwrapped_text == "hello world" + assert snap.unwrapped_text == "hello world" + assert snap.format(OutputFormat.PLAIN) == "hello wo\nrld" + assert snap.format(OutputFormat.PLAIN, unwrap=True) == "hello world" + assert Formatter(OutputFormat.PLAIN, unwrap=True).format_snapshot(snap) == ( + "hello world" + ) + assert snap.format(OutputFormat.HTML) == ( + '
\nhello wo\nrld\n\n
' + ) + assert snap.format(OutputFormat.HTML, unwrap=True) == ( + '
\nhello world\n\n
' + ) + + styled = libvt.Terminal(rows=2, cols=8) + styled.feed( + b"\x1b[1;31m\x1b]8;;https://example.com\x07hello world\x1b]8;;\x07\x1b[0m", + ) + assert styled.committed.format(OutputFormat.HTML, unwrap=True) == ( + '
\n'
+        ''
+        'hello world'
+        "\n"
+        "
" + ) + + # 2. Wide CJK wrap with SPACER_HEAD (no phantom space on viewport or FrozenRow). + cjk = libvt.Terminal(rows=2, cols=5, scrollback=10) + cjk.feed("abcd中".encode()) + cjk_snap = cjk.committed + assert cjk_snap[0, 4].width_role == WidthRole.SPACER_HEAD + assert cjk.unwrapped_text == "abcd中" + assert cjk.screen.unwrapped_text == "abcd中" + assert cjk_snap.unwrapped_text == "abcd中" + assert cjk_snap.format(OutputFormat.PLAIN, unwrap=True) == "abcd中" + assert cjk_snap.format(OutputFormat.HTML, unwrap=True) == ( + '
\nabcd中\n
' + ) + cjk.feed(b"\r\nrow2\r\nrow3") + assert format_rows_text(cjk.screen._history.freeze(), unwrap=True) == "abcd中" + + # 3. CUP / cursor-jump gap before wrap. + cup = libvt.Terminal(rows=2, cols=6) + cup.feed(b"ab\x1b[6Gxy") + cup_snap = cup.committed + assert cup.unwrapped_text == "ab xy" + assert cup.screen.unwrapped_text == "ab xy" + assert cup_snap.unwrapped_text == "ab xy" + assert cup_snap.format(OutputFormat.PLAIN, unwrap=True) == "ab xy" + assert cup_snap.format(OutputFormat.HTML, unwrap=True) == ( + '
\nab   xy\n
' + ) + + # 4. Trimmed wrapped=True row from tmux capture-pane + written trailing spaces. + cap_gap = decode_tmux_capture( + ["W ab", "- GH"], + rows=2, + cols=6, + flagged=True, + trim_trailing=True, + ) + assert cap_gap.snapshot.text == "ab\nGH" + assert cap_gap.snapshot.unwrapped_text == "ab GH" + assert cap_gap.terminal.unwrapped_text == "ab GH" + assert cap_gap.terminal.screen.unwrapped_text == "ab GH" + assert cap_gap.snapshot.format(OutputFormat.PLAIN, unwrap=True) == "ab GH" + assert cap_gap.snapshot.format(OutputFormat.HTML, unwrap=True) == ( + '
\nab    GH\n
' + ) + + cap_trail = decode_tmux_capture( + ["W ab", "- "], + rows=2, + cols=6, + flagged=True, + trim_trailing=True, + ) + assert cap_trail.snapshot.unwrapped_text == "ab" + assert cap_trail.snapshot.format(OutputFormat.PLAIN, unwrap=True) == "ab" + assert cap_trail.snapshot.format(OutputFormat.HTML, unwrap=True) == ( + '
\nab\n
' + ) + + prompt_t = libvt.Terminal(rows=2, cols=8) + prompt_t.feed(b"12345678prompt$ ") + assert prompt_t.committed.unwrapped_text == "12345678prompt$ " + assert prompt_t.committed.format(OutputFormat.PLAIN, unwrap=True) == ( + "12345678prompt$ " + ) + + # 5. Hard linebreak isolation. + hard = libvt.Terminal(rows=3, cols=10) + hard.feed(b"alpha\r\nbeta") + hard_snap = hard.committed + assert hard_snap.unwrapped_text == "alpha\nbeta" + assert "alphabeta" not in hard_snap.unwrapped_text + assert hard_snap.format(OutputFormat.PLAIN, unwrap=True) == "alpha\nbeta" + assert hard_snap.format(OutputFormat.HTML, unwrap=True) == ( + '
\nalpha\nbeta\n\n
' + ) From cd4257e3288f97105ce46739396def2b76a291a6 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Wed, 2 Dec 2026 05:08:00 -0600 Subject: [PATCH 2/5] terminal(fix[unwrap]): Preserve styled gaps why: Logical text and HTML must preserve gaps that occupy display columns. what: - Preserve BCE gaps and support region and render exports - Cache captured text and cover multi-row wait predicates --- docs/topics/snapshots.md | 3 +- docs/topics/sync-and-asyncio.md | 3 +- src/libvt/aio.py | 23 +++++++++--- src/libvt/screen.py | 26 +++++++++++++ src/libvt/terminal.py | 55 +++++++++++++++++++++++---- tests/test_aio.py | 33 +++++++++++++++++ tests/test_terminal.py | 66 +++++++++++++++++++++++++++++++++ 7 files changed, 194 insertions(+), 15 deletions(-) diff --git a/docs/topics/snapshots.md b/docs/topics/snapshots.md index b3cdc025..79422a71 100644 --- a/docs/topics/snapshots.md +++ b/docs/topics/snapshots.md @@ -119,7 +119,8 @@ A `Snapshot` supports the same zero-based `(row, col)` indexing and slicing as - {attr}`~libvt.terminal.Snapshot.lines` omits unwritten trailing blank cells, {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` joins soft-wrapped + 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 diff --git a/docs/topics/sync-and-asyncio.md b/docs/topics/sync-and-asyncio.md index e3e84d8e..45151c71 100644 --- a/docs/topics/sync-and-asyncio.md +++ b/docs/topics/sync-and-asyncio.md @@ -90,7 +90,8 @@ substring or callable predicate against the current committed snapshot, then at synchronized frame and read boundaries, expiring unclosed `?2026` holds after `sync_timeout` seconds. Substring predicates match against {attr}`Snapshot.unwrapped_text ` across -soft-wrapped rows while preserving hard linebreaks (`"\n"`). On timeout or +soft-wrapped rows while preserving hard linebreaks (`"\n"`) and multi-line +{attr}`Snapshot.text ` matches. On timeout or premature EOF, both raise {exc}`~libvt.exc.TerminalTimeoutError` with the boxed screen and recent decoded input attached via `__notes__`: diff --git a/src/libvt/aio.py b/src/libvt/aio.py index 548c254d..af8620b0 100644 --- a/src/libvt/aio.py +++ b/src/libvt/aio.py @@ -296,7 +296,8 @@ async def wait_for( r"""Wait until *predicate* matches a committed ``Snapshot``. ``str`` predicates match against ``snapshot.unwrapped_text`` across - soft-wrapped rows while preserving hard linebreaks (``"\n"``). + soft-wrapped rows while preserving hard linebreaks (``"\n"``) and + multi-line ``snapshot.text`` matches. """ async def aclose(self) -> object: @@ -1393,7 +1394,8 @@ async def wait_for( Callable evaluated in the waiting task at read and synchronized frame boundaries, or a substring matched against :attr:`~libvt.terminal.Snapshot.unwrapped_text` across soft-wrapped - rows while preserving hard linebreaks (``"\n"``). + rows (preserving hard ``"\n"`` linebreaks and multi-line + :attr:`~libvt.terminal.Snapshot.text` matches). timeout : float Maximum wait duration in seconds before raising :exc:`~libvt.exc.TerminalTimeoutError`. @@ -1415,7 +1417,12 @@ async def wait_for( _validate_nonneg_seconds(timeout, "timeout") check = ( - (lambda snap: predicate in snap.unwrapped_text) + ( + lambda snap: ( + predicate in snap.unwrapped_text + or ("\n" in predicate and predicate in snap.text) + ) + ) if isinstance(predicate, str) else predicate ) @@ -1986,7 +1993,8 @@ async def wait_for( Callable evaluated in the waiting task at read and synchronized frame boundaries, or a substring matched against :attr:`~libvt.terminal.Snapshot.unwrapped_text` across soft-wrapped - rows while preserving hard linebreaks (``"\n"``). + rows (preserving hard ``"\n"`` linebreaks and multi-line + :attr:`~libvt.terminal.Snapshot.text` matches). timeout : float Maximum wait duration in seconds before raising :exc:`~libvt.exc.TerminalTimeoutError`. @@ -2007,7 +2015,12 @@ async def wait_for( _validate_nonneg_seconds(timeout, "timeout") check = ( - (lambda snap: predicate in snap.unwrapped_text) + ( + lambda snap: ( + predicate in snap.unwrapped_text + or ("\n" in predicate and predicate in snap.text) + ) + ) if isinstance(predicate, str) else predicate ) diff --git a/src/libvt/screen.py b/src/libvt/screen.py index 9532d4c2..a3ef0348 100644 --- a/src/libvt/screen.py +++ b/src/libvt/screen.py @@ -908,6 +908,32 @@ 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"``; narrower column sub-rectangles + 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 ( + len(self._rows) > 0 + and columns.start == 0 + and all(columns.stop >= r.cols for r in self._rows) + ): + return format_rows_text(self._rows, unwrap=True) + return self.text + def __iter__(self) -> collections.abc.Iterator[RowView]: """Iterate over rows using the current rectangular extent.""" columns = self.columns diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py index db3d18be..bbe8d92f 100644 --- a/src/libvt/terminal.py +++ b/src/libvt/terminal.py @@ -676,6 +676,8 @@ def _make_snapshot( if evicted_total is None else evicted_total ) + snap._text_cache = None + snap._unwrapped_text_cache = None snap.cursor = cursor snap.title = title snap.cwd = cwd @@ -768,6 +770,8 @@ class Snapshot: "_rows", "_scroll_region", "_scrolled_total", + "_text_cache", + "_unwrapped_text_cache", "_vt_pen", "active_is_alt", "appearance", @@ -792,6 +796,8 @@ class Snapshot: _rows: tuple[_Row, ...] _scroll_region: ScrollRegion _scrolled_total: int + _text_cache: str | None + _unwrapped_text_cache: str | None _vt_pen: _VtPen active_is_alt: bool appearance: Appearance @@ -1072,7 +1078,11 @@ def text(self) -> str: >>> term.committed.text 'top\nnext' """ - return format_rows_text(self._rows) + cached = self._text_cache + if cached is None: + cached = format_rows_text(self._rows) + object.__setattr__(self, "_text_cache", cached) + return cached @property def unwrapped_text(self) -> str: @@ -1088,7 +1098,11 @@ def unwrapped_text(self) -> str: >>> term.committed.unwrapped_text 'hello world\nok' """ - return format_rows_text(self._rows, unwrap=True) + cached = self._unwrapped_text_cache + if cached is None: + cached = format_rows_text(self._rows, unwrap=True) + object.__setattr__(self, "_unwrapped_text_cache", cached) + return cached @t.overload def __getitem__(self, key: int) -> RowView: ... @@ -1700,11 +1714,12 @@ def _render_html(self, snapshot: Snapshot) -> str: chain_end = r_idx r_idx += 1 - last_text_idx = -1 + last_content_idx = -1 if chain_end > chain_start: for k in range(chain_end, chain_start - 1, -1): - if snapshot._rows[k].text_used > 0: - last_text_idx = k + rk = snapshot._rows[k] + if rk.text_used > 0 or rk.used > 0: + last_content_idx = k break merged_runs: list[tuple[str, Style, Hyperlink | None]] = [] @@ -1726,7 +1741,7 @@ def _render_html(self, snapshot: Snapshot) -> str: ) else: merged_runs.append((run.text, run.style, run.hyperlink)) - if k < last_text_idx: + if k < last_content_idx: eff_cols = ( row.cols - 1 if ( @@ -7456,14 +7471,38 @@ def render( cols: int = 80, profile: Profile = DEFAULT_PROFILE, newline_mode: bool = False, + unwrap: bool = False, ) -> str: - r"""Emulate *data* on a fresh ``(rows, cols)`` terminal and return ``text``. + r"""Emulate *data* on a fresh ``(rows, cols)`` terminal and return screen text. + + Parameters + ---------- + data : collections.abc.Buffer | str + Raw VT byte stream or UTF-8 string to feed. + rows : int + Screen height in rows. + cols : int + Screen width in columns. + profile : Profile + Compatibility profile governing emulation quirks. + newline_mode : bool + When ``True``, enable ANSI ``LNM`` (``LF`` implies ``CR``). + unwrap : bool + When ``True``, return :attr:`Terminal.unwrapped_text` with soft-wrapped + rows joined instead of :attr:`Terminal.text`. + + Returns + ------- + str + Rendered visible text with trailing blank rows omitted. Examples -------- >>> import libvt >>> libvt.render(b"loading 10%\r\x1b[2Kloading 100%", rows=1, cols=20) 'loading 100%' + >>> libvt.render(b"hello world", rows=2, cols=8, unwrap=True) + 'hello world' """ term = Terminal( rows=rows, @@ -7476,7 +7515,7 @@ def render( term.feed_str(data) else: term.feed(data) - return term.text + return term.unwrapped_text if unwrap else term.text class _StripSink: diff --git a/tests/test_aio.py b/tests/test_aio.py index 1099747a..d8916b0d 100644 --- a/tests/test_aio.py +++ b/tests/test_aio.py @@ -1699,3 +1699,36 @@ async def test_open_pty_wait_for_soft_wrapped_substring() -> None: assert snap[0].wrapped is True assert "terminal prompts disabled" in final_snap.unwrapped_text assert "disablednext-line" not in final_snap.unwrapped_text + + +async def test_wait_for_multiline_soft_wrapped_backward_compat() -> None: + """``wait_for`` preserves multi-line ``snap.text`` matches across soft wraps.""" + reader = asyncio.StreamReader() + reader.feed_data(b"hello world\r\n") + reader.feed_eof() + async with AsyncTerminalStream( + reader, + terminal=libvt.Terminal(rows=3, cols=8), + ) as stream: + snap = await stream.wait_for("hello wo\nrld", timeout=0.2) + assert snap.unwrapped_text == "hello world" + assert snap.text == "hello wo\nrld" + with pytest.raises(TerminalTimeoutError): + await stream.wait_for("hello\nworld", timeout=0.05, attach_note=False) + + if sys.platform != "win32": + child_code = "import sys\nsys.stdout.write('hello world\\nalpha\\nbeta\\n')\n" + async with open_pty( + (sys.executable, "-u", "-c", child_code), + rows=5, + cols=8, + ) as pty_sess: + await pty_sess.wait_for("beta", timeout=3.0) + pty_snap = await pty_sess.wait_for("hello wo\nrld", timeout=3.0) + assert pty_snap.unwrapped_text == "hello world\nalpha\nbeta" + with pytest.raises(TerminalTimeoutError): + await pty_sess.wait_for( + "alphabeta", + timeout=0.05, + attach_note=False, + ) diff --git a/tests/test_terminal.py b/tests/test_terminal.py index 1ac87ef9..1cd7d754 100644 --- a/tests/test_terminal.py +++ b/tests/test_terminal.py @@ -1778,3 +1778,69 @@ def test_unwrapped_text_and_formatter_unwrap() -> None: assert hard_snap.format(OutputFormat.HTML, unwrap=True) == ( '
\nalpha\nbeta\n\n
' ) + + +def test_formatter_html_unwrap_bce_continuation_gap() -> None: + """``Formatter(HTML, unwrap=True)`` keeps unwritten gap before BCE-only row.""" + cap_bce = decode_tmux_capture( + ["W ab", "- \x1b[41m \x1b[0m "], + rows=2, + cols=6, + flagged=True, + trim_trailing=False, + ) + snap = cap_bce.snapshot + assert (snap._rows[0].wrapped, snap._rows[0].text_used, snap._rows[0].used) == ( + True, + 2, + 2, + ) + assert (snap._rows[1].text_used, snap._rows[1].used) == (0, 3) + assert snap.format(OutputFormat.HTML, unwrap=True) == ( + '
\n'
+        'ab       \n'
+        "
" + ) + + +def test_snapshot_lazy_text_and_unwrapped_text_caching() -> None: + """``Snapshot.text`` and ``Snapshot.unwrapped_text`` cache ``str`` instances.""" + term = libvt.Terminal(rows=3, cols=8) + term.feed(b"hello world\r\nnext") + snap = term.committed + assert snap.text == "hello wo\nrld\nnext" + assert snap.text is snap.text + assert snap.unwrapped_text == "hello world\nnext" + assert snap.unwrapped_text is snap.unwrapped_text + with pytest.raises(AttributeError): + snap._text_cache = "mutated" + with pytest.raises(AttributeError): + snap._unwrapped_text_cache = "mutated" + + +def test_region_view_unwrapped_text_and_render_unwrap() -> None: + """``RegionView.unwrapped_text`` and ``libvt.render(unwrap=True)`` unwrap rows.""" + term = libvt.Terminal(rows=2, cols=8, scrollback=10) + term.feed(b"hello world\r\nalpha\r\nbeta") + snap = term.committed + + assert snap[0:2].unwrapped_text == "alpha\nbeta" + scrolled = snap.viewport(offset=2) + assert scrolled.unwrapped_text == "hello world" + assert scrolled[0:2].unwrapped_text == "hello world" + assert snap[0:0].unwrapped_text == "" + + sub_t = libvt.Terminal(rows=3, cols=8) + sub_t.feed(b"hello world\r\nok") + sub_snap = sub_t.committed + assert sub_snap[0:2].unwrapped_text == "hello world" + assert sub_snap[0:2, 0:4].unwrapped_text == "hell\nrld" + assert sub_snap[0:2, 2:6].unwrapped_text == sub_snap[0:2, 2:6].text == "llo\nd" + assert sub_t.screen[0:2, 2:6].unwrapped_text == "llo\nd" + + assert libvt.render(b"hello world\r\nok", rows=3, cols=8) == "hello wo\nrld\nok" + assert ( + libvt.render(b"hello world\r\nok", rows=3, cols=8, unwrap=True) + == "hello world\nok" + ) + assert libvt.render("abcd中", rows=2, cols=5, unwrap=True) == "abcd中" From cdd23f106bf505103204fc714fa0161d81513309 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Wed, 2 Dec 2026 17:41:01 -0600 Subject: [PATCH 3/5] aio(fix[wait]): Match logical snapshot text why: String waits need to follow hard line breaks independently of viewport width. what: - Use unwrapped snapshot text for string predicates - Document and test logical stream and PTY waits --- docs/topics/sync-and-asyncio.md | 3 +- src/libvt/aio.py | 27 +++----- tests/test_aio.py | 39 ++---------- tests/test_terminal.py | 107 +++++--------------------------- 4 files changed, 30 insertions(+), 146 deletions(-) diff --git a/docs/topics/sync-and-asyncio.md b/docs/topics/sync-and-asyncio.md index 45151c71..e3e84d8e 100644 --- a/docs/topics/sync-and-asyncio.md +++ b/docs/topics/sync-and-asyncio.md @@ -90,8 +90,7 @@ substring or callable predicate against the current committed snapshot, then at synchronized frame and read boundaries, expiring unclosed `?2026` holds after `sync_timeout` seconds. Substring predicates match against {attr}`Snapshot.unwrapped_text ` across -soft-wrapped rows while preserving hard linebreaks (`"\n"`) and multi-line -{attr}`Snapshot.text ` matches. On timeout or +soft-wrapped rows while preserving hard linebreaks (`"\n"`). On timeout or premature EOF, both raise {exc}`~libvt.exc.TerminalTimeoutError` with the boxed screen and recent decoded input attached via `__notes__`: diff --git a/src/libvt/aio.py b/src/libvt/aio.py index af8620b0..8796ec76 100644 --- a/src/libvt/aio.py +++ b/src/libvt/aio.py @@ -296,8 +296,7 @@ async def wait_for( r"""Wait until *predicate* matches a committed ``Snapshot``. ``str`` predicates match against ``snapshot.unwrapped_text`` across - soft-wrapped rows while preserving hard linebreaks (``"\n"``) and - multi-line ``snapshot.text`` matches. + soft-wrapped rows while preserving hard linebreaks (``"\n"``). """ async def aclose(self) -> object: @@ -1392,10 +1391,9 @@ async def wait_for( ---------- predicate : collections.abc.Callable[[Snapshot], bool] | str Callable evaluated in the waiting task at read and synchronized - frame boundaries, or a substring matched against + frame boundaries, or a substring searched inside :attr:`~libvt.terminal.Snapshot.unwrapped_text` across soft-wrapped - rows (preserving hard ``"\n"`` linebreaks and multi-line - :attr:`~libvt.terminal.Snapshot.text` matches). + rows (preserving hard ``"\n"`` linebreaks). timeout : float Maximum wait duration in seconds before raising :exc:`~libvt.exc.TerminalTimeoutError`. @@ -1417,12 +1415,7 @@ async def wait_for( _validate_nonneg_seconds(timeout, "timeout") check = ( - ( - lambda snap: ( - predicate in snap.unwrapped_text - or ("\n" in predicate and predicate in snap.text) - ) - ) + (lambda snap: predicate in snap.unwrapped_text) if isinstance(predicate, str) else predicate ) @@ -1991,10 +1984,9 @@ async def wait_for( ---------- predicate : collections.abc.Callable[[Snapshot], bool] | str Callable evaluated in the waiting task at read and synchronized - frame boundaries, or a substring matched against + frame boundaries, or a substring searched inside :attr:`~libvt.terminal.Snapshot.unwrapped_text` across soft-wrapped - rows (preserving hard ``"\n"`` linebreaks and multi-line - :attr:`~libvt.terminal.Snapshot.text` matches). + rows (preserving hard ``"\n"`` linebreaks). timeout : float Maximum wait duration in seconds before raising :exc:`~libvt.exc.TerminalTimeoutError`. @@ -2015,12 +2007,7 @@ async def wait_for( _validate_nonneg_seconds(timeout, "timeout") check = ( - ( - lambda snap: ( - predicate in snap.unwrapped_text - or ("\n" in predicate and predicate in snap.text) - ) - ) + (lambda snap: predicate in snap.unwrapped_text) if isinstance(predicate, str) else predicate ) diff --git a/tests/test_aio.py b/tests/test_aio.py index d8916b0d..3c7d42c4 100644 --- a/tests/test_aio.py +++ b/tests/test_aio.py @@ -1648,7 +1648,7 @@ def unexpected_openpty() -> t.NoReturn: async def test_async_terminal_stream_wait_for_soft_wrapped_substring() -> None: - """``AsyncTerminalStream.wait_for`` matches strings split across soft wraps.""" + """``AsyncTerminalStream.wait_for`` matches ``Snapshot.unwrapped_text``.""" reader = asyncio.StreamReader() reader.feed_data( b"fatal: could not read Username for 'http://127.0.0.1:44765': " @@ -1663,6 +1663,10 @@ async def test_async_terminal_stream_wait_for_soft_wrapped_substring() -> None: assert snap[0].wrapped is True assert "terminal prompts di\nsabled" in snap.text assert "terminal prompts disabled" in snap.unwrapped_text + with pytest.raises(TerminalTimeoutError): + await stream.wait_for( + "terminal prompts di\nsabled", timeout=0.05, attach_note=False + ) hard_reader = asyncio.StreamReader() hard_reader.feed_data(b"alpha\r\nbeta\r\n") @@ -1699,36 +1703,3 @@ async def test_open_pty_wait_for_soft_wrapped_substring() -> None: assert snap[0].wrapped is True assert "terminal prompts disabled" in final_snap.unwrapped_text assert "disablednext-line" not in final_snap.unwrapped_text - - -async def test_wait_for_multiline_soft_wrapped_backward_compat() -> None: - """``wait_for`` preserves multi-line ``snap.text`` matches across soft wraps.""" - reader = asyncio.StreamReader() - reader.feed_data(b"hello world\r\n") - reader.feed_eof() - async with AsyncTerminalStream( - reader, - terminal=libvt.Terminal(rows=3, cols=8), - ) as stream: - snap = await stream.wait_for("hello wo\nrld", timeout=0.2) - assert snap.unwrapped_text == "hello world" - assert snap.text == "hello wo\nrld" - with pytest.raises(TerminalTimeoutError): - await stream.wait_for("hello\nworld", timeout=0.05, attach_note=False) - - if sys.platform != "win32": - child_code = "import sys\nsys.stdout.write('hello world\\nalpha\\nbeta\\n')\n" - async with open_pty( - (sys.executable, "-u", "-c", child_code), - rows=5, - cols=8, - ) as pty_sess: - await pty_sess.wait_for("beta", timeout=3.0) - pty_snap = await pty_sess.wait_for("hello wo\nrld", timeout=3.0) - assert pty_snap.unwrapped_text == "hello world\nalpha\nbeta" - with pytest.raises(TerminalTimeoutError): - await pty_sess.wait_for( - "alphabeta", - timeout=0.05, - attach_note=False, - ) diff --git a/tests/test_terminal.py b/tests/test_terminal.py index 1cd7d754..4c454981 100644 --- a/tests/test_terminal.py +++ b/tests/test_terminal.py @@ -1670,9 +1670,8 @@ def test_backward_tab_uses_the_host_wrap_latch(profile: Profile, keeps: bool) -> assert terminal.lines == (("123456789abz", "X") if keeps else ("12345678Xabz", "")) -def test_unwrapped_text_and_formatter_unwrap() -> None: - """``unwrapped_text`` and ``Formatter(unwrap=True)`` join soft-wrapped chains.""" - # 1. ASCII mid-word wrap + styled/hyperlink HTML coalescing across wrap boundary. +def test_unwrapped_text_formatter_bce_cache_and_region() -> None: + """``unwrapped_text``, ``Formatter(unwrap=True)``, and ``render(unwrap=True)``.""" term = libvt.Terminal(rows=3, cols=8) term.feed(b"hello world") snap = term.committed @@ -1680,6 +1679,8 @@ def test_unwrapped_text_and_formatter_unwrap() -> None: assert term.unwrapped_text == "hello world" assert term.screen.unwrapped_text == "hello world" assert snap.unwrapped_text == "hello world" + assert snap.text is snap.text + assert snap.unwrapped_text is snap.unwrapped_text assert snap.format(OutputFormat.PLAIN) == "hello wo\nrld" assert snap.format(OutputFormat.PLAIN, unwrap=True) == "hello world" assert Formatter(OutputFormat.PLAIN, unwrap=True).format_snapshot(snap) == ( @@ -1691,6 +1692,10 @@ def test_unwrapped_text_and_formatter_unwrap() -> None: assert snap.format(OutputFormat.HTML, unwrap=True) == ( '
\nhello world\n\n
' ) + with pytest.raises(AttributeError): + snap._text_cache = "mutated" + with pytest.raises(AttributeError): + snap._unwrapped_text_cache = "mutated" styled = libvt.Terminal(rows=2, cols=8) styled.feed( @@ -1704,7 +1709,6 @@ def test_unwrapped_text_and_formatter_unwrap() -> None: "" ) - # 2. Wide CJK wrap with SPACER_HEAD (no phantom space on viewport or FrozenRow). cjk = libvt.Terminal(rows=2, cols=5, scrollback=10) cjk.feed("abcd中".encode()) cjk_snap = cjk.committed @@ -1712,26 +1716,20 @@ def test_unwrapped_text_and_formatter_unwrap() -> None: assert cjk.unwrapped_text == "abcd中" assert cjk.screen.unwrapped_text == "abcd中" assert cjk_snap.unwrapped_text == "abcd中" - assert cjk_snap.format(OutputFormat.PLAIN, unwrap=True) == "abcd中" assert cjk_snap.format(OutputFormat.HTML, unwrap=True) == ( '
\nabcd中\n
' ) cjk.feed(b"\r\nrow2\r\nrow3") assert format_rows_text(cjk.screen._history.freeze(), unwrap=True) == "abcd中" - # 3. CUP / cursor-jump gap before wrap. cup = libvt.Terminal(rows=2, cols=6) cup.feed(b"ab\x1b[6Gxy") cup_snap = cup.committed assert cup.unwrapped_text == "ab xy" - assert cup.screen.unwrapped_text == "ab xy" - assert cup_snap.unwrapped_text == "ab xy" - assert cup_snap.format(OutputFormat.PLAIN, unwrap=True) == "ab xy" assert cup_snap.format(OutputFormat.HTML, unwrap=True) == ( '
\nab   xy\n
' ) - # 4. Trimmed wrapped=True row from tmux capture-pane + written trailing spaces. cap_gap = decode_tmux_capture( ["W ab", "- GH"], rows=2, @@ -1739,49 +1737,11 @@ def test_unwrapped_text_and_formatter_unwrap() -> None: flagged=True, trim_trailing=True, ) - assert cap_gap.snapshot.text == "ab\nGH" assert cap_gap.snapshot.unwrapped_text == "ab GH" - assert cap_gap.terminal.unwrapped_text == "ab GH" - assert cap_gap.terminal.screen.unwrapped_text == "ab GH" - assert cap_gap.snapshot.format(OutputFormat.PLAIN, unwrap=True) == "ab GH" assert cap_gap.snapshot.format(OutputFormat.HTML, unwrap=True) == ( '
\nab    GH\n
' ) - cap_trail = decode_tmux_capture( - ["W ab", "- "], - rows=2, - cols=6, - flagged=True, - trim_trailing=True, - ) - assert cap_trail.snapshot.unwrapped_text == "ab" - assert cap_trail.snapshot.format(OutputFormat.PLAIN, unwrap=True) == "ab" - assert cap_trail.snapshot.format(OutputFormat.HTML, unwrap=True) == ( - '
\nab\n
' - ) - - prompt_t = libvt.Terminal(rows=2, cols=8) - prompt_t.feed(b"12345678prompt$ ") - assert prompt_t.committed.unwrapped_text == "12345678prompt$ " - assert prompt_t.committed.format(OutputFormat.PLAIN, unwrap=True) == ( - "12345678prompt$ " - ) - - # 5. Hard linebreak isolation. - hard = libvt.Terminal(rows=3, cols=10) - hard.feed(b"alpha\r\nbeta") - hard_snap = hard.committed - assert hard_snap.unwrapped_text == "alpha\nbeta" - assert "alphabeta" not in hard_snap.unwrapped_text - assert hard_snap.format(OutputFormat.PLAIN, unwrap=True) == "alpha\nbeta" - assert hard_snap.format(OutputFormat.HTML, unwrap=True) == ( - '
\nalpha\nbeta\n\n
' - ) - - -def test_formatter_html_unwrap_bce_continuation_gap() -> None: - """``Formatter(HTML, unwrap=True)`` keeps unwritten gap before BCE-only row.""" cap_bce = decode_tmux_capture( ["W ab", "- \x1b[41m \x1b[0m "], rows=2, @@ -1789,54 +1749,21 @@ def test_formatter_html_unwrap_bce_continuation_gap() -> None: flagged=True, trim_trailing=False, ) - snap = cap_bce.snapshot - assert (snap._rows[0].wrapped, snap._rows[0].text_used, snap._rows[0].used) == ( - True, - 2, - 2, - ) - assert (snap._rows[1].text_used, snap._rows[1].used) == (0, 3) - assert snap.format(OutputFormat.HTML, unwrap=True) == ( + assert cap_bce.snapshot.format(OutputFormat.HTML, unwrap=True) == ( '
\n'
         'ab       \n'
         "
" ) - -def test_snapshot_lazy_text_and_unwrapped_text_caching() -> None: - """``Snapshot.text`` and ``Snapshot.unwrapped_text`` cache ``str`` instances.""" - term = libvt.Terminal(rows=3, cols=8) - term.feed(b"hello world\r\nnext") - snap = term.committed - assert snap.text == "hello wo\nrld\nnext" - assert snap.text is snap.text - assert snap.unwrapped_text == "hello world\nnext" - assert snap.unwrapped_text is snap.unwrapped_text - with pytest.raises(AttributeError): - snap._text_cache = "mutated" - with pytest.raises(AttributeError): - snap._unwrapped_text_cache = "mutated" - - -def test_region_view_unwrapped_text_and_render_unwrap() -> None: - """``RegionView.unwrapped_text`` and ``libvt.render(unwrap=True)`` unwrap rows.""" - term = libvt.Terminal(rows=2, cols=8, scrollback=10) - term.feed(b"hello world\r\nalpha\r\nbeta") - snap = term.committed - - assert snap[0:2].unwrapped_text == "alpha\nbeta" - scrolled = snap.viewport(offset=2) - assert scrolled.unwrapped_text == "hello world" - assert scrolled[0:2].unwrapped_text == "hello world" - assert snap[0:0].unwrapped_text == "" - - sub_t = libvt.Terminal(rows=3, cols=8) - sub_t.feed(b"hello world\r\nok") + sub_t = libvt.Terminal(rows=2, cols=8, scrollback=10) + sub_t.feed(b"hello world\r\nalpha\r\nbeta") sub_snap = sub_t.committed - assert sub_snap[0:2].unwrapped_text == "hello world" - assert sub_snap[0:2, 0:4].unwrapped_text == "hell\nrld" - assert sub_snap[0:2, 2:6].unwrapped_text == sub_snap[0:2, 2:6].text == "llo\nd" - assert sub_t.screen[0:2, 2:6].unwrapped_text == "llo\nd" + assert sub_snap.viewport(offset=2).unwrapped_text == "hello world" + assert sub_snap[0:0].unwrapped_text == "" + narrow_t = libvt.Terminal(rows=3, cols=8) + narrow_t.feed(b"hello world\r\nok") + assert narrow_t.committed[0:2].unwrapped_text == "hello world" + assert narrow_t.committed[0:2, 0:4].unwrapped_text == "hell\nrld" assert libvt.render(b"hello world\r\nok", rows=3, cols=8) == "hello wo\nrld\nok" assert ( From a8e89b5f8406d270158cd41fca17bc3eafe4a8a7 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Wed, 2 Dec 2026 20:43:26 -0600 Subject: [PATCH 4/5] terminal(fix[unwrap]): Honor visible margins why: Logical text must join actual continuation rows and preserve gaps without pulling clipped cells into waits or output. what: - Reuse the logical text contract for stream and PTY waits - Respect slice bounds and styled gaps in plain and HTML output - Exercise partial regions, held wraps, and hard newline predicates - Document physical row matching for existing string predicates --- MIGRATION | 15 +++ docs/topics/sync-and-asyncio.md | 9 +- src/libvt/aio.py | 28 ++++-- src/libvt/screen.py | 111 +++++++++++++---------- src/libvt/terminal.py | 106 +++++++--------------- tests/test_aio.py | 60 +++++++++++- tests/test_terminal.py | 156 ++++++++++++++++++++++++++++---- 7 files changed, 332 insertions(+), 153 deletions(-) diff --git a/MIGRATION b/MIGRATION index b3e85471..440f7fc0 100644 --- a/MIGRATION +++ b/MIGRATION @@ -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) diff --git a/docs/topics/sync-and-asyncio.md b/docs/topics/sync-and-asyncio.md index e3e84d8e..ca51e003 100644 --- a/docs/topics/sync-and-asyncio.md +++ b/docs/topics/sync-and-asyncio.md @@ -88,10 +88,11 @@ stream, pass a configured {class}`~libvt.terminal.Terminal` to and {meth}`PtySession.wait_for() ` test a substring or callable predicate against the current committed snapshot, then at synchronized frame and read boundaries, expiring unclosed `?2026` -holds after `sync_timeout` seconds. Substring predicates match against -{attr}`Snapshot.unwrapped_text ` across -soft-wrapped rows while preserving hard linebreaks (`"\n"`). On timeout or -premature EOF, both raise {exc}`~libvt.exc.TerminalTimeoutError` with the +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 diff --git a/src/libvt/aio.py b/src/libvt/aio.py index 8796ec76..74a1ebc1 100644 --- a/src/libvt/aio.py +++ b/src/libvt/aio.py @@ -295,8 +295,8 @@ async def wait_for( ) -> Snapshot: r"""Wait until *predicate* matches a committed ``Snapshot``. - ``str`` predicates match against ``snapshot.unwrapped_text`` across - soft-wrapped rows while preserving hard linebreaks (``"\n"``). + ``str`` predicates match against ``snapshot.unwrapped_text``. Pass a + callable using ``snapshot.text`` to test physical rows. """ async def aclose(self) -> object: @@ -318,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) @@ -1391,9 +1399,10 @@ async def wait_for( ---------- predicate : collections.abc.Callable[[Snapshot], bool] | str Callable evaluated in the waiting task at read and synchronized - frame boundaries, or a substring searched inside + frame boundaries, or a substring matched against :attr:`~libvt.terminal.Snapshot.unwrapped_text` across soft-wrapped - rows (preserving hard ``"\n"`` linebreaks). + 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`. @@ -1413,9 +1422,8 @@ async def wait_for( expires. """ _validate_nonneg_seconds(timeout, "timeout") - check = ( - (lambda snap: predicate in snap.unwrapped_text) + (lambda snap: _snapshot_matches(snap, predicate)) if isinstance(predicate, str) else predicate ) @@ -1984,9 +1992,10 @@ async def wait_for( ---------- predicate : collections.abc.Callable[[Snapshot], bool] | str Callable evaluated in the waiting task at read and synchronized - frame boundaries, or a substring searched inside + frame boundaries, or a substring matched against :attr:`~libvt.terminal.Snapshot.unwrapped_text` across soft-wrapped - rows (preserving hard ``"\n"`` linebreaks). + 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`. @@ -2005,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.unwrapped_text) + (lambda snap: _snapshot_matches(snap, predicate)) if isinstance(predicate, str) else predicate ) diff --git a/src/libvt/screen.py b/src/libvt/screen.py index a3ef0348..847900ba 100644 --- a/src/libvt/screen.py +++ b/src/libvt/screen.py @@ -914,8 +914,10 @@ def unwrapped_text(self) -> str: Full-width row slices (such as ``snap[0:5]`` or :meth:`~libvt.terminal.Snapshot.viewport`) join contiguous - ``row.wrapped`` rows without ``"\n"``; narrower column sub-rectangles - return :attr:`text`. + ``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 -------- @@ -927,11 +929,11 @@ def unwrapped_text(self) -> str: """ columns = self.columns if ( - len(self._rows) > 0 - and columns.start == 0 - and all(columns.stop >= r.cols for r in self._rows) + columns.start == 0 + and columns.step == 1 + and columns.stop >= self._source_width() ): - return format_rows_text(self._rows, unwrap=True) + return _unwrapped_text(self._rows, visible_cols=len(columns)) return self.text def __iter__(self) -> collections.abc.Iterator[RowView]: @@ -975,6 +977,58 @@ def __getitem__( ) +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], *, @@ -1002,48 +1056,9 @@ def format_rows_text( >>> term.screen.text, term.screen.unwrapped_text ('hello wo\nrld', 'hello world') """ - n = len(rows) - if not unwrap or n < 2 or not any(rows[i].wrapped for i in range(n - 1)): - fast_lines = [r.rstrip_text() for r in rows] - while fast_lines and fast_lines[-1] == "": - fast_lines.pop() - return "\n".join(fast_lines) - - lines: list[str] = [] - i = 0 - while i < n: - r = rows[i] - if not (r.wrapped and i + 1 < n): - lines.append(r.rstrip_text()) - i += 1 - continue - parts: list[str] = [] - pending_blanks = 0 - while True: - r = rows[i] - if r.text_used > 0: - if pending_blanks > 0: - parts.append(" " * pending_blanks) - pending_blanks = 0 - parts.append(r.rstrip_text()) - if r.wrapped and i + 1 < n: - eff_cols = ( - r.cols - 1 - if ( - r.cols > 0 - and raw_width_bits(r.attr_at(r.cols - 1)) - == int(WidthRole.SPACER_HEAD) - ) - else r.cols - ) - if r.text_used < eff_cols: - pending_blanks += eff_cols - r.text_used - i += 1 - else: - i += 1 - break - lines.append("".join(parts)) - + if unwrap: + return _unwrapped_text(rows) + lines = [r.rstrip_text() for r in rows] while lines and lines[-1] == "": lines.pop() return "\n".join(lines) diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py index bbe8d92f..9280f392 100644 --- a/src/libvt/terminal.py +++ b/src/libvt/terminal.py @@ -24,6 +24,7 @@ _PEN_BASE_MASK, _PEN_BG_MASK, FrozenRow, + RowLike, _CellExt, _FrozenHistory, _Row, @@ -122,6 +123,8 @@ ScrollRegion, _format_display_row, _HistoryView, + _row_groups, + _unwrapped_rows, format_rows_text, slice_grid, ) @@ -676,7 +679,6 @@ def _make_snapshot( if evicted_total is None else evicted_total ) - snap._text_cache = None snap._unwrapped_text_cache = None snap.cursor = cursor snap.title = title @@ -770,7 +772,6 @@ class Snapshot: "_rows", "_scroll_region", "_scrolled_total", - "_text_cache", "_unwrapped_text_cache", "_vt_pen", "active_is_alt", @@ -796,7 +797,6 @@ class Snapshot: _rows: tuple[_Row, ...] _scroll_region: ScrollRegion _scrolled_total: int - _text_cache: str | None _unwrapped_text_cache: str | None _vt_pen: _VtPen active_is_alt: bool @@ -1078,11 +1078,7 @@ def text(self) -> str: >>> term.committed.text 'top\nnext' """ - cached = self._text_cache - if cached is None: - cached = format_rows_text(self._rows) - object.__setattr__(self, "_text_cache", cached) - return cached + return format_rows_text(self._rows) @property def unwrapped_text(self) -> str: @@ -1412,6 +1408,25 @@ def _vt_wrap_position( return cur.row, col, col +def _unwrapped_style_runs( + rows: collections.abc.Sequence[RowLike], +) -> collections.abc.Iterator[tuple[str, Style, Hyperlink | None]]: + def runs() -> collections.abc.Iterator[tuple[str, Style, Hyperlink | None]]: + for row, padding in _unwrapped_rows(rows, include_styles=True): + yield from ( + (run.text, run.style, run.hyperlink) + for run in RowView(row).runs + if run.text + ) + if padding: + yield " " * padding, DEFAULT_STYLE, None + + for (style, link), group in itertools.groupby( + runs(), key=lambda item: (item[1], item[2]) + ): + yield "".join(text for text, _, _ in group), style, link + + class Formatter: r"""Serialize a :class:`Snapshot` to plain text, VT sequences, or HTML. @@ -1704,72 +1719,17 @@ def _render_html(self, snapshot: Snapshot) -> str: UnderlineStyle.DOTTED: "dotted", UnderlineStyle.DASHED: "dashed", } - n_rows = len(snapshot._rows) - r_idx = 0 - while r_idx < n_rows: - chain_start = r_idx - if self.unwrap: - while snapshot._rows[r_idx].wrapped and r_idx + 1 < n_rows: - r_idx += 1 - chain_end = r_idx - r_idx += 1 - - last_content_idx = -1 - if chain_end > chain_start: - for k in range(chain_end, chain_start - 1, -1): - rk = snapshot._rows[k] - if rk.text_used > 0 or rk.used > 0: - last_content_idx = k - break - - merged_runs: list[tuple[str, Style, Hyperlink | None]] = [] - for k in range(chain_start, chain_end + 1): - row = snapshot._rows[k] - for run in RowView(row).runs: - if not run.text: - continue - if ( - merged_runs - and merged_runs[-1][1] == run.style - and merged_runs[-1][2] == run.hyperlink - ): - prev_txt, _, _ = merged_runs[-1] - merged_runs[-1] = ( - prev_txt + run.text, - run.style, - run.hyperlink, - ) - else: - merged_runs.append((run.text, run.style, run.hyperlink)) - if k < last_content_idx: - eff_cols = ( - row.cols - 1 - if ( - row.cols > 0 - and raw_width_bits(row.attr_at(row.cols - 1)) - == int(WidthRole.SPACER_HEAD) - ) - else row.cols - ) - prev_used = min(eff_cols, row.used) - if prev_used < eff_cols: - gap_txt = " " * (eff_cols - prev_used) - if ( - merged_runs - and merged_runs[-1][1] == DEFAULT_STYLE - and merged_runs[-1][2] is None - ): - prev_txt, _, _ = merged_runs[-1] - merged_runs[-1] = ( - prev_txt + gap_txt, - DEFAULT_STYLE, - None, - ) - else: - merged_runs.append((gap_txt, DEFAULT_STYLE, None)) - + for rows in _row_groups(snapshot._rows, unwrap=self.unwrap): + runs = ( + _unwrapped_style_runs(rows) + if self.unwrap + else ( + (run.text, run.style, run.hyperlink) + for run in RowView(rows[0]).runs + ) + ) chunks: list[str] = [] - for run_text, style, hyperlink in merged_runs: + for run_text, style, hyperlink in runs: escaped = html.escape(run_text) css: list[str] = [] background: str | None = None diff --git a/tests/test_aio.py b/tests/test_aio.py index 3c7d42c4..e1f17896 100644 --- a/tests/test_aio.py +++ b/tests/test_aio.py @@ -1648,7 +1648,7 @@ def unexpected_openpty() -> t.NoReturn: async def test_async_terminal_stream_wait_for_soft_wrapped_substring() -> None: - """``AsyncTerminalStream.wait_for`` matches ``Snapshot.unwrapped_text``.""" + """``AsyncTerminalStream.wait_for`` matches strings split across soft wraps.""" reader = asyncio.StreamReader() reader.feed_data( b"fatal: could not read Username for 'http://127.0.0.1:44765': " @@ -1703,3 +1703,61 @@ async def test_open_pty_wait_for_soft_wrapped_substring() -> None: assert snap[0].wrapped is True assert "terminal prompts disabled" in final_snap.unwrapped_text assert "disablednext-line" not in final_snap.unwrapped_text + + +async def test_async_terminal_stream_string_wait_uses_logical_rows() -> None: + """A physical newline can be inspected with a callable predicate.""" + reader = asyncio.StreamReader() + reader.feed_data(b"hello world\r\nnext") + reader.feed_eof() + async with AsyncTerminalStream( + reader, terminal=libvt.Terminal(rows=3, cols=8) + ) as stream: + snapshot = await stream.wait_for(lambda snap: "hello wo\nrld" in snap.text) + assert snapshot.text == "hello wo\nrld\nnext" + assert snapshot[0].wrapped + with pytest.raises(TerminalTimeoutError, match="EOF"): + await stream.wait_for("hello wo\nrld", attach_note=False) + + +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX pty required") +async def test_pty_string_wait_uses_logical_rows() -> None: + """A PTY wait exposes the same logical text contract as a stream wait.""" + async with open_pty( + (sys.executable, "-u", "-c", "print('hello world'); print('next')"), + rows=4, + cols=8, + ) as session: + snapshot = await session.wait_for(lambda snap: "hello wo\nrld" in snap.text) + assert snapshot[0].wrapped + with pytest.raises(TerminalTimeoutError, match="EOF"): + await session.wait_for("hello wo\nrld", attach_note=False) + + +async def test_async_terminal_stream_waits_for_wrapped_committed_frame() -> None: + """A held wrap becomes visible to a wait when its frame closes.""" + reader = asyncio.StreamReader() + terminal = libvt.Terminal(rows=2, cols=3) + terminal.feed(b"old") + before = terminal.committed + baseline = before.text + stream = AsyncTerminalStream(reader, terminal=terminal) + try: + reader.feed_data(b"\x1b[?2026h\x1b[2J\x1b[HAB\xe7\x95") + await stream.pump_once() + reader.feed_data(b"\x8c") + await stream.pump_once() + assert terminal.text == "AB\n界" + assert terminal.committed.text == baseline + with pytest.raises(TerminalTimeoutError, match="waiting for terminal state"): + await stream.wait_for("AB界", timeout=0, attach_note=False) + + reader.feed_data(b"\x1b[?2026l") + reader.feed_eof() + result = await stream.wait_for("AB界", timeout=0.2) + assert result.text == "AB\n界" + assert result[0].wrapped + assert result.cursor.row == 1 and result.cursor.col == 2 + assert before.text == baseline == "old" + finally: + await stream.aclose() diff --git a/tests/test_terminal.py b/tests/test_terminal.py index 4c454981..51214224 100644 --- a/tests/test_terminal.py +++ b/tests/test_terminal.py @@ -1670,8 +1670,9 @@ def test_backward_tab_uses_the_host_wrap_latch(profile: Profile, keeps: bool) -> assert terminal.lines == (("123456789abz", "X") if keeps else ("12345678Xabz", "")) -def test_unwrapped_text_formatter_bce_cache_and_region() -> None: - """``unwrapped_text``, ``Formatter(unwrap=True)``, and ``render(unwrap=True)``.""" +def test_unwrapped_text_and_formatter_unwrap() -> None: + """``unwrapped_text`` and ``Formatter(unwrap=True)`` join soft-wrapped chains.""" + # 1. ASCII mid-word wrap + styled/hyperlink HTML coalescing across wrap boundary. term = libvt.Terminal(rows=3, cols=8) term.feed(b"hello world") snap = term.committed @@ -1679,8 +1680,6 @@ def test_unwrapped_text_formatter_bce_cache_and_region() -> None: assert term.unwrapped_text == "hello world" assert term.screen.unwrapped_text == "hello world" assert snap.unwrapped_text == "hello world" - assert snap.text is snap.text - assert snap.unwrapped_text is snap.unwrapped_text assert snap.format(OutputFormat.PLAIN) == "hello wo\nrld" assert snap.format(OutputFormat.PLAIN, unwrap=True) == "hello world" assert Formatter(OutputFormat.PLAIN, unwrap=True).format_snapshot(snap) == ( @@ -1692,10 +1691,6 @@ def test_unwrapped_text_formatter_bce_cache_and_region() -> None: assert snap.format(OutputFormat.HTML, unwrap=True) == ( '
\nhello world\n\n
' ) - with pytest.raises(AttributeError): - snap._text_cache = "mutated" - with pytest.raises(AttributeError): - snap._unwrapped_text_cache = "mutated" styled = libvt.Terminal(rows=2, cols=8) styled.feed( @@ -1709,6 +1704,7 @@ def test_unwrapped_text_formatter_bce_cache_and_region() -> None: "" ) + # 2. Wide CJK wrap with SPACER_HEAD (no phantom space on viewport or FrozenRow). cjk = libvt.Terminal(rows=2, cols=5, scrollback=10) cjk.feed("abcd中".encode()) cjk_snap = cjk.committed @@ -1716,20 +1712,26 @@ def test_unwrapped_text_formatter_bce_cache_and_region() -> None: assert cjk.unwrapped_text == "abcd中" assert cjk.screen.unwrapped_text == "abcd中" assert cjk_snap.unwrapped_text == "abcd中" + assert cjk_snap.format(OutputFormat.PLAIN, unwrap=True) == "abcd中" assert cjk_snap.format(OutputFormat.HTML, unwrap=True) == ( '
\nabcd中\n
' ) cjk.feed(b"\r\nrow2\r\nrow3") assert format_rows_text(cjk.screen._history.freeze(), unwrap=True) == "abcd中" + # 3. CUP / cursor-jump gap before wrap. cup = libvt.Terminal(rows=2, cols=6) cup.feed(b"ab\x1b[6Gxy") cup_snap = cup.committed assert cup.unwrapped_text == "ab xy" + assert cup.screen.unwrapped_text == "ab xy" + assert cup_snap.unwrapped_text == "ab xy" + assert cup_snap.format(OutputFormat.PLAIN, unwrap=True) == "ab xy" assert cup_snap.format(OutputFormat.HTML, unwrap=True) == ( '
\nab   xy\n
' ) + # 4. Trimmed wrapped=True row from tmux capture-pane + written trailing spaces. cap_gap = decode_tmux_capture( ["W ab", "- GH"], rows=2, @@ -1737,11 +1739,49 @@ def test_unwrapped_text_formatter_bce_cache_and_region() -> None: flagged=True, trim_trailing=True, ) + assert cap_gap.snapshot.text == "ab\nGH" assert cap_gap.snapshot.unwrapped_text == "ab GH" + assert cap_gap.terminal.unwrapped_text == "ab GH" + assert cap_gap.terminal.screen.unwrapped_text == "ab GH" + assert cap_gap.snapshot.format(OutputFormat.PLAIN, unwrap=True) == "ab GH" assert cap_gap.snapshot.format(OutputFormat.HTML, unwrap=True) == ( '
\nab    GH\n
' ) + cap_trail = decode_tmux_capture( + ["W ab", "- "], + rows=2, + cols=6, + flagged=True, + trim_trailing=True, + ) + assert cap_trail.snapshot.unwrapped_text == "ab" + assert cap_trail.snapshot.format(OutputFormat.PLAIN, unwrap=True) == "ab" + assert cap_trail.snapshot.format(OutputFormat.HTML, unwrap=True) == ( + '
\nab\n
' + ) + + prompt_t = libvt.Terminal(rows=2, cols=8) + prompt_t.feed(b"12345678prompt$ ") + assert prompt_t.committed.unwrapped_text == "12345678prompt$ " + assert prompt_t.committed.format(OutputFormat.PLAIN, unwrap=True) == ( + "12345678prompt$ " + ) + + # 5. Hard linebreak isolation. + hard = libvt.Terminal(rows=3, cols=10) + hard.feed(b"alpha\r\nbeta") + hard_snap = hard.committed + assert hard_snap.unwrapped_text == "alpha\nbeta" + assert "alphabeta" not in hard_snap.unwrapped_text + assert hard_snap.format(OutputFormat.PLAIN, unwrap=True) == "alpha\nbeta" + assert hard_snap.format(OutputFormat.HTML, unwrap=True) == ( + '
\nalpha\nbeta\n\n
' + ) + + +def test_formatter_html_unwrap_bce_continuation_gap() -> None: + """``Formatter(HTML, unwrap=True)`` keeps unwritten gap before BCE-only row.""" cap_bce = decode_tmux_capture( ["W ab", "- \x1b[41m \x1b[0m "], rows=2, @@ -1749,21 +1789,57 @@ def test_unwrapped_text_formatter_bce_cache_and_region() -> None: flagged=True, trim_trailing=False, ) - assert cap_bce.snapshot.format(OutputFormat.HTML, unwrap=True) == ( + snap = cap_bce.snapshot + assert (snap._rows[0].wrapped, snap._rows[0].text_used, snap._rows[0].used) == ( + True, + 2, + 2, + ) + assert (snap._rows[1].text_used, snap._rows[1].used) == (0, 3) + assert snap.unwrapped_text == "ab" + assert snap.format(OutputFormat.HTML, unwrap=True) == ( '
\n'
         'ab       \n'
         "
" ) - sub_t = libvt.Terminal(rows=2, cols=8, scrollback=10) - sub_t.feed(b"hello world\r\nalpha\r\nbeta") + +def test_frozen_snapshot_retains_unwrapped_text_after_resize() -> None: + """Unwrapping a frozen frame uses the wraps captured before reflow.""" + term = libvt.Terminal(rows=3, cols=1) + term.feed(b"abc") + frozen = term.committed + assert frozen.text == "a\nb\nc" + assert frozen.unwrapped_text == "abc" + assert [row.wrapped for row in frozen] == [True, True, False] + assert (frozen.cursor.row, frozen.cursor.col) == (2, 0) + + term.resize(rows=3, cols=5) + term.feed(b"!") + assert term.committed.unwrapped_text == "abc!" + assert frozen.text == "a\nb\nc" + assert frozen.unwrapped_text == "abc" + + +def test_region_view_unwrapped_text_and_render_unwrap() -> None: + """``RegionView.unwrapped_text`` and ``libvt.render(unwrap=True)`` unwrap rows.""" + term = libvt.Terminal(rows=2, cols=8, scrollback=10) + term.feed(b"hello world\r\nalpha\r\nbeta") + snap = term.committed + + assert snap[0:2].unwrapped_text == "alpha\nbeta" + scrolled = snap.viewport(offset=2) + assert scrolled.unwrapped_text == "hello world" + assert scrolled[0:2].unwrapped_text == "hello world" + assert snap[0:0].unwrapped_text == "" + + sub_t = libvt.Terminal(rows=3, cols=8) + sub_t.feed(b"hello world\r\nok") sub_snap = sub_t.committed - assert sub_snap.viewport(offset=2).unwrapped_text == "hello world" - assert sub_snap[0:0].unwrapped_text == "" - narrow_t = libvt.Terminal(rows=3, cols=8) - narrow_t.feed(b"hello world\r\nok") - assert narrow_t.committed[0:2].unwrapped_text == "hello world" - assert narrow_t.committed[0:2, 0:4].unwrapped_text == "hell\nrld" + assert sub_snap[0:2].unwrapped_text == "hello world" + assert sub_snap[0:2, 0:4].unwrapped_text == "hell\nrld" + assert sub_snap[0:2, 2:6].unwrapped_text == sub_snap[0:2, 2:6].text == "llo\nd" + assert sub_t.screen[0:2, 2:6].unwrapped_text == "llo\nd" assert libvt.render(b"hello world\r\nok", rows=3, cols=8) == "hello wo\nrld\nok" assert ( @@ -1771,3 +1847,49 @@ def test_unwrapped_text_formatter_bce_cache_and_region() -> None: == "hello world\nok" ) assert libvt.render("abcd中", rows=2, cols=5, unwrap=True) == "abcd中" + + +def test_viewport_unwrap_uses_current_width_after_no_reflow_resize() -> None: + """Older history widths preserve live wraps in a full-width viewport.""" + term = libvt.Terminal(rows=3, cols=8, scrollback=10) + term.feed(b"old\r\n\r\n\r\n") + old = term.committed + term.resize(rows=3, cols=4, reflow=False) + term.feed(b"\x1b[Habcdef") + snap = term.committed + viewport = snap.viewport(1) + + assert old.cols == 8 and old.viewport(1).lines == ("old", "", "") + assert viewport.cols == snap.cols == 4 + assert viewport.lines == ("old", "abcd", "ef") + assert [row.wrapped for row in viewport] == [False, True, False] + assert (snap.cursor.row, snap.cursor.col) == (1, 2) + assert viewport.text == "old\nabcd\nef" + assert viewport.unwrapped_text == "old\nabcdef" + assert viewport[:].unwrapped_text == "old\nabcdef" + assert viewport[1:].unwrapped_text == "abcdef" + assert snap[:, :3].unwrapped_text == "abc\nef" + assert snap[:, :3][:].unwrapped_text == "abc\nef" + + +def test_unwrapped_viewport_preserves_hidden_historical_wrap_margin() -> None: + """A clipped history edge stays a line break beside a visible live wrap.""" + capture = decode_tmux_capture( + ["W ab", "- C", "- ", "- ", "- ", "- "], + rows=4, + cols=8, + flagged=True, + trim_trailing=True, + ) + term = capture.terminal + original = term.committed.viewport(2) + term.resize(rows=4, cols=4, reflow=False) + term.feed(b"\x1b[Habcdef") + region = term.committed.viewport(2) + + assert region.lines == ("ab", "C", "abcd", "ef") + assert tuple(row.wrapped for row in region) == (True, False, True, False) + assert region[:2].unwrapped_text == "ab\nC" + assert region[2:].unwrapped_text == "abcdef" + assert region.unwrapped_text == "ab\nC\nabcdef" + assert original.unwrapped_text == "ab C" From 134ca3831886ca3a1d8b7b530e3c3b5fae377f0a Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Wed, 2 Dec 2026 20:43:26 -0600 Subject: [PATCH 5/5] CHANGES(docs): Explain logical-line waits why: A prompt can cross a soft wrap, while some tests need to match physical newlines. what: - Document unwrapped text and the snapshot predicate for physical rows. --- CHANGES | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/CHANGES b/CHANGES index 2e0c1a00..2fb8071c 100644 --- a/CHANGES +++ b/CHANGES @@ -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 ` for plain text or HTML. + ### Fixes #### Diagnose a bare PTY command (#165) @@ -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