(topics-snapshots)=

# Snapshots

{class}`libvt.Snapshot <libvt.terminal.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 {class}`~libvt.terminal.Terminal` mutates its rows in place on every
{meth}`~libvt.terminal.Terminal.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
{func}`~libvt.contrib.tmux.capture.decode_tmux_capture`.

## What a `Snapshot` looks like

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

```python
>>> 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`:

```python
>>> 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:

- {attr}`term.committed <libvt.terminal.Terminal.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.
- {meth}`term.snapshot() <libvt.terminal.Terminal.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).

```python
>>> 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
{class}`~libvt.screen.Screen`:

- `snap[row, col]` returns an immutable {class}`~libvt.screen.Cell` (`text`,
  `width_role`, {class}`~libvt.style.Style`, and optional
  {class}`~libvt.style.Hyperlink`).
- `snap[row]` returns a {class}`~libvt.screen.RowView` with contiguous
  {attr}`~libvt.screen.RowView.runs` of identically styled text.
- `snap[r0:r1, c0:c1]` returns a rectangular {class}`~libvt.screen.RegionView`
  that also serializes directly as a sub-grid box.
- {attr}`~libvt.terminal.Snapshot.lines` omits unwritten trailing blank cells,
  whereas {attr}`~libvt.terminal.Snapshot.display_lines` pads every row to full
  column width with spaces (clipping split wide characters cleanly at slice
  edges):

```python
>>> 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. {meth}`Snapshot.viewport <libvt.terminal.Snapshot.viewport>` returns
a `(rows, cols)` {class}`~libvt.screen.RegionView` shifted `offset` lines
backward into scrollback (clamped to available history) without mutating the
live `Terminal`. When {attr}`~libvt.terminal.Snapshot.active_is_alt` is `True`
(alternate screen `?1049h`), `viewport()` stays isolated to the alternate
screen without blending primary scrollback:

```python
>>> 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 ({attr}`~libvt.terminal.Snapshot.cursor`,
{attr}`~libvt.terminal.Snapshot.modes`, {attr}`~libvt.terminal.Snapshot.title`,
{attr}`~libvt.terminal.Snapshot.cwd` from `OSC 7`,
{attr}`~libvt.terminal.Snapshot.prompt_zones` from `OSC 133`,
{attr}`~libvt.terminal.Snapshot.program_status` from `OSC 7501` and `OSC 9;4`,
{attr}`~libvt.terminal.Snapshot.appearance`, and
{attr}`~libvt.terminal.Snapshot.placements`), renders to plain text, VT escape
sequences, or HTML via {meth}`~libvt.terminal.Snapshot.format` and
{class}`~libvt.terminal.OutputFormat`, and exports a deterministic
JSON-compatible dictionary via {meth}`~libvt.terminal.Snapshot.to_dict`:

```python
>>> 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 {doc}`testing`.
