Skip to content
Open
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
21 changes: 21 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,27 @@ for ISO-2022 `DOCS` (`ESC % G` / `ESC % @`) transitions,
{meth}`Terminal.feed_str <libvt.terminal.Terminal.feed_str>` raises
{exc}`ValueError` when the wire encoding is `"latin-1"`.

#### Full-width display export and stateless snapshot history viewports (#59)

{class}`~libvt.terminal.Terminal`, {class}`~libvt.terminal.Snapshot`,
{class}`~libvt.screen.Screen`, and {class}`~libvt.screen.RegionView` add
`display_lines` (paired with
{attr}`RowView.display_text <libvt.screen.RowView.display_text>`) returning
visible rows padded with trailing spaces to exact terminal-column width while
replacing wide glyphs clipped at slice boundaries with `" "`.
{meth}`Snapshot.viewport <libvt.terminal.Snapshot.viewport>` returns an
immutable `(rows, cols)` {class}`~libvt.screen.RegionView` shifted upward into
retained primary scrollback by `offset` rows without mutating live terminal
state or blending primary history into alternate-screen snapshots. See
{ref}`topics-migrating-from-pyte` for details.

### Documentation

- Expand {ref}`topics-migrating-from-pyte` with a `pyte` compatibility matrix,
documented omissions, and runnable doctests for coordinate indexing, legacy
encodings, `display_lines`, {meth}`~libvt.terminal.Snapshot.viewport` paging,
dirty-row deltas, query replies, and `tmux` observation (#59).

## libvt 0.0.1a2 (2026-11-28)

`libvt` 0.0.1a2 splits {class}`~libvt.config.Profile` into capability groups
Expand Down
302 changes: 278 additions & 24 deletions docs/topics/migrating-from-pyte.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,44 +2,298 @@

# Migrating from `pyte`

Moving from `pyte` changes how you construct the terminal, feed output, and
inspect its state. This guide covers those API differences, alternate screens,
and terminal replies.
Moving from [pyte](https://github.com/selectel/pyte) (`0.8.2` comparison
baseline) replaces a separate `Stream` + `Screen` pair with a single
{class}`libvt.Terminal <libvt.terminal.Terminal>`, switches from `(cols, lines)`
arguments to keyword-only `(rows, cols)`, and replaces mutable dict/deque
buffers with typed `(row, col)` views, immutable
{class}`libvt.Snapshot <libvt.terminal.Snapshot>` values, and watermark deltas.

## Dimension order and coordinates
## Terminal construction and coordinates

`libvt` uses keyword-only `(rows, cols)` dimensions and zero-based `(row, col)`
indexing everywhere:
`pyte.Screen(columns, lines)` + `pyte.ByteStream(screen)` become a single
{class}`~libvt.terminal.Terminal` taking keyword-only `rows`, `cols`, and
`scrollback` (default `2_000` lines). Indexing uses zero-based `(row, col)`
coordinates everywhere, while 1-based VT sequences (`CSI row ; col H`) convert
at the parser boundary:

```python
>>> import libvt
>>> term = libvt.Terminal(rows=24, cols=80)
>>> term = libvt.Terminal(rows=24, cols=80, scrollback=1_000)
>>> term.feed(b"\x1b[2;5Hhello")
>>> term.cursor.row, term.cursor.col
(1, 9)
>>> (term.rows, term.cols, term.cursor.row, term.cursor.col)
(24, 80, 1, 9)
>>> term[1, 4].text
'h'
```

## Single byte-stream entry point

Instead of pairing a separate `pyte` stream with a screen object, feed `bytes`,
`bytearray`, or {class}`memoryview` directly to
{meth}`libvt.Terminal.feed <libvt.terminal.Terminal.feed>` (or UTF-8 strings via
{meth}`libvt.Terminal.feed_str <libvt.terminal.Terminal.feed_str>`):
Primary and alternate (`?47` / `?1047` / `?1049`) screen buffers exist by
default on {attr}`Terminal.screens <libvt.terminal.Terminal.screens>`; entering
and leaving a full-screen application preserves primary contents and scrollback:

```python
>>> import libvt
>>> term = libvt.Terminal(rows=4, cols=20, scrollback=500)
>>> term.feed(b"first\r\n\x1b[?1049hfullscreen\x1b[?1049l")
>>> term.feed(b"shell prompt\r\n\x1b[?1049htui view\x1b[?1049l")
>>> term.text
'first'
'shell prompt'
```

## Feeding bytes, text, and legacy encodings

Pass `bytes`, `bytearray`, or {class}`memoryview` chunks of any size to
{meth}`Terminal.feed <libvt.terminal.Terminal.feed>`; multi-byte UTF-8 sequences
and escape sequences split across chunk boundaries reassemble in
{class}`libvt.parser.Parser`. Pass decoded Python strings to
{meth}`Terminal.feed_str <libvt.terminal.Terminal.feed_str>` when the wire
encoding is `"utf-8"`:

```python
>>> import libvt
>>> term = libvt.Terminal(rows=2, cols=16)
>>> term.feed(b"caf\xc3")
>>> term.at_ground_state
False
>>> term.feed(b"\xa9 ")
>>> term.feed_str("ok")
>>> term[0].text
'café ok'
```

For legacy 8-bit streams (`ISO-8859-1` / `DEC` 8-bit `C1` / `CP437`), construct
`Terminal(..., encoding="latin-1")`, or opt into ISO-2022 `DOCS` wire switching
(`ESC % @` for legacy 8-bit and `ESC % G` for UTF-8) via
{data}`libvt.profiles.LINUX_CONSOLE_PROFILE` or
{attr}`ScreenBehavior.allow_encoding_switch <libvt.config.ScreenBehavior.allow_encoding_switch>`.
{data}`libvt.config.DEFAULT_PROFILE`, {data}`libvt.profiles.XTERM_PROFILE`, and
the `tmux` profiles keep `allow_encoding_switch=False` so untrusted output
cannot flip a UTF-8 session into 8-bit `C1` parsing. While `"latin-1"` is
active, `feed_str()` raises {exc}`ValueError` rather than UTF-8-encoding text
into Latin-1 bytes:

```python
>>> from libvt.profiles import LINUX_CONSOLE_PROFILE
>>> from libvt.terminal import Terminal
>>> term = Terminal(rows=2, cols=20, profile=LINUX_CONSOLE_PROFILE)
>>> term.feed(b"\x1b%@\x1b(U\xda\xc4\xbf\x1b%G UTF-8")
>>> term[0].text
'┌─┐ UTF-8'
```

## Cell, style, cursor, and mode inspection

Index `term[row]` for a {class}`~libvt.screen.RowView`, `term[row, col]` for an
immutable {class}`libvt.Cell <libvt.screen.Cell>`, or `term[r1:r2, c1:c2]` for a
{class}`~libvt.screen.RegionView`. Each `Cell` exposes `.text` (full grapheme
cluster, `""` on spacer cells), `.style`
({class}`libvt.Style <libvt.style.Style>` with
{class}`~libvt.style.AnsiColor`, {class}`~libvt.style.IndexedColor`, or
`(r, g, b)` tuples), `.width_role` ({class}`~libvt.screen.WidthRole`), and
`.hyperlink` ({class}`~libvt.style.Hyperlink`). Inspect cursor state via
{attr}`Terminal.cursor <libvt.terminal.Terminal.cursor>`
({class}`~libvt.screen.Cursor`) and enabled modes via
{attr}`Terminal.modes <libvt.terminal.Terminal.modes>`
({meth}`ModeState.is_set <libvt.modes.ModeState.is_set>` with
{class}`~libvt.modes.Mode`):

```python
>>> import libvt
>>> from libvt.modes import Mode
>>> from libvt.style import AnsiColor
>>> term = libvt.Terminal(rows=3, cols=16)
>>> term.feed(b"\x1b[?25l\x1b[1;32mREADY\x1b[0m")
>>> cell = term[0, 0]
>>> (cell.text, cell.style.bold, cell.style.fg)
('R', True, <AnsiColor.GREEN: 2>)
>>> (term.cursor.row, term.cursor.col, term.cursor.visible)
(0, 5, False)
>>> term.modes.is_set(Mode.DECTCEM)
False
```

## Full-width display export

`pyte.Screen.display` returns every row padded to the terminal width in columns.
Use {attr}`Terminal.display_lines <libvt.terminal.Terminal.display_lines>` (also
available on
{attr}`Snapshot.display_lines <libvt.terminal.Snapshot.display_lines>`,
{attr}`Screen.display_lines <libvt.screen.Screen.display_lines>`,
{attr}`RegionView.display_lines <libvt.screen.RegionView.display_lines>`, and
per-row {attr}`RowView.display_text <libvt.screen.RowView.display_text>`) when
callers expect rectangular space-padded lines; use
{attr}`Terminal.lines <libvt.terminal.Terminal.lines>` for right-trimmed rows or
{attr}`Terminal.text <libvt.terminal.Terminal.text>` to omit trailing blank
rows:

```python
>>> import libvt
>>> term = libvt.Terminal(rows=3, cols=8)
>>> term.feed_str("日本\r\nok")
>>> term.display_lines
('日本 ', 'ok ', ' ')
>>> term.lines
('日本', 'ok', '')
>>> term.text
'日本\nok'
```

Sub-row and sub-region slices replace wide characters split at the left or right
slice edge with `" "` so `display_text` and `display_lines` always match the
slice width in terminal columns:

```python
>>> import libvt
>>> term = libvt.Terminal(rows=1, cols=6)
>>> term.feed_str("A日本B")
>>> snap = term.snapshot()
>>> snap[0][1:4].display_text, snap[0][2:5].display_text
('日 ', ' 本')
```

## Stateless history browsing

Instead of mutating the live screen in place with `HistoryScreen.prev_page()`
and `next_page()`, capture an immutable `snap = term.snapshot()` and call
{meth}`Snapshot.viewport <libvt.terminal.Snapshot.viewport>` with a non-negative
row `offset` (`offset=0` returns the active viewport, positive offsets move
upward into retained scrollback, and offsets past `len(snap.history)` clamp at
the earliest retained row). Alternate-screen snapshots return their alternate
viewport without blending primary history, and subsequent `term.feed()` calls
leave existing snapshots and views unchanged:

```python
>>> import libvt
>>> term = libvt.Terminal(rows=2, cols=8, scrollback=20)
>>> for i in range(6):
... term.feed_str(f"row-{i}" + ("\r\n" if i < 5 else ""))
>>> snap = term.snapshot()
>>> page = snap.rows
>>> max_offset = len(snap.history)
>>> offset = min(max_offset, 2 * page) # two pages up
>>> snap.viewport(offset).lines
('row-0', 'row-1')
>>> offset = max(0, offset - page) # one page down
>>> snap.viewport(offset).lines
('row-2', 'row-3')
>>> snap.viewport(0).display_lines # return to latest output
('row-4 ', 'row-5 ')
```

## Bidirectional replies and side-effect events
## Dirty-row tracking through deltas

Instead of clearing a mutable `screen.dirty` set, record a
{class}`~libvt.terminal.SyncToken` with
{meth}`Terminal.sync_token <libvt.terminal.Terminal.sync_token>` and compute a
{class}`~libvt.terminal.ScreenDelta` with
{meth}`Terminal.changes_since <libvt.terminal.Terminal.changes_since>`. Check {attr}`ScreenDelta.full_resync <libvt.terminal.ScreenDelta.full_resync>`
first (triggered on resize, `RIS`, or primary/alternate switches); otherwise
repaint {attr}`ScreenDelta.dirty_rows <libvt.terminal.ScreenDelta.dirty_rows>`
after applying
{attr}`ScreenDelta.viewport_scroll_up <libvt.terminal.ScreenDelta.viewport_scroll_up>`:

```python
>>> import libvt
>>> term = libvt.Terminal(rows=4, cols=12)
>>> term.feed(b"row0\r\nrow1\r\nrow2")
>>> tok = term.sync_token()
>>> term.feed(b"\x1b[2;1HUPDATED")
>>> delta = term.changes_since(tok)
>>> (delta.full_resync, delta.dirty_rows)
(False, (1,))
```

## Terminal replies and parser inspection

Queries such as `DSR` (`CSI 6 n`), `DA1`/`DA2` (`CSI c` / `CSI > c`), `DECRQM`,
`DECRQSS`, and `OSC 10`/`11` queue wire responses for
{meth}`Terminal.drain_replies <libvt.terminal.Terminal.drain_replies>` (or pass
`on_pty_write` to forward replies directly to a transport). For sequence
debugging (`pyte.DebugScreen`) or custom stream consumers (`pyte.Stream`), call
{func}`libvt.codec.explain` or drive {class}`~libvt.parser.Parser` with an
{class}`~libvt.parser.ActionSink`:

```python
>>> import libvt
>>> from libvt.codec import explain
>>> term = libvt.Terminal(rows=4, cols=20)
>>> term.feed(b"abc\x1b[6n")
>>> term.drain_replies()
b'\x1b[1;4R'
>>> [(s.kind, s.mnemonic, s.summary) for s in explain(b"\x1b[31mhi\x1b[0m")]
[('CSI', 'SGR', '31m'), ('PRINT', 'TEXT', "'hi'"), ('CSI', 'SGR', '0m')]
```

## 80/132-column switching and `tmux` pane observation

{data}`~libvt.config.DEFAULT_PROFILE` configures
{attr}`ScreenBehavior.deccolm <libvt.config.ScreenBehavior.deccolm>` with
{attr}`DeccolmBehavior.GATED_BY_MODE_40 <libvt.config.DeccolmBehavior.GATED_BY_MODE_40>`
and DEC mode `?40` ({attr}`Mode.ALLOW_80_132 <libvt.modes.Mode.ALLOW_80_132>`)
initially disabled: `?3h` and `?3l` are no-ops until `?40h` enables `80`/`132`
column switching, `?3l` selects `80` columns unconditionally (never restoring
an arbitrary prior width), and `?95h`
({attr}`Mode.DECNCSM <libvt.modes.Mode.DECNCSM>`) suppresses screen clearing
during the switch. Pass
{attr}`DeccolmBehavior.ALWAYS <libvt.config.DeccolmBehavior.ALWAYS>` when
emulating legacy applications that emit `?3h` without `?40h`:

```python
>>> import libvt
>>> term = libvt.Terminal(rows=4, cols=90)
>>> term.feed(b"\x1b[?3h") # ignored while ?40 is disabled
>>> term.cols
90
>>> term.feed(b"\x1b[?40h\x1b[?3h")
>>> term.cols
132
>>> term.feed(b"\x1b[?3l")
>>> term.cols
80
```

When observing a `tmux` pane via {mod}`libvt.contrib.tmux`
({func}`~libvt.contrib.tmux.capture.decode_tmux_capture`,
{func}`~libvt.contrib.tmux.capture.build_tmux_capture_command`, and
{class}`~libvt.contrib.tmux.control.TmuxPaneSync`),
{func}`~libvt.contrib.tmux.profile.tmux_profile` sets
{attr}`DeccolmBehavior.CLEAR_ONLY <libvt.config.DeccolmBehavior.CLEAR_ONLY>` and
{data}`~libvt.contrib.tmux.profile.TMUX_OBSERVER_POLICY` sets
`emit_replies=False`. `tmux` remains authoritative for pane geometry across live
attachment, and passive observation never writes duplicate query replies back to
the application.

## Compatibility matrix and documented omissions

Comparison baseline: `pyte 0.8.2`.

| Capability | `pyte` (`0.8.2`) | `libvt` equivalent | Differences and omissions |
| :--- | :--- | :--- | :--- |
| Screen + parser | `Screen(cols, lines)` + `ByteStream` | {class}`~libvt.terminal.Terminal` (`rows=`, `cols=`) | Keyword `(rows, cols)`; zero-based `(row, col)` |
| Cursor & margins | `CUU`/`CUD`/`CUF`/`CUB`/`CUP`/`DECSTBM` | `Terminal` (`DECSTBM` + `?69` `DECSLRM`) | Adds `CHT`/`CBT` (`I`/`Z`), `HPR`/`VPR`, left/right margins |
| Editing & erase | `ED`, `EL`, `ICH`, `DCH`, `IL`, `DL`, `ECH` | `Terminal` + `Screen` | Adds `DECSED`/`DECSEL` (`DECSCA` protection), `ED 3` history clear, `REP` |
| Tabstops | `HTS`, `TBC 0`/`3` | {attr}`Screen.tabstops <libvt.screen.Screen.tabstops>` | Immutable sorted `tuple[int, ...]` |
| Modes & `?1049` | Mutable bit-shifted `screen.mode` set; no alt buffer | {attr}`Terminal.modes <libvt.terminal.Terminal.modes>` ({class}`~libvt.modes.Mode`) | Dual primary/alternate screens (`?47`/`?1047`/`?1049`), `?2004`, `?2026`, `?2027`, `XTSAVE`/`XTRESTORE` |
| `DECCOLM` (`?3`) | Always resizes `132` / saved width | {class}`~libvt.config.DeccolmBehavior` (`?3`, `?40`, `?95`) | Default `GATED_BY_MODE_40`; `?3l` selects `80` cols unconditionally; `CLEAR_ONLY` on `tmux` |
| Character sets | `B`, `0`, `A`, `U` (CP437), `V` (`VAX42`) | `G0`–`G3` (`B`, `0`, `A`, `U`), `SI`/`SO`/`LS2`/`LS3`/`SS2`/`SS3` | **pyte’s VAX42 extension is unsupported** (falls back to `'B'`); `'U'` maps `0xA0..0xFF` in `"latin-1"` |
| Wire encoding | `ESC % G` / `ESC % @` always active | `Parser(encoding=...)` + `allow_encoding_switch` | Default `False` (UTF-8 locked); `True` on `LINUX_CONSOLE_PROFILE`; `feed_str()` raises `ValueError` in `"latin-1"` |
| Colors & SGR | Strings / hex RGB; basic SGR | {class}`~libvt.style.Style` (`AnsiColor`, `IndexedColor`, RGB) | Adds `dim`, `overline`, `hidden`, ITU T.416 `:` subparameters (`4:3` curly underline, `58:...` underline color), `OSC 8` links |
| Unicode & width | `wcwidth` per code point | Unicode 17 UAX #11 / #29 (`?2027`) | Zero-width combining marks, `VS15`/`VS16`, regional flags, and ZWJ emoji stay in single wide cells |
| Resizing | Truncates/pads without reflow | {meth}`Terminal.resize <libvt.terminal.Terminal.resize>` (`reflow=...`) | Soft-wrapped primary lines reflow by default (`reflow=False` opts out) |
| History paging | `HistoryScreen` mutates `screen.buffer` | {attr}`Terminal.history <libvt.terminal.Terminal.history>`, {meth}`Snapshot.viewport <libvt.terminal.Snapshot.viewport>` | Stateless `(rows, cols)` `RegionView` over immutable snapshots |
| Full-grid export | `screen.display` | `display_lines`, `RowView.display_text` | Space-padded to terminal columns with wide-boundary clipping |
| Change tracking | Mutable `screen.dirty` set | `sync_token()` + `changes_since()` | Watermark `ScreenDelta` safe for multiple independent observers |
| Parser debug & replies | `DebugScreen`, `write_process_input` | {func}`~libvt.codec.explain`, `Parser`, `drain_replies()`, `on_pty_write` | Replies buffered up to `Limits.max_reply_bytes` or streamed via callback |

Intentional omissions and behavioral differences:

Terminal queries (`CSI 6 n`, `CSI c`, `DECRQM`, `DECRQSS`, `XTVERSION`,
`XTGETTCAP`, `OSC 10/11 ; ?`) accumulate in
{meth}`libvt.Terminal.drain_replies <libvt.terminal.Terminal.drain_replies>`
rather than being dropped, and structured notifications (`OSC 0/2`, `OSC 7`,
`OSC 52`, `OSC 133`, `OSC 7501`, `?2026`) flow through `on_event` or
{meth}`libvt.Terminal.drain_events <libvt.terminal.Terminal.drain_events>`.
- **pyte’s VAX42 extension is unsupported.** Designating `'V'` via `ESC ( V`
(or `)` / `*` / `+`) falls back to US-ASCII (`'B'`).
- **`DECCOLM` (`?3`) requires `?40h` on `DEFAULT_PROFILE` and resets to `80`
columns.** Enable `?40h` or configure
{attr}`DeccolmBehavior.ALWAYS <libvt.config.DeccolmBehavior.ALWAYS>` when
testing bare `CSI ? 3 h` sequences; `CSI ? 3 l` always selects `80` columns
rather than restoring a pre-`DECCOLM` custom width.
- **Wire encoding switches (`ESC % @` / `ESC % G`) default off.** Enable
`allow_encoding_switch=True` (or
{data}`~libvt.profiles.LINUX_CONSOLE_PROFILE`) when replaying legacy ISO-2022
`DOCS` byte streams.
Loading
Loading