diff --git a/CHANGES b/CHANGES index ca1c339..db4b065 100644 --- a/CHANGES +++ b/CHANGES @@ -6,6 +6,37 @@ _Notes on the upcoming release will go here._ +### Breaking changes + +#### Scrub each captured viewport row (#149) + +{func}`~libvt.testing.serialize_vt_snapshot` and +{func}`~libvt.testing.vt_screen` match scrubbers within individual captured +rows. To scrub a temporary path, choose a `TMPDIR` and viewport that keep +the path on one row. Include padding in fixed-width field patterns to +keep dividers at their captured columns. + +```python +# Before +scrubbers = [(r"pid=\d+", "pid=")] + +# After +scrubbers = [(r"pid=\d+ +", "pid= ")] +``` + +See {ref}`topics-testing` for runnable examples. + +### Fixes + +#### Keep erased viewport text separate from scrollback (#149) + +Widening the terminal after an in-place display erase leaves fresh text +and blank rows in view. Scrollback retains the earlier text as a separate +line. The Ghostty profile retains incoming wraps across the applicable +display or line erases and alignment tests. Custom profiles can select +that behavior with `erase_severs_history_wrap=False` on +{class}`~libvt.config.ScreenBehavior`. + ## 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 56f039a..0055ea3 100644 --- a/MIGRATION +++ b/MIGRATION @@ -14,6 +14,15 @@ downstream projects (and `>=0.x,<0.y` once `0.1.0` is released). _Detailed migration steps for the next version will be posted here._ +### Boxed snapshot scrubbers match one row at a time (#149) + +Set the child process's `TMPDIR` and choose viewport dimensions that keep +dynamic values on one row before passing them to +{func}`~libvt.testing.vt_screen`. Match padding explicitly when masking a +fixed-width field. For logical text from a line-oriented command, scrub +the output of {func}`~libvt.terminal.strip`. Use {ref}`topics-testing` +for runnable examples. + ## libvt 0.0.1a2 (2026-11-28) ### Curated PEP 562 `libvt` root exports (#43) diff --git a/docs/api/contrib_syrupy.md b/docs/api/contrib_syrupy.md index f27a908..2912e1c 100644 --- a/docs/api/contrib_syrupy.md +++ b/docs/api/contrib_syrupy.md @@ -30,7 +30,7 @@ uninstalled or disabled via `-p no:syrupy`): See {doc}`../topics/testing` for using {func}`~libvt.testing.serialize_vt_snapshot` and {func}`~libvt.testing.vt_screen` -without `syrupy`, or configuring project-wide `.ambr` scrubbers with +without `syrupy`, or sharing row scrubbers with {meth}`VtSnapshotExtension.configure `. ## Fixture diff --git a/docs/api/testing.md b/docs/api/testing.md index 6a48cc6..5684590 100644 --- a/docs/api/testing.md +++ b/docs/api/testing.md @@ -1,7 +1,7 @@ # `libvt.testing` Tool-agnostic visual screen assertions, boxed VT + `SGR` snapshot -serialization, regime-aware dynamic-value scrubbing, and diff formatting with +serialization, row-local scrubbing, and diff formatting with no runtime dependencies: ```python diff --git a/docs/quickstart.md b/docs/quickstart.md index 0855c3f..03ad417 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -138,7 +138,7 @@ coordinates; {func}`libvt.testing.assert_screen_box` checks column-aligned For multi-row TUIs, `SGR` color palettes, hyperlinks, or `tmux` captures, {func}`~libvt.testing.vt_screen` and {func}`~libvt.testing.serialize_vt_snapshot` emit escape-free boxes with -run-length `styles:` spans and regime-aware regex scrubbing: +run-length `styles:` spans and per-row regex scrubbing: ```python >>> import libvt diff --git a/docs/topics/testing.md b/docs/topics/testing.md index 7d96c24..aac45f8 100644 --- a/docs/topics/testing.md +++ b/docs/topics/testing.md @@ -90,43 +90,96 @@ styles: r0[6..10]: fg=#ff8c00 ``` -### Scrubbing dynamic values without breaking box borders +### Scrubbing dynamic values -Naive string replacement shifts right-hand `│` borders whenever a PID, port, or -duration changes character length. {func}`~libvt.testing.vt_screen` adapts -scrubbing to the active screen regime: +{func}`~libvt.testing.vt_screen` applies each pattern to one visible row at +a time. The box keeps the viewport size, row order, and soft-wrap markers from +the frame. A replacement can shift later columns in its row, including the +cursor. The serializer clips text at the right edge. -- Fixed-row 2D screens (`alt=True` or `!DECAWM`) absorb width deltas between a - matched token and its replacement into adjacent whitespace slack inside the - same `│`-delimited cell before shifting right-hand dividers. -- Primary autowrap streams (`alt=False` and `DECAWM`) coalesce contiguous - soft-wrapped row chains before regex matching and re-wrap to terminal width - without pulling cleared scrollback (`CSI 2 J` / `Ctrl-L`) back onscreen. +To keep a divider at a fixed column, match the whole field, including its +padding, and supply a replacement of the same display width. ```python ->>> import libvt +>>> from libvt import Terminal >>> from libvt.testing import serialize_vt_snapshot, vt_screen ->>> tui = libvt.Terminal(rows=3, cols=24) ->>> tui.feed( -... "\x1b[?1049h\x1b[H" -... "┌──────────────────────┐\r\n" -... "│ worker pid=9 OK │\r\n" -... "└──────────────────────┘".encode() -... ) ->>> tui_wide_pid = libvt.Terminal(rows=3, cols=24) ->>> tui_wide_pid.feed( -... "\x1b[?1049h\x1b[H" -... "┌──────────────────────┐\r\n" -... "│ worker pid=48291 OK │\r\n" -... "└──────────────────────┘".encode() -... ) ->>> scrub = [(r"pid=\d+", "pid=")] ->>> serialize_vt_snapshot(vt_screen(tui, scrubbers=scrub)) == serialize_vt_snapshot( -... vt_screen(tui_wide_pid, scrubbers=scrub) +>>> term = Terminal(rows=2, cols=16) +>>> term.feed_str("\x1b[?1049h┌──────────────┐\r\n│ pid=9 OK│") +>>> view = vt_screen(term, scrubbers=[(r"pid=\d+ +", "pid= ")]) +>>> print(serialize_vt_snapshot(view)) +size=16x2 cursor=(1,15,vis=True) alt=True modes=[] +┌────────────────┐ +│┌──────────────┐│ +││ pid= OK││ +└────────────────┘ +``` + +Pass the source frame with `region=` to measure replacement glyphs with its +profile and grapheme mode. A standalone {class}`~libvt.screen.RegionView` uses +the default profile and grapheme mode for new glyphs. Both forms keep the +captured cell widths outside the edited text. + +```python +>>> from libvt import Profile, Terminal +>>> from libvt.config import UnicodeBehavior +>>> from libvt.testing import serialize_vt_snapshot, vt_screen +>>> profile = Profile(unicode=UnicodeBehavior(ambiguous_width=2)) +>>> term = Terminal(rows=1, cols=6, profile=profile) +>>> term.feed(b"\x1b[32mAxB") +>>> crop = vt_screen(term, region=(0, 1, 0, 6), scrubbers=[(r"x", "Ω")]) +>>> print(serialize_vt_snapshot(crop)) +size=6x1 region=True +┌──────┐ +│AΩB │ +└──────┘ +styles: + r0[0..4]: fg=green +``` + +### Temporary paths in command output + +Set the temporary root in the child process environment and give the +terminal enough columns for the longest permitted path. Use +{func}`~libvt.aio.open_pty`'s `env`, `rows`, and `cols` when the child uses +a PTY. Here a linear Python command writes to a pipe and the caller uses an +escaped path pattern for both the box and a plain-text assertion. + +```python +>>> import os +>>> import pathlib +>>> import re +>>> import subprocess +>>> import sys +>>> import tempfile +>>> from libvt import Terminal, strip +>>> from libvt.testing import serialize_vt_snapshot, vt_screen +>>> script = ( +... "import tempfile\n" +... "with tempfile.TemporaryDirectory(prefix='run-') as run:\n" +... " print(f'Log: {run}')\n" +... "print('Done', end='')" ... ) -True +>>> with tempfile.TemporaryDirectory() as tmpdir: +... output = subprocess.check_output( +... [sys.executable, "-c", script], +... env={**os.environ, "TMPDIR": tmpdir, "PYTHONIOENCODING": "utf-8"}, +... ) +>>> prefix = re.escape(str(pathlib.Path(tmpdir) / "run-")) +>>> path_pattern = re.compile(prefix + r"[^\r\n]+") +>>> term = Terminal(rows=2, cols=len(tmpdir.encode()) + 40, newline_mode=True) +>>> term.feed(output) +>>> boxed = serialize_vt_snapshot(vt_screen(term, scrubbers=[(path_pattern, "")])) +>>> tuple(row.strip("│ ") for row in boxed.splitlines()[2:4]) +('Log: ', 'Done') +>>> path_pattern.sub("", strip(output)).splitlines() +['Log: ', 'Done'] ``` +Use {func}`~libvt.terminal.strip` on captured command output when you want +to check its logical text. For applications that redraw with cursor +controls, use `vt_screen` or `term.committed.text` to check the displayed +frame. + ### Region slices and step-by-step TUI deltas Pass `region=(start_row, end_row, start_col, end_col)` to serialize one toolbar @@ -242,10 +295,9 @@ from `pytest --fixtures` when `syrupy` is uninstalled or disabled via >>> test_worker_row(_CheckAmbr()) # doctest: +HIDE ``` -### Project-wide `.ambr` scrubbers +### Shared row scrubbers -To share scrubbers across every `.ambr` test in a repository, build a memoized -subclass with +To share row scrubbers across snapshot tests, build a memoized subclass with {meth}`VtSnapshotExtension.configure ` and bind it with `snapshot.use_extension(...)` inside a `conftest.py` fixture: diff --git a/src/libvt/_grid.py b/src/libvt/_grid.py index 498243a..a6d7470 100644 --- a/src/libvt/_grid.py +++ b/src/libvt/_grid.py @@ -18,6 +18,7 @@ import array import bisect import collections.abc +import dataclasses import operator import typing as t from dataclasses import dataclass @@ -1402,6 +1403,28 @@ def replace_all(self, rows: collections.abc.Sequence[RowLike]) -> int: self._snapshot = None return evicted + def sever_last_wrap(self) -> bool: + """Clear ``wrapped`` and trailing ``SPACER_HEAD`` on ``self[-1]`` via CoW.""" + if self._len == 0: + return False + last = self[-1] + if not last.wrapped: + return False + end = last.cols - 1 + if raw_width_bits(last.attr_at(end)) == int(WidthRole.SPACER_HEAD): + row = last.thaw() + row.clear_spacer_head(end) + row.wrapped = False + severed = row.freeze() + else: + severed = dataclasses.replace(last, wrapped=False) + if self._tail: + self._tail[-1] = severed + else: + self._blocks[-1] = (*self._blocks[-1][:-1], severed) + self._snapshot = None + return True + def freeze(self) -> _FrozenHistory: """Capture an ``O(1)`` CoW :class:`_FrozenHistory` snapshot.""" if self._snapshot is not None: diff --git a/src/libvt/config.py b/src/libvt/config.py index 50c5603..edd4ca1 100644 --- a/src/libvt/config.py +++ b/src/libvt/config.py @@ -193,6 +193,10 @@ class ScreenBehavior: When ``True``, primary-screen ``CSI 2 J`` (and ``CSI J`` at ``(0, 0)``) scrolls rows up to the last non-empty or image-bearing row into scrollback before clearing with ``BCE``. + erase_severs_history_wrap : bool + When ``True``, an in-place ``ED`` or ``EL`` that erases the incoming + continuation at the top of the screen ends the scrollback line, as + does ``DECALN``. When ``False``, these operations retain the soft wrap. top_margin_scrolls_to_history : bool When ``True``, primary-screen full-width upward scrolls push ``DECSTBM``'s top row into scrollback even when ``top > 0``. @@ -257,6 +261,7 @@ class ScreenBehavior: reflow_on_resize: bool = True ed3_clears_scrollback_on_alt: bool = False ed2_scrolls_primary_to_history: bool = False + erase_severs_history_wrap: bool = True top_margin_scrolls_to_history: bool = False hpr_vpr_enabled: bool = True il_dl_resets_col: bool = True diff --git a/src/libvt/profiles.py b/src/libvt/profiles.py index 8e01572..6185b50 100644 --- a/src/libvt/profiles.py +++ b/src/libvt/profiles.py @@ -55,6 +55,10 @@ queries=QueryBehavior( xtsmgraphics_enabled=False, ), + screen=ScreenBehavior( + # libghostty-vt retains the scrollback row's wrap after ED/EL and DECALN. + erase_severs_history_wrap=False, + ), ) #: ``Kitty`` host terminal profile (CSI u keyboard stack, XTGETTCAP, reflow). diff --git a/src/libvt/screen.py b/src/libvt/screen.py index 4b15ae4..753e41b 100644 --- a/src/libvt/screen.py +++ b/src/libvt/screen.py @@ -942,6 +942,7 @@ class Screen: "_history", "_history_clear_at", "_history_clear_seq", + "_history_sever_seq", "_is_alt", "_max_image_dimension", "_max_images", @@ -990,6 +991,7 @@ def __init__( self._evicted_total: int = 0 self._history_clear_at: int = 0 self._history_clear_seq: int = 0 + self._history_sever_seq: int = 0 self._is_alt: bool = is_alt self._top_margin_scrolls_to_history: bool = ( top_margin_scrolls_to_history and not is_alt @@ -1133,21 +1135,84 @@ def _clear_row_spacer_head(self, row_obj: _Row) -> bool: return False return row_obj.clear_spacer_head(self._cols - 1) + def _sever_history_wrap(self) -> None: + if self._history.sever_last_wrap(): + self._history_sever_seq += 1 + self._gen_counter.next() + + def _sever_incoming_wrap( + self, row: int, *, start: int = 0, selective: bool = False + ) -> None: + """End the preceding soft wrap when the continuation starts in the erase.""" + target = self._rows[row] + if start != 0 and ( + start != 1 + or raw_width_bits(target.attr_at(1)) != int(WidthRole.SPACER_TAIL) + ): + return + if selective and target.is_protected(0): + return + if row == 0: + if self._profile.screen.erase_severs_history_wrap: + self._sever_history_wrap() + else: + prev = self._rows[row - 1] + self._clear_row_spacer_head(prev) + prev.wrapped = False + + def _heal_before_erase( + self, row: int, start: int, end: int, *, selective: bool + ) -> None: + self._heal_before_edit( + row, + start, + end, + selective=selective, + retain_history_wrap=not self._profile.screen.erase_severs_history_wrap, + ) + def heal_before_edit(self, row: int, col_start: int, col_end: int) -> None: """Repair cross-row ``SPACER_HEAD`` pairs before mutating cells.""" + self._heal_before_edit(row, col_start, col_end) + + def _heal_before_edit( + self, + row: int, + col_start: int, + col_end: int, + *, + selective: bool = False, + retain_history_wrap: bool = False, + ) -> None: if not (0 <= row < len(self._rows)): return - if col_start <= 1 and row > 0: - prev = self._rows[row - 1] - if self._clear_row_spacer_head(prev): - prev.wrapped = False - self._rows[row]._heal_wide_boundary(0) + cur = self._rows[row] + if col_start <= 1 and (not selective or not cur.is_protected(0)): + if row > 0: + prev = self._rows[row - 1] + if self._clear_row_spacer_head(prev): + prev.wrapped = False + cur._heal_wide_boundary(0) + elif ( + not retain_history_wrap + and self._history + and (last_h := self._history[-1]).wrapped + and raw_width_bits(last_h.attr_at(last_h.cols - 1)) + == int(WidthRole.SPACER_HEAD) + ): + self._sever_history_wrap() + cur._heal_wide_boundary(0) if col_end > self._cols - 1: - cur = self._rows[row] + next_row = self._rows[row + 1] if row + 1 < len(self._rows) else None + if selective and ( + cur.is_protected(self._cols - 1) + or (next_row is not None and next_row.is_protected(0)) + ): + return if self._clear_row_spacer_head(cur): cur.wrapped = False - if row + 1 < len(self._rows): - self._rows[row + 1]._heal_wide_boundary(0) + if next_row is not None: + next_row._heal_wide_boundary(0) def heal_wrapped_spacer_head(self, row: int) -> None: """Clear preceding ``SPACER_HEAD`` and ``wrapped`` if ``(row, 0)`` splits.""" @@ -1441,6 +1506,8 @@ def push_scrollback_and_clear( ) elif self._gfx is not None: self._gfx.clear_active_screen(self._scrolled_total, len(self._rows)) + if last_used < 0 and not self._is_alt: + self._sever_history_wrap() for r in self._rows: r.reset_blank(self._cols, bce_word) @@ -1483,6 +1550,7 @@ def _reflow_primary( new_cur_col = 0 new_pending_wrap = False cursor_placed = False + viewport_start = 0 idx = 0 while idx < total: @@ -1514,6 +1582,8 @@ def _reflow_primary( continue group_start = idx + if group_start == hist_len: + viewport_start = len(new_all) while idx + 1 < total: cur_src = ( hist_rows[idx] if idx < hist_len else self._rows[idx - hist_len] @@ -1708,6 +1778,10 @@ def _reflow_primary( ) hist_cut = max(0, len(new_all) - rows) + # Keep existing bottom padding from pulling hard history lines into view. + if hist_cut < viewport_start: + trailing_blanks = len(self._rows) - last_active - 1 + hist_cut = min(viewport_start, hist_cut + trailing_blanks) hist_cut = min(hist_cut, new_cur_abs) prev_scrolled = self._scrolled_total @@ -1889,6 +1963,7 @@ def reset(self) -> None: """Clear all visible rows, margins, cursor, keyboard stack, and tabstops.""" if self._on_mutate is not None: self._on_mutate(True) + self._sever_history_wrap() rows = len(self._rows) for r in self._rows: r.reset_blank(self._cols) diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py index cdb7c22..cfce369 100644 --- a/src/libvt/terminal.py +++ b/src/libvt/terminal.py @@ -225,7 +225,7 @@ class ResyncReason(enum.StrEnum): INITIAL = "initial" #: Token belonged to another :class:`Terminal` or different ``view``. TERMINAL_MISMATCH = "terminal_mismatch" - #: Terminal resized, reset, or switched state across an epoch boundary. + #: Terminal resized, reset, switched screens, or rewrote retained history. EPOCH_CHANGED = "epoch_changed" #: Scrollback evicted rows older than the caller's previous watermark. HISTORY_EVICTED = "history_evicted" @@ -1331,7 +1331,7 @@ def _render_vt(self, snapshot: Snapshot) -> str: if cur_style != DEFAULT_STYLE: out.append("\x1b[0m") cur_style = DEFAULT_STYLE - out.append(f" \x1b[{r_idx + 1};1H\x1b[K") + out.append(f" \x1b[{r_idx + 1};1H\x1b[X") if eff_wrapped: has_spacer_head = ( cols > 0 @@ -2738,7 +2738,7 @@ def _live_sync_token( _SyncState( terminal_id=self._terminal_id, view=view, - epoch=self._epoch, + epoch=self._epoch + prim._history_sever_seq, revision=self._screens._row_gen, scrolled_total=prim._scrolled_total, evicted_total=prim._evicted_total, @@ -4669,6 +4669,7 @@ def _handle_esc(self, intermediates: bytes, final: int) -> None: self._docs_utf8_active = False elif intermediates == b"#" and final == 0x38: # DECALN self._before_mutate() + scr._sever_incoming_wrap(0) fill = "E" * scr.cols for r in scr._rows: r.reset_blank(scr.cols) @@ -5228,7 +5229,8 @@ def _erase_display( if mode == 0: if not phantom: - scr.heal_before_edit(c_row, c_col, scr.cols) + scr._sever_incoming_wrap(c_row, start=c_col, selective=selective) + scr._heal_before_erase(c_row, c_col, scr.cols, selective=selective) scr._rows[c_row].clear_range( c_col, scr.cols, @@ -5236,7 +5238,8 @@ def _erase_display( bce_e, selective=selective, ) - scr._rows[c_row].wrapped = False + if not selective: + scr._rows[c_row].wrapped = False if not selective and scr._gfx is not None and scr._gfx.has_sixels: scr._gfx.erase_sixel_rect( row=c_row, @@ -5248,6 +5251,7 @@ def _erase_display( ) self._notify_erase(Rect(c_row, c_col, 1, scr.cols - c_col), cause) for r in range(c_row + 1, scr.rows): + scr._sever_incoming_wrap(r, selective=selective) scr._rows[r].clear_range(0, scr.cols, bce_w, bce_e, selective=selective) if c_row + 1 < scr.rows: if not selective and scr._gfx is not None and scr._gfx.has_sixels: @@ -5266,8 +5270,11 @@ def _erase_display( elif mode == 1: end_c = scr.cols if phantom else c_col + 1 for r in range(c_row): + scr._sever_incoming_wrap(r, selective=selective) scr._rows[r].clear_range(0, scr.cols, bce_w, bce_e, selective=selective) - scr.heal_before_edit(c_row, 0, end_c) + if c_row == 0 or end_c >= scr.cols: + scr._sever_incoming_wrap(c_row, selective=selective) + scr._heal_before_erase(c_row, 0, end_c, selective=selective) scr._rows[c_row].clear_range( 0, end_c, @@ -5275,6 +5282,8 @@ def _erase_display( bce_e, selective=selective, ) + if not selective and end_c >= scr.cols: + scr._rows[c_row].wrapped = False if not selective and scr._gfx is not None and scr._gfx.has_sixels: if c_row > 0: scr._gfx.erase_sixel_rect( @@ -5298,6 +5307,7 @@ def _erase_display( self._notify_erase(Rect(c_row, 0, 1, end_c), cause) elif mode == 2: for r in range(scr.rows): + scr._sever_incoming_wrap(r, selective=selective) scr._rows[r].clear_range(0, scr.cols, bce_w, bce_e, selective=selective) if not selective and scr._gfx is not None: scr._gfx.clear_active_screen(scr._scrolled_total, scr.rows) @@ -5307,6 +5317,7 @@ def _erase_display( scr.push_scrollback_and_clear(bce_w) else: for r in range(scr.rows): + scr._sever_incoming_wrap(r) scr._rows[r].clear_range(0, scr.cols, bce_w, bce_e) if scr._gfx is not None: scr._gfx.clear_active_screen(scr._scrolled_total, scr.rows) @@ -5332,7 +5343,8 @@ def _erase_line( c_col = scr._cur_col sixel_pol = self._profile.screen.sixel_erase_policy if mode == 0: - scr.heal_before_edit(c_row, c_col, scr.cols) + scr._sever_incoming_wrap(c_row, start=c_col, selective=selective) + scr._heal_before_erase(c_row, c_col, scr.cols, selective=selective) scr._rows[c_row].clear_range( c_col, scr.cols, @@ -5340,7 +5352,8 @@ def _erase_line( bce_e, selective=selective, ) - scr._rows[c_row].wrapped = False + if not selective: + scr._rows[c_row].wrapped = False if not selective and scr._gfx is not None and scr._gfx.has_sixels: scr._gfx.erase_sixel_rect( row=c_row, @@ -5353,7 +5366,9 @@ def _erase_line( self._notify_erase(Rect(c_row, c_col, 1, scr.cols - c_col), cause) elif mode == 1: end_c = scr.cols if phantom else c_col + 1 - scr.heal_before_edit(c_row, 0, end_c) + if end_c >= scr.cols: + scr._sever_incoming_wrap(c_row, selective=selective) + scr._heal_before_erase(c_row, 0, end_c, selective=selective) scr._rows[c_row].clear_range( 0, end_c, @@ -5361,7 +5376,7 @@ def _erase_line( bce_e, selective=selective, ) - if end_c >= scr.cols: + if not selective and end_c >= scr.cols: scr._rows[c_row].wrapped = False if not selective and scr._gfx is not None and scr._gfx.has_sixels: scr._gfx.erase_sixel_rect( @@ -5374,7 +5389,8 @@ def _erase_line( ) self._notify_erase(Rect(c_row, 0, 1, end_c), cause) elif mode == 2: - scr.heal_before_edit(c_row, 0, scr.cols) + scr._sever_incoming_wrap(c_row, selective=selective) + scr._heal_before_erase(c_row, 0, scr.cols, selective=selective) scr._rows[c_row].clear_range( 0, scr.cols, @@ -5382,6 +5398,8 @@ def _erase_line( bce_e, selective=selective, ) + if not selective: + scr._rows[c_row].wrapped = False if not selective and scr._gfx is not None and scr._gfx.has_sixels: scr._gfx.erase_sixel_rect( row=c_row, diff --git a/src/libvt/testing.py b/src/libvt/testing.py index e1bbf07..e44b4f7 100644 --- a/src/libvt/testing.py +++ b/src/libvt/testing.py @@ -4,6 +4,7 @@ import collections.abc import difflib +import itertools import re import textwrap import typing as t @@ -20,7 +21,7 @@ from libvt.config import DEFAULT_PROFILE, Profile, UnicodeBehavior from libvt.exc import ScreenAssertionError from libvt.modes import ALT_SCREEN_MODES, TRANSIENT_SNAPSHOT_MODES, Mode -from libvt.screen import RegionView, RowRun, RowView, Screen +from libvt.screen import Cell, RegionView, RowView, Screen from libvt.style import ( DEFAULT_STYLE, AnsiColor, @@ -445,7 +446,7 @@ class VtScreenView: emits only the compact contextual delta from *diff* to *target*. scrubbers : tuple[ScrubberSpec, ...] Regex ``(pattern, replacement)`` pairs applied on top of any caller or - extension scrubbers using regime-aware width normalization. + extension scrubbers to the text of each visible row. region : tuple[int, int, int, int] | None Optional ``(start_row, end_row, start_col, end_col)`` slice extracted from *target* (and *diff* when given) prior to serialization. @@ -498,9 +499,10 @@ def vt_screen( Previous terminal or snapshot state; when provided, serializes only the contextual diff between *diff* and *target* (``"(unchanged)"`` when equal). scrubbers : Sequence[ScrubberSpec], optional - Additional ``(pattern, replacement)`` scrubbers applied for this view. + Additional ``(pattern, replacement)`` scrubbers applied within each row. region : tuple[int, int, int, int] | None, optional Half-open ``(start_row, end_row, start_col, end_col)`` viewport slice. + Replacement glyphs use the source frame's width settings. include_styles : bool | None, optional Override whether the ``styles:`` footer is emitted. include_cursor_shape : bool | None, optional @@ -518,7 +520,7 @@ def vt_screen( >>> term = Terminal(rows=2, cols=16) >>> term.feed(b"pid=4821 OK") >>> view = vt_screen(term, scrubbers=[(r"pid=\d+", "pid=")]) - >>> "│pid= OK │" in serialize_vt_snapshot(view) + >>> "│pid= OK │" in serialize_vt_snapshot(view) True """ return VtScreenView( @@ -536,6 +538,7 @@ class _CellMeta: ch: str style: Style hyperlink: Hyperlink | None + source: tuple[int, Cell] | None = None def _compile_scrubbers( @@ -603,73 +606,88 @@ def _canonical_modes(enabled: collections.abc.Set[Mode]) -> list[str]: return tokens -def _row_to_cells(row: RowView, *, trim_trailing_unstyled: bool) -> list[_CellMeta]: +def _row_to_cells(row: RowView) -> list[_CellMeta]: cells: list[_CellMeta] = [] - runs: tuple[RowRun, ...] = row.runs - for idx, run in enumerate(runs): - txt = sanitize_terminal_text(run.text) - if ( - trim_trailing_unstyled - and idx == len(runs) - 1 - and run.style == DEFAULT_STYLE - and run.hyperlink is None - ): - txt = txt.rstrip(" ") - cells.extend(_CellMeta(ch, run.style, run.hyperlink) for ch in txt) + limit = min(len(row), row._current_row().used - row._col_range.start) + for col in range(limit): + cell = row[col] + if cell.width_role == WidthRole.SPACER_TAIL and col > 0: + continue + if cell.width == 0 or col + cell.width > len(row): + cells.append(_CellMeta(" ", cell.style, cell.hyperlink)) + else: + cells.extend( + _CellMeta(ch, cell.style, cell.hyperlink, (col, cell)) + for ch in sanitize_terminal_text(cell.text) + ) return cells -def _cells_width( - cells: collections.abc.Sequence[_CellMeta], +def _display_glyphs( + cells: list[_CellMeta], *, mode_2027: bool, profile: Profile, -) -> int: - text = "".join(c.ch for c in cells) - return sum( - display_width(cluster, mode_2027=mode_2027, profile=profile) - for cluster in segment_graphemes(text) - ) +) -> collections.abc.Iterator[tuple[str, int, _CellMeta]]: + start = 0 + for glyph in segment_graphemes("".join(cell.ch for cell in cells)): + end = start + len(glyph) + glyph_cells = cells[start:end] + start = end + captured: list[tuple[str, int, _CellMeta]] = [] + next_col: int | None = None + for source, group in itertools.groupby( + glyph_cells, key=lambda cell: cell.source + ): + if source is None: + break + col, original = source + original_cells = list(group) + text = "".join(cell.ch for cell in original_cells) + if text != original.text or (next_col is not None and col != next_col): + break + captured.append((text, original.width, original_cells[0])) + next_col = col + original.width + else: + # Source boundaries can differ from grapheme boundaries in legacy mode. + yield from captured + continue + + width = display_width(glyph, mode_2027=mode_2027, profile=profile) + yield glyph, width, glyph_cells[0] -def _display_col_to_char_idx( +def _cursor_text_offset( cells: list[_CellMeta], target_col: int, *, - pad_spaces: bool, mode_2027: bool, profile: Profile, -) -> int: - """Convert zero-based display *target_col* into a ``cells`` index.""" - col = 0 - pos = 0 - for cl in segment_graphemes("".join(c.ch for c in cells)): - cw = display_width(cl, mode_2027=mode_2027, profile=profile) - if col + cw > target_col and cw > 0: - return pos - col += cw - pos += len(cl) - if target_col > col and pad_spaces: - extra = target_col - col - cells.extend([_CellMeta(" ", DEFAULT_STYLE, None)] * extra) - pos += extra - return pos +) -> tuple[int, int]: + """Return the text index and column offset within or after the glyph.""" + col = pos = 0 + for cluster, width, _ in _display_glyphs( + cells, mode_2027=mode_2027, profile=profile + ): + if col + width > target_col: + break + col += width + pos += len(cluster) + return pos, max(0, target_col - col) def _scrub_cells( cells: list[_CellMeta], compiled: tuple[tuple[re.Pattern[str], str], ...], cursor_idx: int | None, -) -> tuple[list[_CellMeta], int | None, list[tuple[int, int, int]]]: +) -> tuple[list[_CellMeta], int | None]: cur = cursor_idx - edits: list[tuple[int, int, int]] = [] for pat, raw_repl in compiled: repl = sanitize_terminal_text(raw_repl) matches = list(pat.finditer("".join(c.ch for c in cells))) if not matches: continue out: list[_CellMeta] = [] - new_edits: list[tuple[int, int, int]] = [] new_cur = cur pos = 0 for m in matches: @@ -695,211 +713,122 @@ def _scrub_cells( ) f_st = fill.style if fill is not None else DEFAULT_STYLE f_lk = fill.hyperlink if fill is not None else None - for r_i, r_ch in enumerate(repl): - if r_i < pre: - out.append(_CellMeta(r_ch, sl[r_i].style, sl[r_i].hyperlink)) - elif r_i >= new_n - suf: - src = sl[old_n - (new_n - r_i)] - out.append(_CellMeta(r_ch, src.style, src.hyperlink)) - else: - out.append(_CellMeta(r_ch, f_st, f_lk)) + out.extend(sl[:pre]) + out.extend(_CellMeta(ch, f_st, f_lk) for ch in repl[pre : new_n - suf]) + out.extend(sl[old_n - suf :]) rep_end = len(out) - new_edits.append((rep_start, rep_end, new_n - old_n)) if cur is not None: - if pos <= cur <= s: - new_cur = (rep_start - s) + cur - elif s < cur <= e: + if s < cur <= e or s == e == cur: new_cur = rep_end + elif pos <= cur <= s: + new_cur = (rep_start - s) + cur pos = e if cur is not None and cur > pos: new_cur = len(out) + (cur - pos) out.extend(cells[pos:]) - cells, cur, edits = out, new_cur, new_edits - return cells, cur, edits - - -def _absorb_2d_slack( - cells: list[_CellMeta], - edits: list[tuple[int, int, int]], - *, - target_cols: int, - cursor_idx: int | None, - mode_2027: bool, - profile: Profile, -) -> tuple[list[_CellMeta], int | None]: - # Absorb token width deltas into >=2-space unstyled alignment gaps bounded by box - # dividers so 2D CSI H panels never wrap their right border onto the next row. - cur = cursor_idx - delta = _cells_width(cells, mode_2027=mode_2027, profile=profile) - target_cols - if delta == 0 or not edits: - return cells, cur - dividers = frozenset("│┃║╎╏┆┇┊┋") - - def _is_space(i: int) -> bool: - c = cells[i] - return c.ch == " " and c.style == DEFAULT_STYLE and c.hyperlink is None - - def _scan_gap(start: int, step: int) -> tuple[int, int] | None: - i, n = start, len(cells) - while 0 <= i < n and cells[i].ch not in dividers: - if _is_space(i): - j = i - while 0 <= j < n and _is_space(j): - j += step - lo, hi = (i, j) if step > 0 else (j + 1, i + 1) - if hi - lo >= 2: - return (lo, hi) - i = j - else: - i += step - return None - - for rep_start, rep_end, _ in reversed(edits): - if delta == 0: - break - gap = _scan_gap(rep_end, 1) or _scan_gap(rep_start - 1, -1) - if gap is None: - continue - g_lo, g_hi = gap - if delta > 0: - eat = min(delta, (g_hi - g_lo) - 1) - del cells[g_hi - eat : g_hi] - if cur is not None and cur > g_hi - eat: - cur = max(g_hi - eat, cur - eat) - delta -= eat - else: - add = -delta - cells[g_hi:g_hi] = [_CellMeta(" ", DEFAULT_STYLE, None)] * add - if cur is not None and cur >= g_hi: - cur += add - delta = 0 + cells, cur = out, new_cur return cells, cur -def _wrap_or_pad_cells( +def _render_scrubbed_row( cells: list[_CellMeta], *, cols: int, - allow_wrap: bool, cursor_idx: int | None, + cursor_extra: int, mode_2027: bool, profile: Profile, -) -> tuple[list[tuple[str, bool, list[str]]], tuple[int, int] | None]: - clusters: list[tuple[str, int, Style, Hyperlink | None, int, int]] = [] - pos = 0 - for cl in segment_graphemes("".join(c.ch for c in cells)): - cw = display_width(cl, mode_2027=mode_2027, profile=profile) - m = cells[pos] - clusters.append((cl, cw, m.style, m.hyperlink, pos, pos + len(cl))) - pos += len(cl) - - rows_out: list[tuple[str, bool, list[str]]] = [] - cur_rc: tuple[int, int] | None = None - c_idx, n_cl = 0, len(clusters) - while True: - col_used = 0 - txt: list[str] = [] - spans: list[tuple[int, int, Style, Hyperlink | None]] = [] - while c_idx < n_cl: - cl, cw, st, lk, s_p, e_p = clusters[c_idx] - if cw > cols: - if ( - cursor_idx is not None - and cur_rc is None - and s_p <= cursor_idx < e_p - ): - cur_rc = (len(rows_out), col_used) - c_idx += 1 - break - if col_used + cw > cols: - break - if cursor_idx is not None and cur_rc is None and s_p <= cursor_idx < e_p: - cur_rc = (len(rows_out), col_used) - txt.append(cl) - if cw > 0 and (st != DEFAULT_STYLE or lk is not None): - if spans and spans[-1][1] == col_used and spans[-1][2:] == (st, lk): - spans[-1] = (spans[-1][0], col_used + cw, st, lk) - else: - spans.append((col_used, col_used + cw, st, lk)) - col_used += cw - c_idx += 1 - - wrapped = allow_wrap and c_idx < n_cl - if col_used < cols: - txt.append(" " * (cols - col_used)) - span_strs = [ - f"[{sc}..{ec}]: {_format_style_token(st, lk)}" for sc, ec, st, lk in spans - ] - rows_out.append(("".join(txt), wrapped, span_strs)) - if not wrapped: - if cursor_idx is not None and cur_rc is None: - cur_rc = (len(rows_out) - 1, min(cols, col_used)) +) -> tuple[str, list[str], int | None]: + col = pos = 0 + cursor_col: int | None = None + text: list[str] = [] + spans: list[tuple[int, int, Style, Hyperlink | None]] = [] + for cluster, width, cell in _display_glyphs( + cells, mode_2027=mode_2027, profile=profile + ): + if col + width > cols: break - return rows_out, cur_rc + end = col + width + next_pos = pos + len(cluster) + if cursor_idx is not None and pos <= cursor_idx < next_pos: + cursor_col = col + min(cursor_extra, max(0, width - 1)) + if width > 0 and (cell.style != DEFAULT_STYLE or cell.hyperlink is not None): + if spans and spans[-1][1:] == (col, cell.style, cell.hyperlink): + spans[-1] = (spans[-1][0], end, cell.style, cell.hyperlink) + else: + spans.append((col, end, cell.style, cell.hyperlink)) + text.append(cluster) + col, pos = end, next_pos + + if cursor_idx is not None and cursor_col is None: + cursor_col = min(cols - 1, col + cursor_extra) + text.append(" " * (cols - col)) + return ( + "".join(text), + [ + f"[{start}..{end}]: {_format_style_token(style, link)}" + for start, end, style, link in spans + ], + cursor_col, + ) def _render_fixed_rows( - vp_rows: collections.abc.Sequence[RowView], + view: Snapshot | Screen | RegionView, *, - cols_n: int, compiled: tuple[tuple[re.Pattern[str], str], ...], cur_row: int | None, cur_col: int, include_styles: bool, - keep_wrap_mark: bool, mode_2027: bool, profile: Profile, ) -> tuple[str, list[str], int]: - border = "─" * cols_n + border = "─" * view.cols box_lines = [f"┌{border}┐"] style_lines: list[str] = [] out_col = cur_col - for r, rv in enumerate(vp_rows): - cells = _row_to_cells(rv, trim_trailing_unstyled=False) - rem = cols_n - _cells_width(cells, mode_2027=mode_2027, profile=profile) - if rem > 0: - cells.extend([_CellMeta(" ", DEFAULT_STYLE, None)] * rem) - c_in = ( - _display_col_to_char_idx( - cells, - cur_col, - pad_spaces=False, - mode_2027=mode_2027, - profile=profile, + for r in range(view.rows): + row = view[r] + cells = _row_to_cells(row) if compiled else [] + cursor_idx: int | None = None + extra = 0 + if compiled and r == cur_row: + cursor_idx, extra = _cursor_text_offset( + cells, cur_col, mode_2027=mode_2027, profile=profile ) - if cur_row is not None and r == cur_row - else None - ) - if compiled: - cells, c_in, edits = _scrub_cells(cells, compiled, c_in) - cells, c_in = _absorb_2d_slack( - cells, - edits, - target_cols=cols_n, - cursor_idx=c_in, + scrubbed, cursor_idx = _scrub_cells(cells, compiled, cursor_idx) + if scrubbed != cells: + text, spans, mapped = _render_scrubbed_row( + scrubbed, + cols=view.cols, + cursor_idx=cursor_idx, + cursor_extra=extra, mode_2027=mode_2027, profile=profile, ) - packed, mapped = _wrap_or_pad_cells( - cells, - cols=cols_n, - allow_wrap=False, - cursor_idx=c_in, - mode_2027=mode_2027, - profile=profile, - ) - if mapped is not None and cur_row is not None and r == cur_row: - out_col = mapped[1] - txt, _, sp = packed[0] - w_mark = "W" if keep_wrap_mark and rv.wrapped else "" - box_lines.append(f"│{txt}│{w_mark}") + if mapped is not None: + out_col = mapped + else: + text = sanitize_terminal_text(row.display_text) + col_start = row._col_range.start + spans = [ + f"[{run.start_col - col_start}..{run.end_col - col_start}]: " + f"{_format_style_token(run.style, run.hyperlink)}" + for run in row.runs + if include_styles + and (run.style != DEFAULT_STYLE or run.hyperlink is not None) + ] + w_mark = "W" if not isinstance(view, RegionView) and row.wrapped else "" + box_lines.append(f"│{text}│{w_mark}") if include_styles: - style_lines.extend(f" r{r}{s}" for s in sp) + style_lines.extend(f" r{r}{span}" for span in spans) box_lines.append(f"└{border}┘") return "\n".join(box_lines), style_lines, out_col -def _extract_target(data: object) -> tuple[object, set[str]] | None: +def _extract_target( + data: object, +) -> tuple[Snapshot | Screen | RegionView, set[str]] | None: from libvt.contrib.tmux.capture import TmuxCaptureResult if isinstance(data, TmuxCaptureResult): @@ -926,19 +855,14 @@ def _extract_target(data: object) -> tuple[object, set[str]] | None: return None -def _slice_extracted( - extracted: tuple[object, set[str]], - region: tuple[int, int, int, int] | None, -) -> tuple[object, set[str]]: - if region is None: - return extracted - view, unexposed = extracted +def _slice_view( + view: Snapshot | Screen | RegionView, + region: tuple[int, int, int, int], +) -> RegionView: r0, r1, c0, c1 = region - if isinstance(view, (Snapshot, Screen)): - return view[r0:r1, c0:c1], unexposed if isinstance(view, RegionView): - return RegionView(view._rows[r0:r1], view._col_range[c0:c1]), unexposed - return extracted + return RegionView(view._rows[r0:r1], view._col_range[c0:c1]) + return view[r0:r1, c0:c1] def serialize_vt_snapshot( @@ -948,7 +872,12 @@ def serialize_vt_snapshot( include_cursor_shape: bool = False, include_styles: bool = True, ) -> str: - r"""Serialize *target* into a canonical, escape-free boxed VT snapshot string. + r"""Serialize one captured viewport as an escape-free box. + + A terminal supplies its committed frame. Visible row order and soft-wrap + markers come from the captured grid. A standalone + :class:`~libvt.screen.RegionView` uses the default profile and grapheme + mode for replacement glyphs. Parameters ---------- @@ -959,7 +888,10 @@ def serialize_vt_snapshot( or duck-typed pane wrapper exposing ``.terminal``, ``.snapshot()``, or ``.capture_vt()``. scrubbers : Sequence[ScrubberSpec], optional - Regex ``(pattern, replacement)`` pairs applied during serialization. + Regex ``(pattern, replacement)`` pairs applied to each visible row. + Replacements shift the rest of that row and remap its cursor column. + Insertions shift a cursor at the insertion point with its cell. + Text is clipped to the captured width at glyph boundaries. include_cursor_shape : bool, optional When ``True``, include ``shape=`` in the cursor header tuple unless marked unexposed by ``tmux`` capture completeness metadata. @@ -1011,7 +943,8 @@ def serialize_vt_snapshot( ) raise TypeError(msg) cur_str = _serialize_extracted( - _slice_extracted(cur_ext, target.region), + cur_ext, + region=target.region, scrubbers=merged_scrubbers, include_cursor_shape=eff_shape, include_styles=eff_styles, @@ -1025,7 +958,8 @@ def serialize_vt_snapshot( ) raise TypeError(msg) base_str = _serialize_extracted( - _slice_extracted(base_ext, target.region), + base_ext, + region=target.region, scrubbers=merged_scrubbers, include_cursor_shape=eff_shape, include_styles=eff_styles, @@ -1058,179 +992,60 @@ def serialize_vt_snapshot( def _serialize_extracted( - extracted: tuple[object, set[str]], + extracted: tuple[Snapshot | Screen | RegionView, set[str]], *, + region: tuple[int, int, int, int] | None = None, scrubbers: collections.abc.Sequence[ScrubberSpec] = (), include_cursor_shape: bool = False, include_styles: bool = True, ) -> str: - view, unexposed = extracted + source, unexposed = extracted compiled = _compile_scrubbers(scrubbers) + profile = DEFAULT_PROFILE if isinstance(source, RegionView) else source._profile + mode_2027 = ( + not isinstance(source, Snapshot) or Mode.GRAPHEME_CLUSTERING in source.modes + ) + view = source if region is None else _slice_view(source, region) if isinstance(view, RegionView): box, style_lines, _ = _render_fixed_rows( - [view[r] for r in range(view.rows)], - cols_n=view.cols, + view, compiled=compiled, cur_row=None, cur_col=0, include_styles=include_styles, - keep_wrap_mark=False, - mode_2027=True, - profile=DEFAULT_PROFILE, + mode_2027=mode_2027, + profile=profile, ) out = f"size={view.cols}x{view.rows} region=True\n{box}" return f"{out}\nstyles:\n" + "\n".join(style_lines) if style_lines else out if isinstance(view, Screen): - rows_n, cols_n, alt = view.rows, view.cols, view._is_alt - cur_row, cur_col = view.cursor.row, view.cursor.col - cur_vis, cur_shape = view.cursor.visible, view.cursor.shape + alt = view._is_alt modes_set: frozenset[Mode] = frozenset({Mode.DECAWM, Mode.GRAPHEME_CLUSTERING}) - profile = DEFAULT_PROFILE else: - assert isinstance(view, Snapshot) - rows_n, cols_n, alt = view.rows, view.cols, view.active_is_alt - cur_row, cur_col = view.cursor.row, view.cursor.col - cur_vis, cur_shape = view.cursor.visible, view.cursor.shape + alt = view.active_is_alt modes_set = view.modes - profile = view._profile - - vp_rows = [view[r] for r in range(rows_n)] - hist_rows = list(view.history) if not alt else [] - mode_2027 = Mode.GRAPHEME_CLUSTERING in modes_set - autowrap = Mode.DECAWM in modes_set - - if not compiled and isinstance(view, Snapshot): - box = format_screen_box(view) - style_lines = [ - f" r{r}[{run.start_col}..{run.end_col}]: " - f"{_format_style_token(run.style, run.hyperlink)}" - for r in range(rows_n) - for run in vp_rows[r].runs - if include_styles - and (run.style != DEFAULT_STYLE or run.hyperlink is not None) - ] - elif not compiled or alt or not autowrap: - box, style_lines, cur_col = _render_fixed_rows( - vp_rows, - cols_n=cols_n, - compiled=compiled, - cur_row=cur_row, - cur_col=cur_col, - include_styles=include_styles, - keep_wrap_mark=True, - mode_2027=mode_2027, - profile=profile, - ) - else: - # Coalesce only contiguous soft-wrapped chains so OS path-length wraps match - # without resurrecting scrollback rows cleared by ED 2 (Ctrl-L). - prefix_hist: list[RowView] = [] - h_idx = len(hist_rows) - 1 - while h_idx >= 0 and hist_rows[h_idx].wrapped: - prefix_hist.append(hist_rows[h_idx]) - h_idx -= 1 - prefix_hist.reverse() - combined = prefix_hist + vp_rows - cur_combined_row = len(prefix_hist) + cur_row - last_active = max( - cur_combined_row, - max( - ( - i - for i, rv in enumerate(combined) - if rv.text - or rv.wrapped - or any( - r.style != DEFAULT_STYLE or r.hyperlink is not None - for r in rv.runs - ) - ), - default=0, - ), - ) - active_rows = combined[: last_active + 1] - repacked: list[tuple[str, bool, list[str]]] = [] - idx = 0 - while idx < len(active_rows): - c_start = idx - while idx < len(active_rows) - 1 and active_rows[idx].wrapped: - idx += 1 - c_end = idx - idx += 1 - logical: list[_CellMeta] = [] - cur_idx: int | None = None - for r_i in range(c_start, c_end + 1): - seg = _row_to_cells( - active_rows[r_i], - trim_trailing_unstyled=not active_rows[r_i].wrapped - and r_i == c_end, - ) - if r_i == cur_combined_row: - rel_idx = _display_col_to_char_idx( - seg, - cur_col, - pad_spaces=True, - mode_2027=mode_2027, - profile=profile, - ) - cur_idx = len(logical) + rel_idx - logical.extend(seg) - if compiled: - pre_w = _cells_width( - logical, - mode_2027=mode_2027, - profile=profile, - ) - logical, cur_idx, edits = _scrub_cells(logical, compiled, cur_idx) - if c_end == c_start: - logical, cur_idx = _absorb_2d_slack( - logical, - edits, - target_cols=pre_w, - cursor_idx=cur_idx, - mode_2027=mode_2027, - profile=profile, - ) - packed, mapped = _wrap_or_pad_cells( - logical, - cols=cols_n, - allow_wrap=True, - cursor_idx=cur_idx, - mode_2027=mode_2027, - profile=profile, - ) - if mapped is not None: - cur_row, cur_col = len(repacked) + mapped[0], mapped[1] - repacked.extend(packed) - - if len(repacked) > rows_n: - drop = len(repacked) - rows_n - repacked = repacked[drop:] - cur_row = max(0, cur_row - drop) - while len(repacked) < rows_n: - repacked.append((" " * cols_n, False, [])) - - border = "─" * cols_n - box_parts = [f"┌{border}┐"] - style_lines = [] - for r, (txt, w_flag, sp) in enumerate(repacked): - box_parts.append(f"│{txt}│{'W' if w_flag else ''}") - if include_styles: - style_lines.extend(f" r{r}{s}" for s in sp) - box_parts.append(f"└{border}┘") - box = "\n".join(box_parts) + cursor = view.cursor + box, style_lines, cur_col = _render_fixed_rows( + view, + compiled=compiled, + cur_row=cursor.row, + cur_col=cursor.col, + include_styles=include_styles, + mode_2027=mode_2027, + profile=profile, + ) shape_part = ( - f",shape={cur_shape.name}" + f",shape={cursor.shape.name}" if include_cursor_shape and "cursor_shape" not in unexposed else "" ) modes_str = ",".join(_canonical_modes(modes_set)) header = ( - f"size={cols_n}x{rows_n} " - f"cursor=({cur_row},{cur_col},vis={cur_vis}{shape_part}) " + f"size={view.cols}x{view.rows} " + f"cursor=({cursor.row},{cur_col},vis={cursor.visible}{shape_part}) " f"alt={alt} modes=[{modes_str}]" ) out = f"{header}\n{box}" diff --git a/tests/test_screen.py b/tests/test_screen.py index d37bf5e..3882745 100644 --- a/tests/test_screen.py +++ b/tests/test_screen.py @@ -17,7 +17,7 @@ from libvt.config import DEFAULT_PROFILE, Profile, ScreenBehavior, UnicodeBehavior from libvt.events import InBandResize from libvt.modes import Mode -from libvt.profiles import XTERM_PROFILE +from libvt.profiles import GHOSTTY_PROFILE, XTERM_PROFILE from libvt.screen import Cursor, Screen from libvt.style import ( AnsiColor, @@ -27,6 +27,8 @@ Style, UnderlineStyle, ) +from libvt.terminal import ResyncReason +from libvt.testing import serialize_vt_snapshot def _assert_grid_invariants(term: libvt.Terminal) -> None: @@ -176,6 +178,248 @@ def test_resize_pending_wrap_and_reflow_cases(case: ResizeCase) -> None: ) == case.expected_cursor +@pytest.mark.parametrize("bytewise", [False, True], ids=["whole", "bytewise"]) +@pytest.mark.parametrize( + ("erase", "expected"), + [ + pytest.param(b"\x1b[H\x1b[J", ("", ""), id="ed0-home"), + pytest.param(b"\x1b[H\x1b[1J", (" jklmnop", "qr"), id="ed1-prefix"), + pytest.param(b"\x1b[1J", ("", ""), id="ed1-lower"), + pytest.param(b"\x1b[2J", ("", ""), id="ed2"), + pytest.param(b"\x1b[H\x1b[K", ("", "qr"), id="el0-home"), + pytest.param(b"\x1b[1;8H\x1b[1K", ("", "qr"), id="el1-full"), + pytest.param(b"\x1b[H\x1b[2K", ("", "qr"), id="el2"), + ], +) +def test_erase_severs_history_wrap( + erase: bytes, expected: tuple[str, str], *, bytewise: bool +) -> None: + """Erasing the incoming continuation seals the preceding scrollback row.""" + term = libvt.Terminal(rows=2, cols=8) + term.feed(b"abcdefghijklmnopqr") + old_history = term.screen.history + assert [(row.text, row.wrapped) for row in old_history] == [("abcdefgh", True)] + + if bytewise: + for byte in erase[:-1]: + term.feed(bytes((byte,))) + assert term.screen.history[-1].wrapped + term.feed(erase[-1:]) + else: + term.feed(erase) + + assert term.lines == expected + assert [(row.text, row.wrapped) for row in term.screen.history] == [ + ("abcdefgh", False) + ] + assert old_history[-1].wrapped + if erase == b"\x1b[2J": + term.feed(b"\x1b[HFresh") + assert serialize_vt_snapshot(term, scrubbers=[(r"Fresh", "OK")]) == ( + "size=8x2 cursor=(0,2,vis=True) alt=False modes=[]\n" + "┌────────┐\n│OK │\n│ │\n└────────┘" + ) + term.resize(rows=2, cols=16, reflow=True) + assert term.lines == ("Fresh", "") + assert (term.cursor.row, term.cursor.col) == (0, 5) + + +@pytest.mark.parametrize( + "erase", + [ + b"\x1b[1;2H\x1b[J", + b"\x1b[J", + b"\x1b[1;2H\x1b[K", + b"\x1b[1;2H\x1b[1K", + b"\x1b[2K", + b"\x1b[H\x1b[X", + b"\x1b[?1049h\x1b[2J\x1b[?1049l", + ], + ids=[ + "ed0-right", + "ed0-lower", + "el0-right", + "el1-prefix", + "el2-lower", + "ech", + "alt", + ], +) +def test_erase_elsewhere_preserves_history_wrap(erase: bytes) -> None: + """An erase outside the incoming boundary leaves scrollback intact.""" + term = libvt.Terminal(rows=2, cols=8) + term.feed(b"abcdefghijklmnopqr") + history = term.snapshot()._history + term.feed(erase) + assert term.snapshot()._history is history + assert term.screen.history[-1].wrapped + + +def test_erase_wrap_honors_host_and_scroll_clear() -> None: + """Ghostty retains the link, and scroll clear moves the linked rows together.""" + ghostty = libvt.Terminal(rows=2, cols=8, profile=GHOSTTY_PROFILE) + ghostty.feed(b"abcdefghijklmnopqr\x1b[2J\x1b[HFresh") + assert ghostty.screen.history[-1].wrapped + ghostty.resize(rows=2, cols=16) + assert ghostty.lines == ("abcdefghFresh", "") + assert (ghostty.cursor.row, ghostty.cursor.col) == (0, 13) + + alignment = libvt.Terminal(rows=2, cols=8, profile=GHOSTTY_PROFILE) + alignment.feed(b"abcdefghijklmnopqr\x1b#8") + assert alignment.history[-1].wrapped + alignment.resize(rows=2, cols=16) + assert alignment.lines == ("abcdefghEEEEEEEE", "EEEEEEEE") + assert (alignment.cursor.row, alignment.cursor.col) == (0, 8) + + profile = Profile(screen=ScreenBehavior(ed2_scrolls_primary_to_history=True)) + scroll = libvt.Terminal(rows=2, cols=8, profile=profile) + scroll.feed(b"abcdefghijklmnopqr\x1b[2J\x1b[HFresh") + assert [(row.text, row.wrapped) for row in scroll.screen.history] == [ + ("abcdefgh", True), + ("ijklmnop", True), + ("qr", False), + ] + assert scroll.lines == ("Fresh", "") + + +def test_erase_history_wrap_one_column_respects_phantom_cursor() -> None: + """A phantom-column EL0 preserves the link until a physical erase.""" + profile = Profile(screen=ScreenBehavior(pending_wrap_phantom_col=True)) + term = libvt.Terminal(rows=2, cols=1, profile=profile) + term.feed(b"ABC\x1b[HB\x1b[K") + assert term.cursor.pending_wrap + assert term.lines == ("B", "C") + assert term.screen.history[-1].wrapped + + term.feed(b"\x1b[H\x1b[KX") + assert not term.screen.history[-1].wrapped + term.resize(rows=2, cols=4) + assert term.lines == ("X", "C") + + +@pytest.mark.parametrize( + ("erase", "cols"), + [(b"\x1b[2J", 8), (b"\x1b[1;2H\x1b[K", 10)], + ids=["whole-display", "wide-tail-after-crop-resize"], +) +def test_erase_history_wrap_seals_wide_padding_and_keeps_bce( + erase: bytes, cols: int +) -> None: + """A row relieved of its wrap keeps the background of its retired padding.""" + term = libvt.Terminal(rows=2, cols=8) + term.feed_str("\x1b[44mabcdefg界ijklmnopq") + old_history = term.screen.history + assert old_history[-1][7].width_role is WidthRole.SPACER_HEAD + assert old_history[-1][7].style.bg is AnsiColor.BLUE + assert term[0][0].text == "界" + assert term[0][1].width_role is WidthRole.SPACER_TAIL + term.resize(rows=2, cols=cols, reflow=False) + term.feed(b"\x1b[41m" + erase) + assert not term.screen.history[-1].wrapped + assert term.screen.history[-1].text == "abcdefg" + assert term.screen.history[-1][7].width_role is WidthRole.NARROW + assert term.screen.history[-1][7].style.bg is AnsiColor.BLUE + assert term[0].text == ("" if cols == 8 else " ") + assert term[0][1].style.bg is AnsiColor.RED + assert term.screen._rows[0].used == cols + assert term.screen._rows[0].text_used == (0 if cols == 8 else 1) + assert old_history[-1].wrapped + assert old_history[-1][7].width_role is WidthRole.SPACER_HEAD + + +def test_selective_erase_keeps_history_wrap_into_protected_wide_cell() -> None: + """A protected grapheme at the continuation's origin keeps its padding.""" + term = libvt.Terminal(rows=2, cols=8) + term.feed_str('abcdefg\x1b[1"q界\x1b[0"qijklmnopq') + history = term.snapshot()._history + term.feed(b"\x1b[1;2H\x1b[?K\x1b[?2J") + assert term.snapshot()._history is history + assert term[0][0].text == "界" + assert term[0][0].protected + assert term.screen.history[-1][7].width_role is WidthRole.SPACER_HEAD + + +@pytest.mark.parametrize( + "erase", + [b"\x1b[2;2H\x1b[?K", b"\x1b[1;8H\x1b[?K"], + ids=["target-wide-tail", "preceding-padding"], +) +def test_selective_erase_keeps_protected_wide_cell_across_visible_rows( + erase: bytes, +) -> None: + """Selective erase must honor protection when healing across a row boundary.""" + term = libvt.Terminal(rows=3, cols=8) + term.feed_str('abcdefg\x1b[1"q界\x1b[0"qxyz') + assert term.screen[0][7].width_role is WidthRole.SPACER_HEAD + term.feed(erase) + assert term.screen[1][0].text == "界" + assert term.screen[1][0].protected + assert term.screen[1][1].width_role is WidthRole.SPACER_TAIL + + +@pytest.mark.parametrize("hard_lines", [511, 512], ids=["sealed-block", "tail"]) +def test_erase_history_wrap_cow_and_held_frame(hard_lines: int) -> None: + """Publish the changed history row with the held frame and reuse older blocks.""" + term = libvt.Terminal(rows=2, cols=8, scrollback=300) + term.feed(b"q\r\n" * hard_lines + b"abcdefghijklmnopqr") + old = term.committed + old_token = term.sync_token() + working_token = term.sync_token(view="working") + assert len(old.history) == 300 + assert old.history[-1].wrapped + + term.feed(b"\x1b[?2026h\x1b[2J") + assert term.committed.history[-1].wrapped + assert not term.changes_since(old_token).has_changes + working = term.changes_since(working_token, view="working") + assert working.resync_reason is ResyncReason.EPOCH_CHANGED + assert not working.new_history[-1].wrapped + + term.feed(b"\x1b[?2026l") + delta = term.changes_since(old_token) + assert delta.resync_reason is ResyncReason.EPOCH_CHANGED + assert delta.snapshot.lines == ("", "") + assert not delta.history_cleared + assert delta.history_evicted == delta.viewport_scroll_up == 0 + assert len(delta.new_history) == 300 + assert (delta.new_history[-1].text, delta.new_history[-1].wrapped) == ( + "abcdefgh", + False, + ) + before = old._history + after = delta.snapshot._history + assert after.head_offset == before.head_offset + assert after.blocks[0] is before.blocks[0] + assert (after.blocks[-1] is before.blocks[-1]) is bool(before.tail) + assert old.history[-1].wrapped + term.feed(b"\x1b[2J") + assert not term.changes_since(delta.token).full_resync + + +def test_reflow_keeps_blank_viewport_padding_after_a_hard_history_line() -> None: + """A width change preserves existing bottom padding after a hard line break.""" + term = libvt.Terminal(rows=2, cols=8) + term.feed(b"abcdefgh\r\nFresh\r\n\x1b[1;6H") + assert term.lines == ("Fresh", "") + assert not term.history[-1].wrapped + + term.resize(rows=2, cols=16) + assert term.lines == ("Fresh", "") + assert (term.cursor.row, term.cursor.col) == (0, 5) + assert term.history[-1].text == "abcdefgh" + + +def test_reflow_joins_an_untouched_history_continuation() -> None: + """Reflow still joins the viewport and history across a live soft wrap.""" + term = libvt.Terminal(rows=2, cols=8) + term.feed(b"abcdefghijklmnopqr") + assert term.history[-1].wrapped + term.resize(rows=2, cols=16) + assert term.lines == ("abcdefghijklmnop", "qr") + assert (term.cursor.row, term.cursor.col) == (1, 2) + assert not term.history + + def test_resize_soft_wrap_join_alt_crop_and_inband_2048() -> None: """Primary soft wraps join on widen, alt crops, and ``?2048`` emits reply.""" term = libvt.Terminal(rows=4, cols=10, scrollback=20, record_events=True) @@ -715,3 +959,79 @@ def test_screen_put_text_sixel_cluster_and_negative_col_invariants() -> None: assert prot_term.screen[0][0].protected is True assert prot_term.screen[0][2].protected is True assert prot_term.screen[0][1].protected is False + + +def test_sever_dangling_wrap_on_erase_display_erase_line_decaln_and_edit() -> None: + """Full-row non-selective erases and row-0 wide edits sever dangling wraps.""" + # ED 2 under DEFAULT_PROFILE clears in place and severs history[-1].wrapped + # without mutating earlier CoW snapshots (both _tail and 256-row _blocks). + for pad_rows in (0, 255): + term = libvt.Terminal(rows=2, cols=16, scrollback=512) + for idx in range(pad_rows): + term.feed(f"hist-{idx:03d}\r\n".encode()) + term.feed(b"0123456789abcdefTAIL\r\nROW1") + pre_snap = term.snapshot() + assert pre_snap.history[-1].text == "0123456789abcdef" + assert pre_snap.history[-1].wrapped is True + + rep_h = list(pre_snap.history) + rep_v = [pre_snap[i] for i in range(pre_snap.rows)] + tok = term.sync_token(view="working") + + term.feed(b"\x1b[2J\x1b[HFresh\r\nDone") + post_snap = term.snapshot() + assert pre_snap.history[-1].wrapped is True + assert post_snap.history[-1].wrapped is False + + delta = term.changes_since(tok, view="working") + delta.apply_rows(rep_h, rep_v) + assert rep_h == list(post_snap.history) + assert rep_v == [post_snap[i] for i in range(post_snap.rows)] + + term.resize(rows=2, cols=32, reflow=True) + assert term.history[-1].text == "0123456789abcdef" + assert term.lines == ("Fresh", "Done") + _assert_grid_invariants(term) + + # ED 0 at (0, 0), ED 1 through cols-1, EL 2, EL 0 at col 0, EL 1 at cols-1, DECALN. + for erase_seq, expected_row0 in ( + (b"\x1b[H\x1b[JFresh", "Fresh"), + (b"\x1b[1;16H\x1b[1J\x1b[HFresh", "Fresh"), + (b"\x1b[2;1H\x1b[1J\x1b[HFresh", "Fresh"), + (b"\x1b[H\x1b[2KFresh", "Fresh"), + (b"\x1b[H\x1b[KFresh", "Fresh"), + (b"\x1b[1;16H\x1b[1K\x1b[HFresh", "Fresh"), + (b"\x1b#8", "E" * 16), + ): + t_case = libvt.Terminal(rows=3, cols=16) + t_case.feed(b"0123456789abcdefMID_0123456789abTAIL\r\nBOT") + assert t_case.history[-1].wrapped is True + assert t_case.screen[0].wrapped is True + t_case.feed(erase_seq) + assert t_case.history[-1].wrapped is False + assert t_case.screen[0].wrapped is False + assert t_case.lines[0] == expected_row0 + t_case.resize(rows=3, cols=32, reflow=True) + all_lines = (*(r.text for r in t_case.history), *t_case.lines) + assert "0123456789abcdef" in all_lines + assert expected_row0 in all_lines + assert f"0123456789abcdef{expected_row0}" not in all_lines + + # Wide SPACER_HEAD in history[-1] straddling onto row 0 heals on overwrite and ED 2. + for action, expected_r0 in ( + (b"\x1b[HX", "X "), + (b"\x1b[1;2HX", " X"), + (b"\x1b[2J\x1b[HFresh", "Fresh"), + ): + t_wide = libvt.Terminal(rows=2, cols=5) + t_wide.feed("ABCD日\r\nok".encode()) + pre_wide = t_wide.snapshot() + assert pre_wide.history[-1].wrapped is True + assert pre_wide.history[-1][4].width_role == WidthRole.SPACER_HEAD + t_wide.feed(action) + post_wide = t_wide.snapshot() + assert pre_wide.history[-1][4].width_role == WidthRole.SPACER_HEAD + assert post_wide.history[-1].wrapped is False + assert post_wide.history[-1][4].width_role == WidthRole.NARROW + assert t_wide.lines[0] == expected_r0.rstrip(" ") + _assert_grid_invariants(t_wide) diff --git a/tests/test_testing.py b/tests/test_testing.py index fa5c19a..f01a612 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -4,6 +4,7 @@ import os import pathlib +import re import shutil import subprocess import sys @@ -19,7 +20,7 @@ from libvt.contrib.tmux.profile import tmux_profile from libvt.parser import Parser from libvt.pytest_plugin import TerminalFactory -from libvt.terminal import FlightRecorder, Terminal +from libvt.terminal import FlightRecorder, Terminal, strip from libvt.testing import ( assert_screen, assert_screen_box, @@ -172,77 +173,521 @@ def test_cross_engine_and_tmux_33a_to_38_parity() -> None: ) -def test_cli_stream_scrollback_wrap_without_ctrl_l_history_bleed() -> None: - """Recover 2-row macOS soft-wrap spill without resurrecting ``Ctrl-L`` history.""" - scrubs = [ - (r"pid=\d+", "pid="), - (r"/(?:private/var/folders|tmp)/\S+", ""), - ] - t_linux = Terminal(rows=2, cols=28) - t_linux.feed(b"pid=\x1b[33m912\x1b[0m /tmp/run-1\r\nready") - t_macos = Terminal(rows=2, cols=28) - t_macos.feed(b"pid=\x1b[33m104829\x1b[0m /private/var/folders/run-1\r\nready") - out_linux = serialize_vt_snapshot(t_linux, scrubbers=scrubs) - out_macos = serialize_vt_snapshot(t_macos, scrubbers=scrubs) - assert out_linux == out_macos - assert "r0[4..9]: fg=yellow" in out_linux - - t_macos_red = Terminal(rows=2, cols=28) - t_macos_red.feed(b"pid=\x1b[31m104829\x1b[0m /private/var/folders/run-1\r\nready") - assert serialize_vt_snapshot(t_macos_red, scrubbers=scrubs) != out_linux - - t_clear = Terminal(rows=4, cols=20) - for i in range(5): - t_clear.feed(f"old-history-{i}\r\n".encode()) - t_clear.feed(b"\x1b[2J\x1b[Hpid=912\r\nready") - cleared_snap = serialize_vt_snapshot(t_clear, scrubbers=scrubs) - assert "old-history" not in cleared_snap - assert "cursor=(1,5,vis=True)" in cleared_snap - - -def test_2d_alt_screen_tui_slack_absorption_preserves_borders() -> None: - """2D ``CSI H`` TUIs absorb token width delta without wrapping borders.""" - t_clock = Terminal(rows=3, cols=33) - t_clock.feed( - b"\x1b[?1049h\x1b[H" - + "┌───────────────────────────────┐\r\n".encode() - + "│Title Clock 12:34│\r\n".encode() - + "└───────────────────────────────┘".encode() - ) - s_clock = serialize_vt_snapshot(t_clock, scrubbers=[(r"\d{2}:\d{2}", "