Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,15 @@ A live or paused {class}`~libvt.contrib.tmux.control.TmuxPaneSync` enters
outside the client's session, the sync enters `OUT_OF_SCOPE` and keeps
its last screen.

#### 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`.

### Documentation

#### Assert effective colors alongside screen goldens (#190)
Expand Down Expand Up @@ -320,6 +329,24 @@ reply marker and command batch on two lines. Send the complete string with
a final newline. On a shared control client, a command failure puts only
the requesting pane sync in `FAILED`.

#### 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=<PID>")]

# After
scrubbers = [(r"pid=\d+ +", "pid=<PID> ")]
```

See {ref}`topics-testing` for runnable examples.

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

`libvt` 0.0.1a5 adds rectangular grid blitting, display-column text writes, and
Expand Down
9 changes: 9 additions & 0 deletions MIGRATION
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,15 @@ attachment. `terminal` holds the last screen when the pane moves away and
is `None` when the pane was never attached. Send `resync()` through a control
client attached to a session that contains the pane.

### 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)
Expand Down
10 changes: 6 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,10 +93,12 @@ inline without extra dependencies or snapshot files:
### Serialize and scrub multi-row TUIs (`libvt.testing`)

When a TUI, progress panel, or `tmux` layout spans many styled rows or dynamic
IDs, [`vt_screen()`][vt_screen] and [`serialize_vt_snapshot()`][serialize_vt_snapshot]
in `libvt.testing` emit escape-free boxes with run-length `styles:` spans while
absorbing regex scrubber width changes inside `│` borders with no extra
dependencies (`unittest`, `assert`, `inline-snapshot`, or `pytest-regressions`):
IDs, [`vt_screen()`][vt_screen] and
[`serialize_vt_snapshot()`][serialize_vt_snapshot] in `libvt.testing` emit
escape-free boxes with run-length `styles:` spans and regex scrubbing with no
extra dependencies (`unittest`, `assert`, `inline-snapshot`, or
`pytest-regressions`). Scrubbers match within one visible row at a time; the
serializer pads or clips each row to the captured viewport width:

```python
>>> import libvt
Expand Down
2 changes: 1 addition & 1 deletion docs/api/contrib_syrupy.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <libvt.contrib.syrupy.VtSnapshotExtension.configure>`.

## Fixture
Expand Down
2 changes: 1 addition & 1 deletion docs/api/testing.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/quickstart.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
116 changes: 84 additions & 32 deletions docs/topics/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,43 +121,96 @@ True
For a default-color change, assert `frame.appearance.fg_rgb` or
`frame.appearance.bg_rgb` directly.

### 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=<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=<PID> ")])
>>> print(serialize_vt_snapshot(view))
size=16x2 cursor=(1,15,vis=True) alt=True modes=[]
┌────────────────┐
│┌──────────────┐│
││ pid=<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, "<TMP>")]))
>>> tuple(row.strip("│ ") for row in boxed.splitlines()[2:4])
('Log: <TMP>', 'Done')
>>> path_pattern.sub("<TMP>", strip(output)).splitlines()
['Log: <TMP>', '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
Expand Down Expand Up @@ -419,10 +472,9 @@ Projects that disable plugin autoload can select all three modules in
>>> pytest_plugins = ["syrupy", "libvt.pytest_plugin", "libvt.contrib.syrupy"]
```

### 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 <libvt.contrib.syrupy.VtSnapshotExtension.configure>`
and bind it with `snapshot.use_extension(...)` inside a `conftest.py` fixture:

Expand Down
23 changes: 23 additions & 0 deletions src/libvt/_grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import array
import bisect
import collections.abc
import dataclasses
import operator
import typing as t
from dataclasses import dataclass
Expand Down Expand Up @@ -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:
Expand Down
5 changes: 5 additions & 0 deletions src/libvt/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,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``.
Expand Down Expand Up @@ -266,6 +270,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
Expand Down
2 changes: 2 additions & 0 deletions src/libvt/profiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@
),
screen=ScreenBehavior(
cbt_preserves_pending_wrap=True,
# libghostty-vt retains the scrollback row's wrap after ED/EL and DECALN.
erase_severs_history_wrap=False,
rep_uses_last_graphic=True,
),
input=InputBehavior(
Expand Down
Loading
Loading