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 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/snapshots.md b/docs/topics/snapshots.md index dbc1661c..79422a71 100644 --- a/docs/topics/snapshots.md +++ b/docs/topics/snapshots.md @@ -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 @@ -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 diff --git a/docs/topics/sync-and-asyncio.md b/docs/topics/sync-and-asyncio.md index ead55bb0..ca51e003 100644 --- a/docs/topics/sync-and-asyncio.md +++ b/docs/topics/sync-and-asyncio.md @@ -87,10 +87,13 @@ 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. 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 diff --git a/src/libvt/aio.py b/src/libvt/aio.py index 08d37b5e..74a1ebc1 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``. Pass a + callable using ``snapshot.text`` to test physical rows. + """ async def aclose(self) -> object: """Close the session and expire any active ``?2026`` hold.""" @@ -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) @@ -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`. @@ -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 ) @@ -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`. @@ -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 ) diff --git a/src/libvt/screen.py b/src/libvt/screen.py index 3ef1413c..847900ba 100644 --- a/src/libvt/screen.py +++ b/src/libvt/screen.py @@ -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 @@ -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() @@ -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: ... diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py index 16935d9e..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,6 +679,7 @@ def _make_snapshot( if evicted_total is None else evicted_total ) + snap._unwrapped_text_cache = None snap.cursor = cursor snap.title = title snap.cwd = cwd @@ -768,6 +772,7 @@ class Snapshot: "_rows", "_scroll_region", "_scrolled_total", + "_unwrapped_text_cache", "_vt_pen", "active_is_alt", "appearance", @@ -792,6 +797,7 @@ class Snapshot: _rows: tuple[_Row, ...] _scroll_region: ScrollRegion _scrolled_total: int + _unwrapped_text_cache: str | None _vt_pen: _VtPen active_is_alt: bool appearance: Appearance @@ -1074,6 +1080,26 @@ 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' + """ + 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: ... @@ -1116,6 +1142,7 @@ def format( *, policy: Policy = DEFAULT_POLICY, profile: Profile = DEFAULT_PROFILE, + unwrap: bool = False, ) -> str: r"""Render this snapshot using :class:`Formatter`. @@ -1133,6 +1160,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 +1172,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]: @@ -1377,23 +1408,54 @@ 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 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 +1463,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 +1719,18 @@ def _render_html(self, snapshot: Snapshot) -> str: UnderlineStyle.DOTTED: "dotted", UnderlineStyle.DASHED: "dashed", } - for row in snapshot._rows: - view = RowView(row) + 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 in view.runs: - escaped = html.escape(run.text) - style = run.style + for run_text, style, hyperlink in runs: + escaped = html.escape(run_text) css: list[str] = [] background: str | None = None if style.bold: @@ -1718,10 +1788,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 +2909,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. @@ -7348,14 +7431,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, @@ -7368,7 +7475,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 227dcb47..e1f17896 100644 --- a/tests/test_aio.py +++ b/tests/test_aio.py @@ -1645,3 +1645,119 @@ 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 + 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") + 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 + + +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 0e851f43..51214224 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,228 @@ 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
' + ) + + +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.unwrapped_text == "ab" + assert snap.format(OutputFormat.HTML, unwrap=True) == ( + '
\n'
+        'ab       \n'
+        "
" + ) + + +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[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中" + + +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"