Snapshots

libvt.Snapshot freezes a terminal’s active viewport, scrollback history, cursor state, active DEC/ANSI modes, semantic prompt zones, program status, and graphics placements at one point in time. Because Terminal mutates its rows in place on every feed() call, a Snapshot gives callers an immutable 2D screen value safe to pass across threads, store in UI state, diff across test steps, or return from multiplexer adapters such as decode_tmux_capture().

What a Snapshot looks like

Render any Snapshot visually as a column-aligned ┌──┐ box with format_screen_box() (marking soft-wrapped rows with a trailing W), or include its cursor, mode header, and run-length SGR style spans with serialize_vt_snapshot():

>>> import libvt
>>> from libvt.testing import format_screen_box, serialize_vt_snapshot
>>> term = libvt.Terminal(rows=3, cols=16)
>>> term.feed(
...     b"\x1b[1;32mPASS\x1b[0m suite=core_parser\r\n"
...     b"\x1b[7m> rerun\x1b[0m"
... )
>>> snap = term.committed
>>> print(format_screen_box(snap))
┌────────────────┐
│PASS suite=core_│W
│parser          │
│> rerun         │
└────────────────┘
>>> print(serialize_vt_snapshot(snap))
size=16x3 cursor=(2,7,vis=True) alt=False modes=[]
┌────────────────┐
│PASS suite=core_│W
│parser          │
│> rerun         │
└────────────────┘
styles:
  r0[0..4]: bold fg=green
  r2[0..7]: reverse

Once captured, snap never mutates when later bytes arrive on term:

>>> import libvt
>>> from libvt.testing import format_screen_box
>>> term = libvt.Terminal(rows=2, cols=12)
>>> term.feed(b"step 1\r\nready")
>>> snap = term.committed
>>> term.feed(b"\x1b[2J\x1b[Hstep 2")
>>> print(format_screen_box(snap))
┌────────────┐
│step 1      │
│ready       │
└────────────┘
>>> print(format_screen_box(term.committed))
┌────────────┐
│step 2      │
│            │
└────────────┘

term.committed vs term.snapshot()

Choose between two capture points depending on whether you want completed frames or raw in-flight buffer state:

  • term.committed returns the last completed frame, holding steady while synchronized output (?2026) is open (CSI ? 2026 h … CSI ? 2026 l) so UI renderers, observers, and test predicates never read half-erased screens.

  • term.snapshot() captures the live working buffer immediately, even inside an open ?2026 block (reusing the cached Snapshot in O(1) when no cells or metadata changed since the last call).

>>> import libvt
>>> from libvt.testing import format_screen_box
>>> term = libvt.Terminal(rows=2, cols=16)
>>> term.feed(b"frame 1\r\nstatus: ok")
>>> term.feed(b"\x1b[?2026h\x1b[2J\x1b[Hredrawing...")
>>> print(format_screen_box(term.committed))
┌────────────────┐
│frame 1         │
│status: ok      │
└────────────────┘
>>> print(format_screen_box(term.snapshot()))
┌────────────────┐
│redrawing...    │
│                │
└────────────────┘
>>> term.feed(b"\r\x1b[2Kframe 2\r\nstatus: done\x1b[?2026l")
>>> print(format_screen_box(term.committed))
┌────────────────┐
│frame 2         │
│status: done    │
└────────────────┘

Cells, 2D region slices, and display_lines

A Snapshot supports the same zero-based (row, col) indexing and slicing as Screen:

  • snap[row, col] returns an immutable Cell (text, width_role, Style, and optional Hyperlink).

  • snap[row] returns a RowView with contiguous runs of identically styled text.

  • snap[r0:r1, c0:c1] returns a rectangular RegionView that also serializes directly as a sub-grid box.

  • lines omits unwritten trailing blank cells, whereas display_lines pads every row to full column width with spaces (clipping split wide characters cleanly at slice edges):

>>> import libvt
>>> from libvt.testing import serialize_vt_snapshot
>>> term = libvt.Terminal(rows=2, cols=10)
>>> term.feed(b"\x1b[1;32mOK\x1b[0m  done\r\nnext  item")
>>> snap = term.committed
>>> snap[0, 0].text, snap[0, 0].style.bold, snap[0, 0].style.fg
('O', True, <AnsiColor.GREEN: 2>)
>>> [(run.text, run.style.bold) for run in snap[0].runs]
[('OK', True), ('  done', False)]
>>> snap.lines
('OK  done', 'next  item')
>>> snap.display_lines
('OK  done  ', 'next  item')
>>> print(serialize_vt_snapshot(snap[0:2, 0:4]))
size=4x2 region=True
┌────┐
│OK  │
│next│
└────┘
styles:
  r0[0..2]: bold fg=green

Stateless scrollback paging (viewport())

Primary-screen snapshots retain frozen scrollback alongside the active viewport. Snapshot.viewport returns a (rows, cols) RegionView shifted offset lines backward into scrollback (clamped to available history) without mutating the live Terminal. When active_is_alt is True (alternate screen ?1049h), viewport() stays isolated to the alternate screen without blending primary scrollback:

>>> import libvt
>>> from libvt.testing import serialize_vt_snapshot
>>> term = libvt.Terminal(rows=2, cols=12)
>>> term.feed(b"line 1\r\nline 2\r\nline 3\r\nline 4")
>>> snap = term.committed
>>> len(snap.history), snap.scrolled_total
(2, 2)
>>> print(serialize_vt_snapshot(snap.viewport(offset=0)))
size=12x2 region=True
┌────────────┐
│line 3      │
│line 4      │
└────────────┘
>>> print(serialize_vt_snapshot(snap.viewport(offset=2)))
size=12x2 region=True
┌────────────┐
│line 1      │
│line 2      │
└────────────┘

Metadata, semantic zones, format(), and to_dict()

Alongside cell grids, each Snapshot records terminal metadata at that generation (cursor, modes, title, cwd from OSC 7, prompt_zones from OSC 133, program_status from OSC 7501 and OSC 9;4, appearance, and placements), renders to plain text, VT escape sequences, or HTML via format() and OutputFormat, and exports a deterministic JSON-compatible dictionary via to_dict():

>>> import libvt
>>> from libvt.terminal import OutputFormat
>>> term = libvt.Terminal(rows=2, cols=14)
>>> term.feed(b"\x1b]2;build\x07\x1b]133;A\x07$ \x1b]133;B\x07\x1b[1mmake\x1b[0m\r\nok")
>>> snap = term.committed
>>> snap.title, len(snap.prompt_zones)
('build', 2)
>>> "<span" in snap.format(OutputFormat.HTML)
True
>>> payload = snap.to_dict()
>>> payload["title"], payload["lines"], payload["cursor"]["row"]
('build', ['$ make', 'ok'], 1)

For asserting, scrubbing, and diffing Terminal and Snapshot grids in test suites, see Testing Terminal Programs.