Skip to content

Commit 0864aa2

Browse files
committed
docs(snapshots): Add tested visual grid examples
why: Show concrete boxed screen grids and SGR spans in the snapshots guide, quickstart, and API reference docstrings. what: - Add visual format_screen_box and serialize_vt_snapshot doctests to docs/topics/snapshots.md and README.md - Document Snapshot, Terminal.snapshot, Terminal.committed, screen views, testing helpers, and tmux capture results with tested examples
1 parent 09611e5 commit 0864aa2

7 files changed

Lines changed: 754 additions & 102 deletions

File tree

‎README.md‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -45,21 +45,26 @@ breaking API changes; pin `libvt>=0.0.1a4,<0.1` while the package is pre-1.0.
4545

4646
Each call to [`feed()`][feed] updates the screen. Read live text and cursor
4747
coordinates directly, or capture an immutable [`Snapshot`][committed] that holds
48-
the last completed frame during `?2026` synchronized redraws and pages backward
49-
through scrollback with [`viewport()`][viewport]:
48+
the last completed frame during synchronized redraws (`?2026`) and pages
49+
backward through scrollback with [`viewport()`][viewport]:
5050

5151
```python
5252
>>> import libvt
53+
>>> from libvt.testing import serialize_vt_snapshot
5354
>>> term = libvt.Terminal(rows=2, cols=20)
5455
>>> term.feed(b"booting\r\nLoading 10%")
55-
>>> term.feed(b"\r\x1b[2KLoading 20%\r\ndone")
56+
>>> term.feed(b"\r\x1b[2K\x1b[1;32mLoading 20%\x1b[0m\r\ndone")
5657
>>> snap = term.committed
57-
>>> snap.lines
58-
('Loading 20%', 'done')
58+
>>> print(serialize_vt_snapshot(snap))
59+
size=20x2 cursor=(1,4,vis=True) alt=False modes=[]
60+
┌────────────────────┐
61+
│Loading 20% │
62+
│done │
63+
└────────────────────┘
64+
styles:
65+
r0[0..11]: bold fg=green
5966
>>> snap.viewport(offset=1).lines
6067
('booting', 'Loading 20%')
61-
>>> snap.cursor.row, snap.cursor.col
62-
(1, 4)
6368
```
6469

6570
### Assert screen boxes inline

‎docs/api/terminal.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
.. automodule:: libvt.terminal
55
:members:
66
:no-private-members:
7-
:exclude-members: _state, SyncView
7+
:exclude-members: _state, SyncView, __new__
88
99
.. py:type:: SyncView
1010
:module: libvt.terminal

‎docs/topics/snapshots.md‎

Lines changed: 143 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -2,42 +2,106 @@
22

33
# Snapshots
44

5-
{class}`libvt.Snapshot <libvt.terminal.Snapshot>` is a core runtime value type
6-
in {mod}`libvt`. Because
7-
{class}`~libvt.terminal.Terminal` mutates its rows in place on every
8-
{meth}`~libvt.terminal.Terminal.feed` call, a `Snapshot` freezes the active
9-
viewport, scrollback history, cursor state, terminal modes, semantic prompt
10-
zones, program status, and graphics placements into an immutable object safe to
11-
pass across threads, cache in UI state, or return from multiplexer adapters
12-
such as {func}`~libvt.contrib.tmux.capture.decode_tmux_capture`.
5+
{class}`libvt.Snapshot <libvt.terminal.Snapshot>` freezes a terminal's active
6+
viewport, scrollback history, cursor state, active DEC/ANSI modes, semantic
7+
prompt zones, program status, and graphics placements at one point in time.
8+
Because {class}`~libvt.terminal.Terminal` mutates its rows in place on every
9+
{meth}`~libvt.terminal.Terminal.feed` call, a `Snapshot` gives callers an
10+
immutable 2D screen value safe to pass across threads, store in UI state, diff
11+
across test steps, or return from multiplexer adapters such as
12+
{func}`~libvt.contrib.tmux.capture.decode_tmux_capture`.
13+
14+
## What a `Snapshot` looks like
15+
16+
Render any `Snapshot` visually as a column-aligned `┌──┐` box with
17+
{func}`~libvt.testing.format_screen_box` (marking soft-wrapped rows with a
18+
trailing `W`), or include its cursor, mode header, and run-length `SGR` style
19+
spans with {func}`~libvt.testing.serialize_vt_snapshot`:
20+
21+
```python
22+
>>> import libvt
23+
>>> from libvt.testing import format_screen_box, serialize_vt_snapshot
24+
>>> term = libvt.Terminal(rows=3, cols=16)
25+
>>> term.feed(
26+
... b"\x1b[1;32mPASS\x1b[0m suite=core_parser\r\n"
27+
... b"\x1b[7m> rerun\x1b[0m"
28+
... )
29+
>>> snap = term.committed
30+
>>> print(format_screen_box(snap))
31+
┌────────────────┐
32+
│PASS suite=core_│W
33+
│parser │
34+
│> rerun │
35+
└────────────────┘
36+
>>> print(serialize_vt_snapshot(snap))
37+
size=16x3 cursor=(2,7,vis=True) alt=False modes=[]
38+
┌────────────────┐
39+
│PASS suite=core_│W
40+
│parser │
41+
│> rerun │
42+
└────────────────┘
43+
styles:
44+
r0[0..4]: bold fg=green
45+
r2[0..7]: reverse
46+
```
47+
48+
Once captured, `snap` never mutates when later bytes arrive on `term`:
49+
50+
```python
51+
>>> import libvt
52+
>>> from libvt.testing import format_screen_box
53+
>>> term = libvt.Terminal(rows=2, cols=12)
54+
>>> term.feed(b"step 1\r\nready")
55+
>>> snap = term.committed
56+
>>> term.feed(b"\x1b[2J\x1b[Hstep 2")
57+
>>> print(format_screen_box(snap))
58+
┌────────────┐
59+
│step 1 │
60+
│ready │
61+
└────────────┘
62+
>>> print(format_screen_box(term.committed))
63+
┌────────────┐
64+
│step 2 │
65+
│ │
66+
└────────────┘
67+
```
1368

1469
## `term.committed` vs `term.snapshot()`
1570

16-
Choose between two capture points depending on whether the caller wants
17-
completed frames or raw in-flight state:
71+
Choose between two capture points depending on whether you want completed
72+
frames or raw in-flight buffer state:
1873

1974
- {attr}`term.committed <libvt.terminal.Terminal.committed>` returns the last
20-
completed frame, holding steady while DEC mode `?2026` synchronized output is
21-
open (`CSI ? 2026 h` … `CSI ? 2026 l`) so UI renderers, observers, and
22-
automation loops never read half-erased screens.
75+
completed frame, holding steady while synchronized output (`?2026`) is open
76+
(`CSI ? 2026 h` … `CSI ? 2026 l`) so UI renderers, observers, and test
77+
predicates never read half-erased screens.
2378
- {meth}`term.snapshot() <libvt.terminal.Terminal.snapshot>` captures the live
24-
buffer immediately, even inside an open `?2026` block.
25-
26-
Once captured, neither `Snapshot` changes when later bytes arrive on the
27-
`Terminal`:
79+
working buffer immediately, even inside an open `?2026` block (reusing the
80+
cached `Snapshot` in `O(1)` when no cells or metadata changed since the last
81+
call).
2882

2983
```python
3084
>>> import libvt
85+
>>> from libvt.testing import format_screen_box
3186
>>> term = libvt.Terminal(rows=2, cols=16)
32-
>>> term.feed(b"frame 1")
87+
>>> term.feed(b"frame 1\r\nstatus: ok")
3388
>>> term.feed(b"\x1b[?2026h\x1b[2J\x1b[Hredrawing...")
34-
>>> term.committed.lines
35-
('frame 1', '')
36-
>>> term.snapshot().lines
37-
('redrawing...', '')
38-
>>> term.feed(b"\r\x1b[2Kframe 2\x1b[?2026l")
39-
>>> term.committed.lines
40-
('frame 2', '')
89+
>>> print(format_screen_box(term.committed))
90+
┌────────────────┐
91+
│frame 1 │
92+
│status: ok │
93+
└────────────────┘
94+
>>> print(format_screen_box(term.snapshot()))
95+
┌────────────────┐
96+
│redrawing... │
97+
│ │
98+
└────────────────┘
99+
>>> term.feed(b"\r\x1b[2Kframe 2\r\nstatus: done\x1b[?2026l")
100+
>>> print(format_screen_box(term.committed))
101+
┌────────────────┐
102+
│frame 2 │
103+
│status: done │
104+
└────────────────┘
41105
```
42106

43107
## Cells, 2D region slices, and `display_lines`
@@ -50,25 +114,35 @@ A `Snapshot` supports the same zero-based `(row, col)` indexing and slicing as
50114
{class}`~libvt.style.Hyperlink`).
51115
- `snap[row]` returns a {class}`~libvt.screen.RowView` with contiguous
52116
{attr}`~libvt.screen.RowView.runs` of identically styled text.
53-
- `snap[r0:r1, c0:c1]` returns a sub-grid {class}`~libvt.screen.RegionView`.
54-
- {attr}`~libvt.terminal.Snapshot.lines` right-trims trailing unwritten blanks,
117+
- `snap[r0:r1, c0:c1]` returns a rectangular {class}`~libvt.screen.RegionView`
118+
that also serializes directly as a sub-grid box.
119+
- {attr}`~libvt.terminal.Snapshot.lines` omits unwritten trailing blank cells,
55120
whereas {attr}`~libvt.terminal.Snapshot.display_lines` pads every row to full
56121
column width with spaces (clipping split wide characters cleanly at slice
57122
edges):
58123

59124
```python
60125
>>> import libvt
126+
>>> from libvt.testing import serialize_vt_snapshot
61127
>>> term = libvt.Terminal(rows=2, cols=10)
62-
>>> term.feed(b"\x1b[1;32mOK\x1b[0m done\r\nnext")
128+
>>> term.feed(b"\x1b[1;32mOK\x1b[0m done\r\nnext item")
63129
>>> snap = term.committed
64130
>>> snap[0, 0].text, snap[0, 0].style.bold, snap[0, 0].style.fg
65131
('O', True, <AnsiColor.GREEN: 2>)
132+
>>> [(run.text, run.style.bold) for run in snap[0].runs]
133+
[('OK', True), (' done', False)]
66134
>>> snap.lines
67-
('OK done', 'next')
135+
('OK done', 'next item')
68136
>>> snap.display_lines
69-
('OK done ', 'next ')
70-
>>> snap[0:2, 0:4].lines
71-
('OK', 'next')
137+
('OK done ', 'next item')
138+
>>> print(serialize_vt_snapshot(snap[0:2, 0:4]))
139+
size=4x2 region=True
140+
┌────┐
141+
│OK │
142+
│next│
143+
└────┘
144+
styles:
145+
r0[0..2]: bold fg=green
72146
```
73147

74148
## Stateless scrollback paging (`viewport()`)
@@ -77,39 +151,60 @@ Primary-screen snapshots retain frozen scrollback alongside the active
77151
viewport. {meth}`Snapshot.viewport <libvt.terminal.Snapshot.viewport>` returns
78152
a `(rows, cols)` {class}`~libvt.screen.RegionView` shifted `offset` lines
79153
backward into scrollback (clamped to available history) without mutating the
80-
live `Terminal`. When `active_is_alt` is `True` (`?1049h`), `viewport()` stays
81-
isolated to the alternate screen without blending primary scrollback:
154+
live `Terminal`. When {attr}`~libvt.terminal.Snapshot.active_is_alt` is `True`
155+
(alternate screen `?1049h`), `viewport()` stays isolated to the alternate
156+
screen without blending primary scrollback:
82157

83158
```python
84159
>>> import libvt
160+
>>> from libvt.testing import serialize_vt_snapshot
85161
>>> term = libvt.Terminal(rows=2, cols=12)
86162
>>> term.feed(b"line 1\r\nline 2\r\nline 3\r\nline 4")
87163
>>> snap = term.committed
88-
>>> snap.viewport(offset=0).lines
89-
('line 3', 'line 4')
90-
>>> snap.viewport(offset=2).lines
91-
('line 1', 'line 2')
164+
>>> len(snap.history), snap.scrolled_total
165+
(2, 2)
166+
>>> print(serialize_vt_snapshot(snap.viewport(offset=0)))
167+
size=12x2 region=True
168+
┌────────────┐
169+
│line 3 │
170+
│line 4 │
171+
└────────────┘
172+
>>> print(serialize_vt_snapshot(snap.viewport(offset=2)))
173+
size=12x2 region=True
174+
┌────────────┐
175+
│line 1 │
176+
│line 2 │
177+
└────────────┘
92178
```
93179

94-
## Metadata, semantic zones, and `to_dict()`
180+
## Metadata, semantic zones, `format()`, and `to_dict()`
95181

96182
Alongside cell grids, each `Snapshot` records terminal metadata at that
97-
generation (`cursor`, `modes`, `title`, `cwd` from `OSC 7`, `prompt_zones`
98-
from `OSC 133`, `program_status` from `OSC 7501` and `OSC 9;4`, `appearance`,
99-
and `placements`) and exports a deterministic JSON-compatible dictionary via
100-
{meth}`~libvt.terminal.Snapshot.to_dict`:
183+
generation ({attr}`~libvt.terminal.Snapshot.cursor`,
184+
{attr}`~libvt.terminal.Snapshot.modes`, {attr}`~libvt.terminal.Snapshot.title`,
185+
{attr}`~libvt.terminal.Snapshot.cwd` from `OSC 7`,
186+
{attr}`~libvt.terminal.Snapshot.prompt_zones` from `OSC 133`,
187+
{attr}`~libvt.terminal.Snapshot.program_status` from `OSC 7501` and `OSC 9;4`,
188+
{attr}`~libvt.terminal.Snapshot.appearance`, and
189+
{attr}`~libvt.terminal.Snapshot.placements`), renders to plain text, VT escape
190+
sequences, or HTML via {meth}`~libvt.terminal.Snapshot.format` and
191+
{class}`~libvt.terminal.OutputFormat`, and exports a deterministic
192+
JSON-compatible dictionary via {meth}`~libvt.terminal.Snapshot.to_dict`:
101193

102194
```python
103195
>>> import libvt
196+
>>> from libvt.terminal import OutputFormat
104197
>>> term = libvt.Terminal(rows=2, cols=14)
105-
>>> term.feed(b"\x1b]2;build\x07\x1b]133;A\x07$ \x1b]133;B\x07make\r\n")
198+
>>> term.feed(b"\x1b]2;build\x07\x1b]133;A\x07$ \x1b]133;B\x07\x1b[1mmake\x1b[0m\r\nok")
106199
>>> snap = term.committed
107200
>>> snap.title, len(snap.prompt_zones)
108201
('build', 2)
202+
>>> "<span" in snap.format(OutputFormat.HTML)
203+
True
109204
>>> payload = snap.to_dict()
110-
>>> payload["title"], payload["lines"][0]
111-
('build', '$ make')
205+
>>> payload["title"], payload["lines"], payload["cursor"]["row"]
206+
('build', ['$ make', 'ok'], 1)
112207
```
113208

114-
For asserting and serializing `Terminal` and `Snapshot` states in automated
115-
test suites, see {doc}`testing`.
209+
For asserting, scrubbing, and diffing `Terminal` and `Snapshot` grids in test
210+
suites, see {doc}`testing`.

‎src/libvt/contrib/tmux/capture.py‎

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -469,7 +469,7 @@ class CaptureCompleteness:
469469

470470
@dataclass(frozen=True, slots=True)
471471
class TmuxCaptureResult:
472-
"""Decoded ``tmux`` capture bundle ready for inspection or live streaming.
472+
r"""Decoded ``tmux`` capture bundle ready for inspection or live streaming.
473473
474474
Attributes
475475
----------
@@ -488,6 +488,24 @@ class TmuxCaptureResult:
488488
Parsed pre-capture pane metadata applied during reconstruction.
489489
post_metadata : TmuxPaneMetadata | None
490490
Optional post-capture pane metadata sample when bracketed.
491+
492+
Examples
493+
--------
494+
>>> from libvt.contrib.tmux.capture import decode_tmux_capture
495+
>>> from libvt.testing import serialize_vt_snapshot
496+
>>> res = decode_tmux_capture(
497+
... ["\x1b[1;32mPASS\x1b[0m suite", "done"],
498+
... rows=2,
499+
... cols=12,
500+
... )
501+
>>> print(serialize_vt_snapshot(res.snapshot))
502+
size=12x2 cursor=(0,0,vis=True) alt=False modes=[]
503+
┌────────────┐
504+
│PASS suite │
505+
│done │
506+
└────────────┘
507+
styles:
508+
r0[0..4]: bold fg=green
491509
"""
492510

493511
terminal: Terminal
@@ -1214,9 +1232,16 @@ def decode_tmux_capture(
12141232
Examples
12151233
--------
12161234
>>> from libvt.contrib.tmux.capture import decode_tmux_capture
1235+
>>> from libvt.testing import serialize_vt_snapshot
12171236
>>> res = decode_tmux_capture(["\x1b[32mready\x1b[0m", "done"], rows=2, cols=10)
1218-
>>> res.snapshot.lines
1219-
('ready', 'done')
1237+
>>> print(serialize_vt_snapshot(res.snapshot))
1238+
size=10x2 cursor=(0,0,vis=True) alt=False modes=[]
1239+
┌──────────┐
1240+
│ready │
1241+
│done │
1242+
└──────────┘
1243+
styles:
1244+
r0[0..5]: fg=green
12201245
"""
12211246
eff_hist_req = _validate_history_lines(history_lines)
12221247
fallback_sb = 2_000 if scrollback is None else scrollback

0 commit comments

Comments
 (0)