From 9f579acbcfa8e8be583fbd183fb9c9f5468f601d Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 09:19:12 -0600 Subject: [PATCH] docs(api): Add per-module pages and split aio why: Give every public module and split package its own API reference page after #204 and earlier contrib splits while preserving existing docs URLs through Sphinx rediraffe redirects. what: - Break docs/api/aio.md into docs/api/aio/{index,core,stream,pty}.md - Break docs/api/contrib_tmux.md and contrib_syrupy.md into docs/api/contrib/{index,syrupy}.md and docs/api/contrib/tmux/{index,profile,capture,window,control}.md - Add dedicated pages for views, snapshot, format, and recorder - Scope screen.md and terminal.md to owned symbols and canonicalize cross-references across docs, docstrings, CHANGES, and MIGRATION - Update docs/redirects.txt for moved API paths and document the dirhtml same-path note for api/aio - Add test_every_public_module_has_api_doc_page() in tests/test_libvt.py Refs #203 --- CHANGES | 106 ++++++------ MIGRATION | 18 +- README.md | 8 +- docs/api/aio.md | 14 -- docs/api/aio/core.md | 21 +++ docs/api/aio/index.md | 42 +++++ docs/api/aio/pty.md | 14 ++ docs/api/aio/stream.md | 12 ++ docs/api/contrib/index.md | 34 ++++ .../{contrib_syrupy.md => contrib/syrupy.md} | 2 +- docs/api/contrib/tmux/capture.md | 65 ++++++++ docs/api/contrib/tmux/control.md | 56 +++++++ docs/api/contrib/tmux/index.md | 50 ++++++ docs/api/contrib/tmux/profile.md | 7 + docs/api/contrib/tmux/window.md | 14 ++ docs/api/contrib_tmux.md | 154 ------------------ docs/api/format.md | 7 + docs/api/index.md | 31 ++-- docs/api/pytest_plugin.md | 4 +- docs/api/recorder.md | 7 + docs/api/screen.md | 6 +- docs/api/snapshot.md | 15 ++ docs/api/terminal.md | 15 +- docs/api/testing.md | 2 +- docs/api/views.md | 7 + docs/project/public-api.md | 21 ++- docs/quickstart.md | 8 +- docs/redirects.txt | 5 +- docs/topics/index.md | 2 +- docs/topics/migrating-from-pyte.md | 30 ++-- docs/topics/protocols-and-input.md | 2 +- docs/topics/snapshots.md | 46 +++--- docs/topics/sync-and-asyncio.md | 8 +- docs/topics/testing.md | 10 +- src/libvt/aio/_core.py | 8 +- src/libvt/config.py | 2 +- src/libvt/contrib/tmux/capture.py | 8 +- src/libvt/contrib/tmux/control.py | 4 +- src/libvt/contrib/tmux/window.py | 12 +- src/libvt/exc.py | 2 +- src/libvt/format.py | 4 +- src/libvt/pytest_plugin.py | 2 +- src/libvt/screen.py | 2 +- src/libvt/snapshot.py | 6 +- src/libvt/terminal.py | 4 +- src/libvt/testing.py | 16 +- src/libvt/views.py | 2 +- tests/test_libvt.py | 30 +++- 48 files changed, 595 insertions(+), 350 deletions(-) delete mode 100644 docs/api/aio.md create mode 100644 docs/api/aio/core.md create mode 100644 docs/api/aio/index.md create mode 100644 docs/api/aio/pty.md create mode 100644 docs/api/aio/stream.md create mode 100644 docs/api/contrib/index.md rename docs/api/{contrib_syrupy.md => contrib/syrupy.md} (97%) create mode 100644 docs/api/contrib/tmux/capture.md create mode 100644 docs/api/contrib/tmux/control.md create mode 100644 docs/api/contrib/tmux/index.md create mode 100644 docs/api/contrib/tmux/profile.md create mode 100644 docs/api/contrib/tmux/window.md delete mode 100644 docs/api/contrib_tmux.md create mode 100644 docs/api/format.md create mode 100644 docs/api/recorder.md create mode 100644 docs/api/snapshot.md create mode 100644 docs/api/views.md diff --git a/CHANGES b/CHANGES index 9fa02473..9f042a29 100644 --- a/CHANGES +++ b/CHANGES @@ -10,7 +10,7 @@ _Notes on the upcoming release will go here._ #### Recorder protocol, target protocol, and state replacement (#203) -Pass any {class}`~libvt.terminal.TerminalRecorder` implementation to +Pass any {class}`~libvt.recorder.TerminalRecorder` implementation to {class}`~libvt.terminal.Terminal` to observe normalized input spans and external resizes without monkey-patching. Call {meth}`~libvt.terminal.Terminal.replace_from` to replace emulated screen, mode, @@ -23,17 +23,27 @@ wrappers passed to {func}`~libvt.testing.vt_screen` and {class}`~libvt.aio.AsyncTerminalStream`, {class}`~libvt.aio.PtySession`, and {class}`~libvt.contrib.tmux.capture.TmuxCaptureResult` implement this protocol directly. {func}`~libvt.modes.is_private_mode_supported` exposes profile mode -support queries, and {class}`~libvt.terminal.SnapshotDict` types the dictionary -returned by {meth}`~libvt.terminal.Snapshot.to_dict`. +support queries, and {class}`~libvt.snapshot.SnapshotDict` types the dictionary +returned by {meth}`~libvt.snapshot.Snapshot.to_dict`. + +### Documentation + +#### Split API reference into per-module pages + +Add dedicated API reference pages for {mod}`libvt.views`, +{mod}`libvt.snapshot`, {mod}`libvt.format`, and {mod}`libvt.recorder`, break +{mod}`libvt.aio` and {mod}`libvt.contrib` (including `tmux` submodules and +`syrupy`) into per-module directories, and add Sphinx `rediraffe` redirects for +moved API URLs. ## libvt 0.0.1a6 (2026-12-05) `libvt` 0.0.1a6 adds soft-wrapped logical-line reading and `wait_for()` -matching ({attr}`~libvt.terminal.Snapshot.unwrapped_text`), `os.PathLike` +matching ({attr}`~libvt.snapshot.Snapshot.unwrapped_text`), `os.PathLike` snapshot scrubbers, prepared VT diff baselines and nested container diffs, initial PTY encoding and event recording, `StopOn.PROGRAM_STATUS` stepping, tmux process replacement and session-scope tracking, paired untrimmed tmux -capture bundles, exact {class}`~libvt.terminal.FlightRecorder` byte bounds, +capture bundles, exact {class}`~libvt.recorder.FlightRecorder` byte bounds, strided buffer support across parser, PTY, and tmux control helpers, and fixes for async stream teardown, PTY process-group cleanup, VT replay checkpoints, Kitty key releases, mouse mode selection, and nested region @@ -71,12 +81,12 @@ of a drive letter. Use an explicit regex for paths inside URIs. When using #### Read soft-wrapped rows as logical lines (#152) -Use {attr}`~libvt.terminal.Snapshot.unwrapped_text`, +Use {attr}`~libvt.snapshot.Snapshot.unwrapped_text`, {attr}`~libvt.terminal.Terminal.unwrapped_text`, {attr}`~libvt.screen.Screen.unwrapped_text`, or -{attr}`~libvt.screen.RegionView.unwrapped_text` to join soft wraps while +{attr}`~libvt.views.RegionView.unwrapped_text` to join soft wraps while retaining hard line breaks. Pass `unwrap=True` to -{meth}`~libvt.terminal.Snapshot.format`, {class}`~libvt.terminal.Formatter`, +{meth}`~libvt.snapshot.Snapshot.format`, {class}`~libvt.format.Formatter`, or {func}`libvt.render ` for plain text or HTML. ### Fixes @@ -160,8 +170,8 @@ is false and `unexposed_fields` lists `grapheme_widths`. Pass #### Restore viewport state when replaying VT snapshots (#180) -{meth}`~libvt.terminal.Snapshot.format` with -{attr}`~libvt.terminal.OutputFormat.VT` restores scroll margins, cell +{meth}`~libvt.snapshot.Snapshot.format` with +{attr}`~libvt.format.OutputFormat.VT` restores scroll margins, cell protection, and the active SGR, OSC 8, and DECSCA pen. The formatter paints stored glyphs in their recorded widths and preserves pending wrap where it can reprint the captured margin glyph in place. @@ -174,19 +184,19 @@ Each reads the logical bytes. Step offsets count those bytes. #### Keep retained live rows and nested regions in bounds (#183) -{class}`~libvt.screen.RowView` uses the current width for a live row's +{class}`~libvt.views.RowView` uses the current width for a live row's length, indexing, and rendering. Retained slices clip their selected columns to the current width. Frozen rows keep their captured dimensions. -{class}`~libvt.screen.RegionView` accepts two-axis nested indexing in its own +{class}`~libvt.views.RegionView` accepts two-axis nested indexing in its own coordinates, clipping live regions to their retained rows after a resize and preserving captured dimensions for snapshot regions. Public read-model -properties now cover {attr}`~libvt.screen.RegionView.columns`, -{attr}`~libvt.screen.RowView.columns`, {attr}`~libvt.screen.RowView.used`, -{attr}`~libvt.screen.RowView.text_used`, -{attr}`~libvt.screen.RowView.full_row`, {attr}`~libvt.screen.Screen.profile`, +properties now cover {attr}`~libvt.views.RegionView.columns`, +{attr}`~libvt.views.RowView.columns`, {attr}`~libvt.views.RowView.used`, +{attr}`~libvt.views.RowView.text_used`, +{attr}`~libvt.views.RowView.full_row`, {attr}`~libvt.screen.Screen.profile`, {attr}`~libvt.screen.Screen.is_alt`, and -{attr}`~libvt.terminal.Snapshot.profile`. +{attr}`~libvt.snapshot.Snapshot.profile`. #### Repeat the last printed character on the Ghostty profile (#185) @@ -503,7 +513,7 @@ CI runs ty on the terminal package, test suite and development scripts at the su ({class}`~libvt.config.DeccolmBehavior`), `IBM PC` / `CP437` (`'U'`) graphic charset designations, and opt-in ISO-2022 `DOCS` wire-encoding transitions for legacy terminal streams. It also adds column-padded `display_lines` export and -stateless {meth}`Snapshot.viewport ` +stateless {meth}`Snapshot.viewport ` scrollback paging, and expands {mod}`libvt.contrib.tmux` with cursor/keypad/key-mode metadata, bounded `history_lines` capture, `%layout-change` resizing, and in-place @@ -541,14 +551,14 @@ for ISO-2022 `DOCS` (`ESC % G` / `ESC % @`) transitions, #### 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 +{class}`~libvt.terminal.Terminal`, {class}`~libvt.snapshot.Snapshot`, +{class}`~libvt.screen.Screen`, and {class}`~libvt.views.RegionView` add `display_lines` (paired with -{attr}`RowView.display_text `) returning +{attr}`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 ` returns an -immutable `(rows, cols)` {class}`~libvt.screen.RegionView` shifted upward into +{meth}`Snapshot.viewport ` returns an +immutable `(rows, cols)` {class}`~libvt.views.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. @@ -568,13 +578,13 @@ state or blending primary history into alternate-screen snapshots. See `%layout-change` notifications and adds {meth}`~libvt.contrib.tmux.control.TmuxPaneSync.resync` (also triggered on `%pause` / `%continue` recovery) updating `sync.terminal` in place while -advancing its epoch for {class}`~libvt.terminal.SyncToken` consumers. +advancing its epoch for {class}`~libvt.snapshot.SyncToken` consumers. ### 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, + encodings, `display_lines`, {meth}`~libvt.snapshot.Snapshot.viewport` paging, dirty-row deltas, query replies, and `tmux` observation (#59). ## libvt 0.0.1a2 (2026-11-28) @@ -587,7 +597,7 @@ with {mod}`libvt.profiles` host presets, moves `tmux` support into decoupled {mod}`libvt` behind lazy PEP 562 imports. It also converts {class}`~libvt.events.Event` to an open base class with `OSC 633` shell integration and `OSC 9`/`99`/`777` {class}`~libvt.events.Notification` events, -holds {attr}`Snapshot.appearance ` across +holds {attr}`Snapshot.appearance ` across `?2026` redraws, adds stateful `XTSMGRAPHICS`, `XTSAVE`/`XTRESTORE`, Kitty alternate-key and associated-text encoding, and bidirectional {class}`~libvt.aio.AsyncSession` writes, and certifies `PyPy 3.12` in CI. See @@ -599,11 +609,11 @@ alternate-key and associated-text encoding, and bidirectional #### Curated PEP 562 `libvt` root namespace (#43) Top-level {mod}`libvt` narrows `libvt.__all__` to a curated quickstart surface -({class}`~libvt.style.Appearance`, {class}`~libvt.screen.Cell`, +({class}`~libvt.style.Appearance`, {class}`~libvt.views.Cell`, {class}`~libvt.events.Event`, {exc}`~libvt.exc.LibVtError`, {class}`~libvt.config.Limits`, {class}`~libvt.config.Policy`, {class}`~libvt.config.Profile`, {exc}`~libvt.exc.ProtocolError`, -{class}`~libvt.screen.Screen`, {class}`~libvt.terminal.Snapshot`, +{class}`~libvt.screen.Screen`, {class}`~libvt.snapshot.Snapshot`, {class}`~libvt.style.Style`, {class}`~libvt.terminal.Terminal`, `__version__`, {func}`~libvt.terminal.render`, and {func}`~libvt.terminal.strip`) resolved lazily via PEP 562 so `import libvt` and `pytest11` plugin discovery do not load @@ -814,9 +824,9 @@ outside stateless {meth}`~libvt.terminal.Terminal.encode`, and {class}`~libvt.style.Appearance` captures active color scheme, default foreground/background/cursor RGBs, `OSC 4` palette overrides, and DEC mode `?5` ({attr}`~libvt.modes.Mode.DECSCNM`) reverse video on -{attr}`~libvt.terminal.Snapshot.appearance` and -{attr}`~libvt.terminal.ScreenDelta.appearance_changed`, held atomically across -`?2026` synchronized updates and rendered in {class}`~libvt.terminal.Formatter` +{attr}`~libvt.snapshot.Snapshot.appearance` and +{attr}`~libvt.snapshot.ScreenDelta.appearance_changed`, held atomically across +`?2026` synchronized updates and rendered in {class}`~libvt.format.Formatter` HTML and VT output. {meth}`~libvt.terminal.Terminal.set_theme` updates host theme defaults without clobbering guest `OSC 4` / `OSC 10`–`12` overrides and emits `CSI ? 997 ; Ps n` when `?2031` @@ -861,7 +871,7 @@ cell-calibrated `?1016` pixel mouse coordinates, and chained `tmux` capture bundles (`-N -T -F`). It also buffers outbound POSIX PTY writes above kernel `TTYHOG` limits, expires stalled `?2026` holds on `EOF` and close, retains `SIXEL` and Kitty graphics across `DECSTBM` scrolls and resize reflow, and -isolates per-terminal {class}`~libvt.terminal.SyncToken` watermarks. See +isolates per-terminal {class}`~libvt.snapshot.SyncToken` watermarks. See {doc}`topics/protocols-and-input`, {doc}`topics/sync-and-asyncio`, and {doc}`migration` for upgrade details. @@ -905,9 +915,9 @@ res = decode_tmux_capture(["\x1b[5:3mOV\x1b[0m"], rows=1, cols=4) #### Opaque per-terminal sync watermarks (#22) -{class}`~libvt.terminal.SyncToken` keeps its watermark state private, disallows +{class}`~libvt.snapshot.SyncToken` keeps its watermark state private, disallows direct instantiation, and renders a compact `repr()`. Read snapshot state from -{attr}`~libvt.terminal.ScreenDelta.snapshot` rather than inspecting token +{attr}`~libvt.snapshot.ScreenDelta.snapshot` rather than inspecting token attributes directly: ```python @@ -952,7 +962,7 @@ command chains bracketing `capture-pane -S - -E - -e -p -N -T -F` (`-e -p -N mid-capture and trailing blank viewport lines survive line-splitting wrappers. {func}`~libvt.tmux.decode_tmux_capture`, {meth}`~libvt.terminal.Terminal.from_tmux_capture`, and -{meth}`~libvt.terminal.Snapshot.from_tmux_capture` accept `trim_trailing=True` +{meth}`~libvt.snapshot.Snapshot.from_tmux_capture` accept `trim_trailing=True` to preserve explicit trailing spaces and disambiguate `GRID_FLAG_PADDING` wide-wrap spacers in a single pass. @@ -967,7 +977,7 @@ subparameters while restricting {func}`~libvt.parser.parse_sgr` colons to well-formed `4`/`38`/`48`/`58` groups, and flushes incomplete multi-byte UTF-8 sequences on `0x7F` (`DEL`) in {class}`~libvt.parser.Parser`. `DECSLRM` partial scrolls preserve wide glyphs wholly inside `[left, right]`, and -{class}`~libvt.terminal.Formatter` restores `IRM`, `DECOM`, `DECLRMM`, and +{class}`~libvt.format.Formatter` restores `IRM`, `DECOM`, `DECLRMM`, and `DECSCUSR` after rendering cells while padding `wrapped=True` rows to `cols`. {class}`~libvt.config.Profile` splits {data}`~libvt.config.DEFAULT_PROFILE` and {data}`~libvt.profiles.XTERM_PROFILE` (VT510 `DECSTR` mode set, shared primary @@ -1011,7 +1021,7 @@ in {mod}`libvt.events` under {attr}`~libvt.config.Limits.max_event_bytes`. {meth}`~libvt.terminal.Terminal.changes_since` isolate row-mutation watermarks per {class}`~libvt.terminal.Terminal` instance and report every cell, soft-wrap, and direct {attr}`~libvt.terminal.Terminal.screen` mutation in -{attr}`~libvt.terminal.ScreenDelta.dirty_rows`, while `ICH` and `DCH` outside +{attr}`~libvt.snapshot.ScreenDelta.dirty_rows`, while `ICH` and `DCH` outside `DECLRMM` horizontal margins leave soft-wrapped rows intact. #### Graphics retention, `DECSTBM` `SIXEL` masking, and streaming reflow (#21) @@ -1022,7 +1032,7 @@ margins advance scrollback history. {meth}`~libvt.terminal.Terminal.resize` and {meth}`~libvt.screen.Screen.resize` retain stored images and placements across reflow and non-reflow resizes, stream unwrapped scrollback lines that fit within `cols` in `O(1)` per row without reallocating history blocks, -preserve monotonic {attr}`~libvt.terminal.Snapshot.scrolled_total` +preserve monotonic {attr}`~libvt.snapshot.Snapshot.scrolled_total` continuity, and remap {class}`~libvt.events.PromptZone` and cell-anchored Kitty {class}`~libvt.graphics.ImagePlacement` `(abs_row, col)` pins. @@ -1047,7 +1057,7 @@ terminal emulator, streaming VT500 byte parser, mode-aware input encoder, #### Sans-I/O terminal core, two-tier RLE grid, and Unicode 17 width (#2) {class}`~libvt.terminal.Terminal`, {class}`~libvt.screen.Screen`, and -{class}`~libvt.terminal.Snapshot` emulate primary and `?1049` alternate +{class}`~libvt.snapshot.Snapshot` emulate primary and `?1049` alternate screens with zero-based `(row, col)` coordinates, lazy 64-bit inline viewport attributes, run-length-encoded scrollback history, and primary-screen soft-wrap resize reflow. Top-level @@ -1075,7 +1085,7 @@ emoji variation sequences. See {doc}`topics/architecture` for details. {meth}`~libvt.terminal.Terminal.expire_synchronized_output` provide lazy copy-on-write frame holds and generation-tagged timeout recovery for DEC mode `?2026` synchronized updates. -{class}`~libvt.terminal.Formatter` exports snapshots to plain text, VT +{class}`~libvt.format.Formatter` exports snapshots to plain text, VT escape sequences, and span-coalesced HTML with URI scheme allowlisting. {class}`~libvt.status.ProgramStatusStore` and @@ -1111,23 +1121,23 @@ protocol-typed `vt_terminal`, `vt_factory`, `vt_parser`, `vt_recorder`, and `vt_pty` fixtures alongside {func}`~libvt.testing.assert_screen`, {func}`~libvt.testing.assert_screen_box`, {exc}`~libvt.exc.TerminalTimeoutError` stream diagnostics, and -{class}`~libvt.terminal.FlightRecorder` ring buffers. See +{class}`~libvt.recorder.FlightRecorder` ring buffers. See {doc}`topics/sync-and-asyncio` for details. #### Incremental sync deltas, `tmux` capture reconstruction, and graphics (#13–#20) {meth}`~libvt.terminal.Terminal.sync_token` and {meth}`~libvt.terminal.Terminal.changes_since` emit non-destructive -multi-consumer {class}`~libvt.terminal.ScreenDelta` updates across both +multi-consumer {class}`~libvt.snapshot.ScreenDelta` updates across both `"committed"` (`?2026`-held) and `"working"` views, paired with -{meth}`~libvt.terminal.ScreenDelta.apply_lines`, -{meth}`~libvt.terminal.ScreenDelta.apply_rows`, and `O(1)` copy-on-write -{attr}`~libvt.terminal.Snapshot.history` sequence views. +{meth}`~libvt.snapshot.ScreenDelta.apply_lines`, +{meth}`~libvt.snapshot.ScreenDelta.apply_rows`, and `O(1)` copy-on-write +{attr}`~libvt.snapshot.Snapshot.history` sequence views. {func}`~libvt.tmux.decode_tmux_capture`, {class}`~libvt.tmux.TmuxPaneMetadata`, and {func}`~libvt.tmux.unescape_tmux_control_output` reconstruct live -{class}`~libvt.terminal.Terminal` and {class}`~libvt.terminal.Snapshot` +{class}`~libvt.terminal.Terminal` and {class}`~libvt.snapshot.Snapshot` state from `tmux capture-pane` (handling bare `SO`/`SI` ACS borders, `GRID_FLAG_TAB` tabstops, `-F` / `-J` soft wraps, phantom-column `pending_wrap`, and `-a` saved primary screens). @@ -1136,8 +1146,8 @@ image metadata ({class}`~libvt.graphics.ImageMeta`) and monotonic `abs_row` grid placements ({class}`~libvt.graphics.ImagePlacement` and {meth}`~libvt.graphics.ImagePlacement.occupies_abs`) resolved alongside {class}`~libvt.events.PromptZone` anchors via -{meth}`~libvt.terminal.Snapshot.at_abs` and -{meth}`~libvt.terminal.Snapshot.viewport_row`. +{meth}`~libvt.snapshot.Snapshot.at_abs` and +{meth}`~libvt.snapshot.Snapshot.viewport_row`. {exc}`~libvt.exc.TerminalTimeoutError` attaches multi-line viewport and flight-recorder diagnostics via PEP 678 `__notes__` while keeping `str(exc)` single-line. diff --git a/MIGRATION b/MIGRATION index 23e1f2bb..57769019 100644 --- a/MIGRATION +++ b/MIGRATION @@ -44,8 +44,8 @@ the next character matters. ### VT snapshot output retains the terminal pen -{meth}`~libvt.terminal.Snapshot.format` with -{attr}`~libvt.terminal.OutputFormat.VT` ends with the captured pen and +{meth}`~libvt.snapshot.Snapshot.format` with +{attr}`~libvt.format.OutputFormat.VT` ends with the captured pen and cursor state. When appending unrelated text, set its cursor position and rendition before writing. Close a captured OSC 8 hyperlink with `OSC 8 ; ; ST` and reset SGR and DECSCA with `CSI 0 m` and `CSI 0 " q`. @@ -175,7 +175,7 @@ regenerate affected `.ambr` expectations with `pytest --snapshot-update`. {meth}`~libvt.aio.AsyncTerminalStream.wait_for` and {meth}`~libvt.aio.PtySession.wait_for` match strings against -{attr}`~libvt.terminal.Snapshot.unwrapped_text`. Replace a string that includes +{attr}`~libvt.snapshot.Snapshot.unwrapped_text`. Replace a string that includes a soft-wrap boundary with a callable that inspects the physical rows. ```python @@ -191,11 +191,11 @@ await session.wait_for(lambda snap: "hello wo\nrld" in snap.text) ### Curated PEP 562 `libvt` root exports (#43) Top-level {mod}`libvt` now exports only {class}`~libvt.style.Appearance`, -{class}`~libvt.screen.Cell`, {class}`~libvt.events.Event`, +{class}`~libvt.views.Cell`, {class}`~libvt.events.Event`, {exc}`~libvt.exc.LibVtError`, {class}`~libvt.config.Limits`, {class}`~libvt.config.Policy`, {class}`~libvt.config.Profile`, {exc}`~libvt.exc.ProtocolError`, {class}`~libvt.screen.Screen`, -{class}`~libvt.terminal.Snapshot`, {class}`~libvt.style.Style`, +{class}`~libvt.snapshot.Snapshot`, {class}`~libvt.style.Style`, {class}`~libvt.terminal.Terminal`, `__version__`, {func}`~libvt.terminal.render`, and {func}`~libvt.terminal.strip` via lazy PEP 562 attribute lookup. Import modes, styles, events, parsers, input encoders, and @@ -241,7 +241,7 @@ pol = Policy(clipboard_read=ClipboardReadPolicy.IGNORE) live in decoupled {mod}`libvt.contrib.tmux.profile`, {mod}`libvt.contrib.tmux.capture`, and {mod}`libvt.contrib.tmux.control` submodules (re-exported lazily on {mod}`libvt.contrib.tmux`), and core -{class}`~libvt.terminal.Terminal` / {class}`~libvt.terminal.Snapshot` no longer +{class}`~libvt.terminal.Terminal` / {class}`~libvt.snapshot.Snapshot` no longer carry `from_tmux_capture` constructors: ```python @@ -361,11 +361,11 @@ cap_term = Terminal.from_tmux_capture(["\x1b[5:3moverline\x1b[0m"]) ### Opaque `SyncToken` watermarks (#22) -{class}`~libvt.terminal.SyncToken` no longer exposes internal watermark fields +{class}`~libvt.snapshot.SyncToken` no longer exposes internal watermark fields or direct construction; obtain tokens from {meth}`~libvt.terminal.Terminal.sync_token` or -{attr}`~libvt.terminal.ScreenDelta.token` and inspect terminal state via -{attr}`~libvt.terminal.ScreenDelta.snapshot`: +{attr}`~libvt.snapshot.ScreenDelta.token` and inspect terminal state via +{attr}`~libvt.snapshot.ScreenDelta.snapshot`: ```python # Before diff --git a/README.md b/README.md index 3c1300fc..af46dc13 100644 --- a/README.md +++ b/README.md @@ -206,7 +206,7 @@ styles: - Run terminal programs on POSIX PTYs or connect to `asyncio` streams. Read `tmux` captures as screen cells and decode control-mode output with -[`libvt.contrib.tmux`](https://libvt.git-pull.com/api/contrib_tmux/). Full +[`libvt.contrib.tmux`](https://libvt.git-pull.com/api/contrib/tmux/). Full guides and API reference are at [libvt.git-pull.com](https://libvt.git-pull.com/). ## License @@ -215,11 +215,11 @@ MIT License. See [LICENSE](LICENSE). [feed]: https://libvt.git-pull.com/api/terminal/#libvt.terminal.Terminal.feed [committed]: https://libvt.git-pull.com/api/terminal/#libvt.terminal.Terminal.committed -[viewport]: https://libvt.git-pull.com/api/terminal/#libvt.terminal.Snapshot.viewport +[viewport]: https://libvt.git-pull.com/api/snapshot/#libvt.snapshot.Snapshot.viewport [assert_screen_box]: https://libvt.git-pull.com/api/testing/#libvt.testing.assert_screen_box -[contrib_syrupy]: https://libvt.git-pull.com/api/contrib_syrupy/ +[contrib_syrupy]: https://libvt.git-pull.com/api/contrib/syrupy/ [pytest_plugin]: https://libvt.git-pull.com/api/pytest_plugin/ -[vt_snapshot]: https://libvt.git-pull.com/api/contrib_syrupy/#libvt.contrib.syrupy.vt_snapshot +[vt_snapshot]: https://libvt.git-pull.com/api/contrib/syrupy/#libvt.contrib.syrupy.vt_snapshot [vt_screen]: https://libvt.git-pull.com/api/testing/#libvt.testing.vt_screen [serialize_vt_snapshot]: https://libvt.git-pull.com/api/testing/#libvt.testing.serialize_vt_snapshot [render]: https://libvt.git-pull.com/api/terminal/#libvt.terminal.render diff --git a/docs/api/aio.md b/docs/api/aio.md deleted file mode 100644 index 0fe6fc1f..00000000 --- a/docs/api/aio.md +++ /dev/null @@ -1,14 +0,0 @@ -# `libvt.aio` - -```{eval-rst} -.. automodule:: libvt.aio - :members: - :inherited-members: - :no-show-inheritance: - :no-private-members: - -.. py:type:: TtyMode - :canonical: typing.Literal["cooked", "cbreak", "raw"] - - Slave pseudo-terminal line discipline mode passed to :func:`open_pty`. -``` diff --git a/docs/api/aio/core.md b/docs/api/aio/core.md new file mode 100644 index 00000000..d8127d19 --- /dev/null +++ b/docs/api/aio/core.md @@ -0,0 +1,21 @@ +# `libvt.aio` — Session Core + +Shared session protocol, reply writer protocol, and PTY line discipline type +exported from {mod}`libvt.aio`. + +```{eval-rst} +.. py:currentmodule:: libvt.aio + +.. autoclass:: AsyncSession + :members: + :no-show-inheritance: + +.. autoclass:: ReplyWriter + :members: + :no-show-inheritance: + +.. py:type:: TtyMode + :canonical: typing.Literal["cooked", "cbreak", "raw"] + + Slave pseudo-terminal line discipline mode passed to :func:`open_pty`. +``` diff --git a/docs/api/aio/index.md b/docs/api/aio/index.md new file mode 100644 index 00000000..470f3b54 --- /dev/null +++ b/docs/api/aio/index.md @@ -0,0 +1,42 @@ +# `libvt.aio` + +`asyncio` stream and POSIX PTY adapters over {class}`~libvt.terminal.Terminal`. + +::::{grid} 1 1 3 3 +:gutter: 2 + +:::{grid-item-card} Session Core +:link: core +:link-type: doc +{class}`~libvt.aio.AsyncSession`, {class}`~libvt.aio.ReplyWriter`, and +{obj}`~libvt.aio.TtyMode`. +::: + +:::{grid-item-card} Async Stream +:link: stream +:link-type: doc +{class}`~libvt.aio.AsyncTerminalStream` for `asyncio` stream transports. +::: + +:::{grid-item-card} POSIX PTY +:link: pty +:link-type: doc +{func}`~libvt.aio.open_pty` and {class}`~libvt.aio.PtySession` for child +processes in a pseudo-terminal. +::: + +:::: + +```{eval-rst} +.. automodule:: libvt.aio + :no-members: +``` + +```{toctree} +:hidden: +:maxdepth: 1 + +core +stream +pty +``` diff --git a/docs/api/aio/pty.md b/docs/api/aio/pty.md new file mode 100644 index 00000000..72aa63f5 --- /dev/null +++ b/docs/api/aio/pty.md @@ -0,0 +1,14 @@ +# `libvt.aio` — POSIX PTY + +POSIX pseudo-terminal subprocess adapter exported from {mod}`libvt.aio`. + +```{eval-rst} +.. py:currentmodule:: libvt.aio + +.. autoclass:: PtySession + :members: + :inherited-members: + :no-show-inheritance: + +.. autofunction:: open_pty +``` diff --git a/docs/api/aio/stream.md b/docs/api/aio/stream.md new file mode 100644 index 00000000..9d6d00c8 --- /dev/null +++ b/docs/api/aio/stream.md @@ -0,0 +1,12 @@ +# `libvt.aio` — Async Stream + +`asyncio` stream transport adapter exported from {mod}`libvt.aio`. + +```{eval-rst} +.. py:currentmodule:: libvt.aio + +.. autoclass:: AsyncTerminalStream + :members: + :inherited-members: + :no-show-inheritance: +``` diff --git a/docs/api/contrib/index.md b/docs/api/contrib/index.md new file mode 100644 index 00000000..10ab0f4f --- /dev/null +++ b/docs/api/contrib/index.md @@ -0,0 +1,34 @@ +# `libvt.contrib` + +Optional ecosystem integrations kept separate from the zero-dependency VT core. + +::::{grid} 1 1 2 2 +:gutter: 2 + +:::{grid-item-card} `libvt.contrib.tmux` +:link: tmux/index +:link-type: doc +Decoupled `tmux` profiles, `capture-pane` decoders, multi-pane window +compositing, and `-C` / `-CC` control-mode synchronization. +::: + +:::{grid-item-card} `libvt.contrib.syrupy` +:link: syrupy +:link-type: doc +Optional `syrupy` `.ambr` golden adapter and conditional `vt_snapshot` +fixture (`libvt[syrupy]`). +::: + +:::: + +```{eval-rst} +.. py:module:: libvt.contrib +``` + +```{toctree} +:hidden: +:maxdepth: 2 + +tmux/index +syrupy +``` diff --git a/docs/api/contrib_syrupy.md b/docs/api/contrib/syrupy.md similarity index 97% rename from docs/api/contrib_syrupy.md rename to docs/api/contrib/syrupy.md index f97c529f..0b177574 100644 --- a/docs/api/contrib_syrupy.md +++ b/docs/api/contrib/syrupy.md @@ -28,7 +28,7 @@ uninstalled or disabled via `-p no:syrupy`): >>> test_tui_banner(_VerifyAmbr()) # doctest: +HIDE ``` -See {doc}`../topics/testing` for using +See {doc}`../../topics/testing` for using {func}`~libvt.testing.serialize_vt_snapshot` and {func}`~libvt.testing.vt_screen` without `syrupy`, or sharing row scrubbers with {meth}`VtSnapshotExtension.configure `. diff --git a/docs/api/contrib/tmux/capture.md b/docs/api/contrib/tmux/capture.md new file mode 100644 index 00000000..56485f7f --- /dev/null +++ b/docs/api/contrib/tmux/capture.md @@ -0,0 +1,65 @@ +# `libvt.contrib.tmux.capture` + +Use {func}`~libvt.contrib.tmux.capture.build_tmux_capture_command` to +capture the pane's written extent and trailing styles together on tmux 3.4 +and later. For raw captures, use the same pane, line range and line flags +with `capture-pane -e -p -N -T` and `capture-pane -e -p -N`. + +```python +>>> from libvt.contrib.tmux import decode_tmux_capture +>>> capture = decode_tmux_capture( +... b"\n", +... rows=1, cols=3, trim_trailing=True, +... untrimmed_capture=b"\x1b[41m \n", +... ) +>>> capture.snapshot.lines +('',) +>>> capture.snapshot[0, 2].style.bg.name +'RED' +>>> capture.completeness.exact_cells +True +``` + +An older tmux can return the same trailing spaces for a written blank row +and an erased row. The decoder retains the available styles, and reports +`trailing_cells` in `completeness.unexposed_fields` when it cannot establish +which spaces were written. A `-T` capture without its untrimmed companion +likewise reports uncertainty when a row stops short of the pane width. + +Preserve empty physical rows when passing a sequence of lines. A capture +with missing viewport, requested history, or requested saved-primary rows +reports `capture_rows` and clears `exact_cells` and `exact_wraps`. The +generation bracket reports the metadata comparison independently. + +## Continue after a capture + +{attr}`~libvt.contrib.tmux.capture.CaptureCompleteness.exact_cells` +describes the captured frame. Later input can depend on earlier bytes. +{attr}`~libvt.contrib.tmux.capture.CaptureCompleteness.unexposed_fields` +reports state outside the capture's visible cells. + +- `preceding_graphic` is the glyph that a following REP (`CSI Ps b`) repeats. + A cursor movement can clear it without changing the visible cells. +- `grapheme_continuation` is the state used to join a following combining + mark or emoji component to the preceding glyph. +- `utf8_prefix` is an incomplete UTF-8 code point at the checkpoint. + +{class}`~libvt.contrib.tmux.control.TmuxPaneSync` feeds the pending escape +bytes tmux returns through `capture-pane -P -C`. The native command can +return an empty prefix while the UTF-8 decoder still has buffered bytes. +Resume from a known input boundary when continuation must be exact. A +redraw that supplies complete encoded text and establishes its own first +graphic can serve as that checkpoint. + +```{eval-rst} +.. automodule:: libvt.contrib.tmux.capture + :members: + :no-private-members: + :exclude-members: CaptureInput + +.. py:type:: CaptureInput + :module: libvt.contrib.tmux.capture + :canonical: str | bytes | bytearray | collections.abc.Sequence[str] + + Accepted input representation for ``tmux capture-pane`` lines or raw text. +``` diff --git a/docs/api/contrib/tmux/control.md b/docs/api/contrib/tmux/control.md new file mode 100644 index 00000000..3fa0896f --- /dev/null +++ b/docs/api/contrib/tmux/control.md @@ -0,0 +1,56 @@ +# `libvt.contrib.tmux.control` + +A pane size change starts the same native refresh as +{meth}`~libvt.contrib.tmux.control.TmuxPaneSync.resync`. Send the commands +returned by {meth}`~libvt.contrib.tmux.control.TmuxPaneSync.handle_event` and +wait for `LIVE` before reading the new dimensions. The terminal keeps its +last frame until the new capture installs. + +(tmux-row-bookmarks)= + +## Keep a scrollback bookmark across updates + +Store an absolute row with a {class}`~libvt.snapshot.SyncToken` from the +same terminal. A native refresh retains the current visible rows and the +requested history that tmux still holds. Once tmux has evicted earlier +history, the capture cannot recover the previous absolute origin. The +same row number may resolve to different text after a refresh. + +```python +>>> from libvt import Terminal +>>> from libvt.terminal import ResyncReason, SyncToken +>>> def bookmarked_text(term: Terminal, token: SyncToken, row: int) -> str | None: +... delta = term.changes_since(token) +... expired = (ResyncReason.EPOCH_CHANGED, ResyncReason.TERMINAL_MISMATCH) +... if delta.resync_reason in expired or delta.snapshot.active_is_alt: +... return None +... try: +... return delta.snapshot.at_abs(row).text +... except IndexError: +... return None +>>> term = Terminal(rows=2, cols=8, scrollback=3) +>>> term.feed(b"r0\r\nr1\r\nr2") +>>> bookmark = (term.sync_token(), term.committed.scrolled_total + 1) +>>> bookmarked_text(term, *bookmark) +'r2' +>>> term.resize(rows=2, cols=10) +>>> bookmarked_text(term, *bookmark) is None +True +``` + +Use the same check with `sync.terminal` after a native tmux refresh. +An immutable snapshot retained with the bookmark still resolves rows in +its original frame. + +```{eval-rst} +.. automodule:: libvt.contrib.tmux.control + :members: + :no-private-members: + :exclude-members: TmuxControlEvent + +.. py:type:: TmuxControlEvent + :module: libvt.contrib.tmux.control + :canonical: TmuxCommandBlock | TmuxOutput | TmuxExtendedOutput | TmuxPause | TmuxContinue | TmuxLayoutChange | TmuxSubscriptionChanged | TmuxExit | TmuxNotification + + Union of typed events emitted by :meth:`~libvt.contrib.tmux.control.TmuxControlParser.feed`. +``` diff --git a/docs/api/contrib/tmux/index.md b/docs/api/contrib/tmux/index.md new file mode 100644 index 00000000..d2d28da5 --- /dev/null +++ b/docs/api/contrib/tmux/index.md @@ -0,0 +1,50 @@ +# `libvt.contrib.tmux` + +Decoupled `tmux` integration submodules for host profiles, one-shot +`capture-pane` decoding, multi-pane window compositing, and live `-C` / `-CC` +control-mode synchronization. + +::::{grid} 1 1 2 2 +:gutter: 2 + +:::{grid-item-card} `libvt.contrib.tmux.profile` +:link: profile +:link-type: doc +Host capability profiles for inner `tmux` panes across tmux versions. +::: + +:::{grid-item-card} `libvt.contrib.tmux.capture` +:link: capture +:link-type: doc +One-shot `capture-pane` command builder, ANSI decoder, and completeness +reporting. +::: + +:::{grid-item-card} `libvt.contrib.tmux.window` +:link: window +:link-type: doc +Multi-pane window layout parsing and composited viewport capture. +::: + +:::{grid-item-card} `libvt.contrib.tmux.control` +:link: control +:link-type: doc +Streaming `tmux -C` / `-CC` control-mode parser and live pane synchronizer. +::: + +:::: + +```{eval-rst} +.. automodule:: libvt.contrib.tmux + :no-members: +``` + +```{toctree} +:hidden: +:maxdepth: 1 + +profile +capture +window +control +``` diff --git a/docs/api/contrib/tmux/profile.md b/docs/api/contrib/tmux/profile.md new file mode 100644 index 00000000..faf1df25 --- /dev/null +++ b/docs/api/contrib/tmux/profile.md @@ -0,0 +1,7 @@ +# `libvt.contrib.tmux.profile` + +```{eval-rst} +.. automodule:: libvt.contrib.tmux.profile + :members: + :no-private-members: +``` diff --git a/docs/api/contrib/tmux/window.md b/docs/api/contrib/tmux/window.md new file mode 100644 index 00000000..9c79d51a --- /dev/null +++ b/docs/api/contrib/tmux/window.md @@ -0,0 +1,14 @@ +# `libvt.contrib.tmux.window` + +```{eval-rst} +.. automodule:: libvt.contrib.tmux.window + :members: + :no-private-members: + :exclude-members: TmuxPaneSource + +.. py:type:: TmuxPaneSource + :module: libvt.contrib.tmux.window + :canonical: Snapshot | Screen | Terminal | TmuxCaptureResult | object + + Accepted per-pane state source for :func:`~libvt.contrib.tmux.window.composite_tmux_window`. +``` diff --git a/docs/api/contrib_tmux.md b/docs/api/contrib_tmux.md deleted file mode 100644 index 0d820df5..00000000 --- a/docs/api/contrib_tmux.md +++ /dev/null @@ -1,154 +0,0 @@ -# `libvt.contrib.tmux` - -```{eval-rst} -.. py:module:: libvt.contrib - -.. automodule:: libvt.contrib.tmux - :no-members: -``` - -## `libvt.contrib.tmux.profile` - -```{eval-rst} -.. automodule:: libvt.contrib.tmux.profile - :members: - :no-private-members: -``` - -## `libvt.contrib.tmux.capture` - -Use {func}`~libvt.contrib.tmux.capture.build_tmux_capture_command` to -capture the pane's written extent and trailing styles together on tmux 3.4 -and later. For raw captures, use the same pane, line range and line flags -with `capture-pane -e -p -N -T` and `capture-pane -e -p -N`. - -```python ->>> from libvt.contrib.tmux import decode_tmux_capture ->>> capture = decode_tmux_capture( -... b"\n", -... rows=1, cols=3, trim_trailing=True, -... untrimmed_capture=b"\x1b[41m \n", -... ) ->>> capture.snapshot.lines -('',) ->>> capture.snapshot[0, 2].style.bg.name -'RED' ->>> capture.completeness.exact_cells -True -``` - -An older tmux can return the same trailing spaces for a written blank row -and an erased row. The decoder retains the available styles, and reports -`trailing_cells` in `completeness.unexposed_fields` when it cannot establish -which spaces were written. A `-T` capture without its untrimmed companion -likewise reports uncertainty when a row stops short of the pane width. - -Preserve empty physical rows when passing a sequence of lines. A capture -with missing viewport, requested history, or requested saved-primary rows -reports `capture_rows` and clears `exact_cells` and `exact_wraps`. The -generation bracket reports the metadata comparison independently. - -### Continue after a capture - -{attr}`~libvt.contrib.tmux.capture.CaptureCompleteness.exact_cells` -describes the captured frame. Later input can depend on earlier bytes. -{attr}`~libvt.contrib.tmux.capture.CaptureCompleteness.unexposed_fields` -reports state outside the capture's visible cells. - -- `preceding_graphic` is the glyph that a following REP (`CSI Ps b`) repeats. - A cursor movement can clear it without changing the visible cells. -- `grapheme_continuation` is the state used to join a following combining - mark or emoji component to the preceding glyph. -- `utf8_prefix` is an incomplete UTF-8 code point at the checkpoint. - -{class}`~libvt.contrib.tmux.control.TmuxPaneSync` feeds the pending escape -bytes tmux returns through `capture-pane -P -C`. The native command can -return an empty prefix while the UTF-8 decoder still has buffered bytes. -Resume from a known input boundary when continuation must be exact. A -redraw that supplies complete encoded text and establishes its own first -graphic can serve as that checkpoint. - -```{eval-rst} -.. automodule:: libvt.contrib.tmux.capture - :members: - :no-private-members: - :exclude-members: CaptureInput - -.. py:type:: CaptureInput - :module: libvt.contrib.tmux.capture - :canonical: str | bytes | bytearray | collections.abc.Sequence[str] - - Accepted input representation for ``tmux capture-pane`` lines or raw text. -``` - -## `libvt.contrib.tmux.window` - -```{eval-rst} -.. automodule:: libvt.contrib.tmux.window - :members: - :no-private-members: - :exclude-members: TmuxPaneSource - -.. py:type:: TmuxPaneSource - :module: libvt.contrib.tmux.window - :canonical: Snapshot | Screen | Terminal | TmuxCaptureResult | object - - Accepted per-pane state source for :func:`~libvt.contrib.tmux.window.composite_tmux_window`. -``` - -## `libvt.contrib.tmux.control` - -A pane size change starts the same native refresh as -{meth}`~libvt.contrib.tmux.control.TmuxPaneSync.resync`. Send the commands -returned by {meth}`~libvt.contrib.tmux.control.TmuxPaneSync.handle_event` and -wait for `LIVE` before reading the new dimensions. The terminal keeps its -last frame until the new capture installs. - -(tmux-row-bookmarks)= - -### Keep a scrollback bookmark across updates - -Store an absolute row with a {class}`~libvt.terminal.SyncToken` from the -same terminal. A native refresh retains the current visible rows and the -requested history that tmux still holds. Once tmux has evicted earlier -history, the capture cannot recover the previous absolute origin. The -same row number may resolve to different text after a refresh. - -```python ->>> from libvt import Terminal ->>> from libvt.terminal import ResyncReason, SyncToken ->>> def bookmarked_text(term: Terminal, token: SyncToken, row: int) -> str | None: -... delta = term.changes_since(token) -... expired = (ResyncReason.EPOCH_CHANGED, ResyncReason.TERMINAL_MISMATCH) -... if delta.resync_reason in expired or delta.snapshot.active_is_alt: -... return None -... try: -... return delta.snapshot.at_abs(row).text -... except IndexError: -... return None ->>> term = Terminal(rows=2, cols=8, scrollback=3) ->>> term.feed(b"r0\r\nr1\r\nr2") ->>> bookmark = (term.sync_token(), term.committed.scrolled_total + 1) ->>> bookmarked_text(term, *bookmark) -'r2' ->>> term.resize(rows=2, cols=10) ->>> bookmarked_text(term, *bookmark) is None -True -``` - -Use the same check with `sync.terminal` after a native tmux refresh. -An immutable snapshot retained with the bookmark still resolves rows in -its original frame. - -```{eval-rst} -.. automodule:: libvt.contrib.tmux.control - :members: - :no-private-members: - :exclude-members: TmuxControlEvent - -.. py:type:: TmuxControlEvent - :module: libvt.contrib.tmux.control - :canonical: TmuxCommandBlock | TmuxOutput | TmuxExtendedOutput | TmuxPause | TmuxContinue | TmuxLayoutChange | TmuxSubscriptionChanged | TmuxExit | TmuxNotification - - Union of typed events emitted by :meth:`~libvt.contrib.tmux.control.TmuxControlParser.feed`. -``` diff --git a/docs/api/format.md b/docs/api/format.md new file mode 100644 index 00000000..9a6a5ca4 --- /dev/null +++ b/docs/api/format.md @@ -0,0 +1,7 @@ +# `libvt.format` + +```{eval-rst} +.. automodule:: libvt.format + :members: + :no-private-members: +``` diff --git a/docs/api/index.md b/docs/api/index.md index 365b7b91..ffb8f192 100644 --- a/docs/api/index.md +++ b/docs/api/index.md @@ -19,15 +19,22 @@ core types. :::{grid-item-card} `libvt.terminal` :link: terminal :link-type: doc -`Terminal`, `Snapshot`, `Formatter`, `FlightRecorder`, `render`, and `strip`. +`Terminal`, `StopOn`, `StepResult`, `render`, and `strip`. ::: -:::{grid-item-card} `libvt.screen` +:::{grid-item-card} `libvt.screen` & `libvt.views` :link: screen :link-type: doc `Screen`, `ScreenSet`, `Cell`, `RowView`, `RowRun`, `RegionView`, and `Cursor`. ::: +:::{grid-item-card} `libvt.snapshot`, `format`, & `recorder` +:link: snapshot +:link-type: doc +`Snapshot`, `SyncToken`, `ScreenDelta`, `Formatter`, `TerminalRecorder`, and +`FlightRecorder`. +::: + :::{grid-item-card} `libvt.parser` :link: parser :link-type: doc @@ -54,9 +61,9 @@ Mode-aware `KeyEvent`, `MouseEvent`, `PasteEvent`, and VT sequence `explain`. ::: :::{grid-item-card} `libvt.aio` -:link: aio +:link: aio/index :link-type: doc -`AsyncTerminalStream` and POSIX `open_pty` subprocess sessions. +`AsyncSession`, `AsyncTerminalStream`, and POSIX `open_pty` / `PtySession`. ::: :::{grid-item-card} `libvt.testing` @@ -80,14 +87,13 @@ Import-light `vt_terminal`, `vt_factory`, `vt_recorder`, `vt_parser`, and ::: :::{grid-item-card} `libvt.contrib.tmux` -:link: contrib_tmux +:link: contrib/tmux/index :link-type: doc -Decoupled `tmux_profile`, `decode_tmux_capture`, `TmuxControlParser`, and -`TmuxPaneSync` submodules. +Decoupled `tmux` `profile`, `capture`, `window`, and `control` submodules. ::: :::{grid-item-card} `libvt.contrib.syrupy` -:link: contrib_syrupy +:link: contrib/syrupy :link-type: doc Optional `syrupy` `VtSnapshotExtension` and conditional `vt_snapshot` fixture for `.ambr` golden files (`libvt[syrupy]`). @@ -127,6 +133,10 @@ Active deprecations and migration guidance. libvt terminal screen +views +snapshot +format +recorder parser style modes @@ -137,9 +147,8 @@ status input codec graphics -contrib_tmux -contrib_syrupy -aio +aio/index +contrib/index testing pytest_plugin exc diff --git a/docs/api/pytest_plugin.md b/docs/api/pytest_plugin.md index bb17bce5..76aab60e 100644 --- a/docs/api/pytest_plugin.md +++ b/docs/api/pytest_plugin.md @@ -36,7 +36,7 @@ automatically. `libvt`'s own `conftest.py` also seeds these fixtures in ## Which fixture to request - Request {fixture}`vt_terminal` when a standard `24x80` terminal with an - attached {class}`~libvt.terminal.FlightRecorder` fits the test. + attached {class}`~libvt.recorder.FlightRecorder` fits the test. - Request {fixture}`vt_factory` when the test chooses custom `(rows, cols)`, scrollback limits, or terminal profiles. - Request {fixture}`vt_recorder` when sharing or inspecting the 4 KiB @@ -52,7 +52,7 @@ automatically. `libvt`'s own `conftest.py` also seeds these fixtures in | --- | --- | --- | | {fixture}`vt_terminal` | function | `24x80` {class}`~libvt.terminal.Terminal` wired to {fixture}`vt_recorder` | | {fixture}`vt_factory` | function | {class}`~libvt.pytest_plugin.TerminalFactory` for custom geometry or profiles | -| {fixture}`vt_recorder` | function | 4 KiB {class}`~libvt.terminal.FlightRecorder` ring buffer | +| {fixture}`vt_recorder` | function | 4 KiB {class}`~libvt.recorder.FlightRecorder` ring buffer | | {fixture}`vt_parser` | function | Streaming {class}`~libvt.parser.Parser` | | {fixture}`vt_pty` | function | POSIX {class}`~libvt.pytest_plugin.PtyFactory` (`win32` skip) | diff --git a/docs/api/recorder.md b/docs/api/recorder.md new file mode 100644 index 00000000..5609d026 --- /dev/null +++ b/docs/api/recorder.md @@ -0,0 +1,7 @@ +# `libvt.recorder` + +```{eval-rst} +.. automodule:: libvt.recorder + :members: + :no-private-members: +``` diff --git a/docs/api/screen.md b/docs/api/screen.md index c6f15692..b575abd6 100644 --- a/docs/api/screen.md +++ b/docs/api/screen.md @@ -1,7 +1,11 @@ # `libvt.screen` +`Screen` and `ScreenSet` grid state. Compatibility re-exports for cell, cursor, +row, and region views live in {mod}`libvt.views`. + ```{eval-rst} .. automodule:: libvt.screen - :members: + :members: Screen, ScreenSet :no-private-members: + :exclude-members: BLANK_CELL, Cell, Cursor, CursorShape, RegionView, RowRun, RowView, ScrollRegion ``` diff --git a/docs/api/snapshot.md b/docs/api/snapshot.md new file mode 100644 index 00000000..610f0013 --- /dev/null +++ b/docs/api/snapshot.md @@ -0,0 +1,15 @@ +# `libvt.snapshot` + +```{eval-rst} +.. automodule:: libvt.snapshot + :members: + :no-private-members: + :exclude-members: SyncView + +.. py:type:: SyncView + :module: libvt.snapshot + :canonical: typing.Literal['working', 'committed'] + + Buffer view selector for :meth:`~libvt.terminal.Terminal.sync_token` and + :meth:`~libvt.terminal.Terminal.changes_since`. +``` diff --git a/docs/api/terminal.md b/docs/api/terminal.md index 9bcee570..ef7a51fa 100644 --- a/docs/api/terminal.md +++ b/docs/api/terminal.md @@ -1,15 +1,12 @@ # `libvt.terminal` +`Terminal`, boundary stepping, and convenience renderers. Compatibility +re-exports live in their owning modules: {mod}`libvt.snapshot`, +{mod}`libvt.format`, and {mod}`libvt.recorder`. + ```{eval-rst} .. automodule:: libvt.terminal - :members: + :members: Terminal, StopOn, StepResult, render, strip :no-private-members: - :exclude-members: _state, SyncView, __new__ - -.. py:type:: SyncView - :module: libvt.terminal - :canonical: typing.Literal['working', 'committed'] - - Buffer view selector for :meth:`Terminal.sync_token` and - :meth:`Terminal.changes_since`. + :exclude-members: _state, __new__, FlightRecorder, Formatter, OutputFormat, ResyncReason, ScreenDelta, Snapshot, SnapshotDict, SyncToken, SyncView, TerminalRecorder ``` diff --git a/docs/api/testing.md b/docs/api/testing.md index 9ba8260b..9617221b 100644 --- a/docs/api/testing.md +++ b/docs/api/testing.md @@ -20,7 +20,7 @@ styles: ``` See {doc}`../topics/snapshots` and {doc}`../topics/testing` for choosing between -immutable {class}`~libvt.terminal.Snapshot` objects, inline +immutable {class}`~libvt.snapshot.Snapshot` objects, inline {func}`~libvt.testing.assert_screen_box` checks, and {func}`~libvt.testing.serialize_vt_snapshot` strings. diff --git a/docs/api/views.md b/docs/api/views.md new file mode 100644 index 00000000..21df10f9 --- /dev/null +++ b/docs/api/views.md @@ -0,0 +1,7 @@ +# `libvt.views` + +```{eval-rst} +.. automodule:: libvt.views + :members: + :no-private-members: +``` diff --git a/docs/project/public-api.md b/docs/project/public-api.md index 24b82b0d..e5085444 100644 --- a/docs/project/public-api.md +++ b/docs/project/public-api.md @@ -6,11 +6,11 @@ Every module documented under [API Reference](../api/index.md) is public API. Top-level {mod}`libvt` resolves a focused quickstart surface lazily via [PEP 562](https://peps.python.org/pep-0562/) -({class}`~libvt.style.Appearance`, {class}`~libvt.screen.Cell`, +({class}`~libvt.style.Appearance`, {class}`~libvt.views.Cell`, {class}`~libvt.events.Event`, {exc}`~libvt.exc.LibVtError`, {class}`~libvt.config.Limits`, {class}`~libvt.config.Policy`, {class}`~libvt.config.Profile`, {exc}`~libvt.exc.ProtocolError`, -{class}`~libvt.screen.Screen`, {class}`~libvt.terminal.Snapshot`, +{class}`~libvt.screen.Screen`, {class}`~libvt.snapshot.Snapshot`, {class}`~libvt.style.Style`, {class}`~libvt.terminal.Terminal`, `__version__`, {func}`~libvt.terminal.render`, and {func}`~libvt.terminal.strip`) so `import libvt` and `pytest11` plugin discovery do not load emulator modules or @@ -22,10 +22,12 @@ Import specialized types and helpers from their owning submodules: policies, resource ceilings, and host terminal presets - {mod}`libvt.events`, {mod}`libvt.modes`, and {mod}`libvt.style` — structured events, ANSI/DEC modes, colors, and hyperlinks -- {mod}`libvt.parser`, {mod}`libvt.screen`, and {mod}`libvt.terminal` — - streaming VT500 parser, screen grid views, incremental - {class}`~libvt.terminal.SyncToken` / {class}`~libvt.terminal.ScreenDelta` - replicas, and {class}`~libvt.terminal.Formatter` +- {mod}`libvt.parser`, {mod}`libvt.screen`, {mod}`libvt.views`, + {mod}`libvt.snapshot`, {mod}`libvt.format`, {mod}`libvt.recorder`, and + {mod}`libvt.terminal` — streaming VT500 parser, screen grids and views, + immutable snapshots and incremental {class}`~libvt.snapshot.SyncToken` / + {class}`~libvt.snapshot.ScreenDelta` replicas, + {class}`~libvt.format.Formatter`, and {class}`~libvt.recorder.TerminalRecorder` - {mod}`libvt.input`, {mod}`libvt.aio`, and {mod}`libvt.codec` — mode-aware input encoders, {class}`~libvt.aio.AsyncSession` transports, and sequence disassembly @@ -37,8 +39,11 @@ Import specialized types and helpers from their owning submodules: - {mod}`libvt.pytest_plugin` — optional `pytest` fixtures (`libvt[pytest]`): {fixture}`vt_terminal`, {fixture}`vt_factory`, {fixture}`vt_recorder`, {fixture}`vt_parser`, and {fixture}`vt_pty` -- {mod}`libvt.contrib.tmux` — decoupled `tmux` inner-pane profiles, - `capture-pane` decoders, and `-C` / `-CC` control-mode parser and pane sync +- {mod}`libvt.contrib.tmux` ({mod}`~libvt.contrib.tmux.profile`, + {mod}`~libvt.contrib.tmux.capture`, {mod}`~libvt.contrib.tmux.window`, + {mod}`~libvt.contrib.tmux.control`) — decoupled `tmux` inner-pane profiles, + `capture-pane` decoders, multi-pane window compositing, and `-C` / `-CC` + control-mode parser and pane sync - {mod}`libvt.contrib.syrupy` — optional `syrupy` `.ambr` adapter (`libvt[syrupy]`): {class}`~libvt.contrib.syrupy.VtSnapshotExtension` and conditional {fixture}`vt_snapshot` `pytest11` fixture diff --git a/docs/quickstart.md b/docs/quickstart.md index d6eb6d72..a291e55f 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -55,12 +55,12 @@ b'\x1b[2;5R' ## Immutable snapshots and scrollback viewports {meth}`term.snapshot() ` captures an immutable -{class}`~libvt.terminal.Snapshot` of the current screen and scrollback, while +{class}`~libvt.snapshot.Snapshot` of the current screen and scrollback, while {attr}`term.committed ` holds the last completed frame while DEC mode `?2026` synchronized output is active. -{meth}`Snapshot.viewport ` pages backward into +{meth}`Snapshot.viewport ` pages backward into scrollback without mutating the terminal, and -{attr}`~libvt.terminal.Snapshot.display_lines` pads rows to full column width: +{attr}`~libvt.snapshot.Snapshot.display_lines` pads rows to full column width: ```python >>> import libvt @@ -158,7 +158,7 @@ styles: ## Pytest plugin (`libvt[pytest]`) {mod}`libvt.pytest_plugin` registers {fixture}`vt_terminal` (pre-wired to a -4 KiB {class}`~libvt.terminal.FlightRecorder`), {fixture}`vt_factory`, +4 KiB {class}`~libvt.recorder.FlightRecorder`), {fixture}`vt_factory`, {fixture}`vt_recorder`, {fixture}`vt_parser`, and POSIX {fixture}`vt_pty`: ```python diff --git a/docs/redirects.txt b/docs/redirects.txt index 6b750663..75554d3e 100644 --- a/docs/redirects.txt +++ b/docs/redirects.txt @@ -1,2 +1,5 @@ -"api/tmux" "api/contrib_tmux" +"api/tmux" "api/contrib/tmux/index" +"api/contrib_tmux" "api/contrib/tmux/index" +"api/contrib_syrupy" "api/contrib/syrupy" +# "api/aio" "api/aio/index" # dirhtml: same output path "topics/testing-and-snapshots" "topics/testing" diff --git a/docs/topics/index.md b/docs/topics/index.md index 8684376d..596eeb7d 100644 --- a/docs/topics/index.md +++ b/docs/topics/index.md @@ -18,7 +18,7 @@ How the parser, screen, terminal, and I/O adapters divide work, plus viewport, s :::{grid-item-card} Snapshots :link: snapshots :link-type: doc -Immutable {class}`~libvt.terminal.Snapshot` captures, {attr}`~libvt.terminal.Terminal.committed` vs {meth}`~libvt.terminal.Terminal.snapshot`, {meth}`~libvt.terminal.Snapshot.viewport` scrollback paging, and {meth}`~libvt.terminal.Snapshot.to_dict`. +Immutable {class}`~libvt.snapshot.Snapshot` captures, {attr}`~libvt.terminal.Terminal.committed` vs {meth}`~libvt.terminal.Terminal.snapshot`, {meth}`~libvt.snapshot.Snapshot.viewport` scrollback paging, and {meth}`~libvt.snapshot.Snapshot.to_dict`. ::: :::{grid-item-card} Testing Terminal Programs diff --git a/docs/topics/migrating-from-pyte.md b/docs/topics/migrating-from-pyte.md index 62aaf0cc..9127b10b 100644 --- a/docs/topics/migrating-from-pyte.md +++ b/docs/topics/migrating-from-pyte.md @@ -7,7 +7,7 @@ baseline) replaces a separate `Stream` + `Screen` pair with a single {class}`libvt.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 ` values, and watermark deltas. +{class}`libvt.Snapshot ` values, and watermark deltas. ## Terminal construction and coordinates @@ -82,16 +82,16 @@ into Latin-1 bytes: ## Cell, style, cursor, and mode inspection -Index `term[row]` for a {class}`~libvt.screen.RowView`, `term[row, col]` for an -immutable {class}`libvt.Cell `, or `term[r1:r2, c1:c2]` for a -{class}`~libvt.screen.RegionView`. Each `Cell` exposes `.text` (full grapheme +Index `term[row]` for a {class}`~libvt.views.RowView`, `term[row, col]` for an +immutable {class}`libvt.Cell `, or `term[r1:r2, c1:c2]` for a +{class}`~libvt.views.RegionView`. Each `Cell` exposes `.text` (full grapheme cluster, `""` on spacer cells), `.style` ({class}`libvt.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 ` -({class}`~libvt.screen.Cursor`) and enabled modes via +({class}`~libvt.views.Cursor`) and enabled modes via {attr}`Terminal.modes ` ({meth}`ModeState.is_set ` with {class}`~libvt.modes.Mode`): @@ -116,10 +116,10 @@ False `pyte.Screen.display` returns every row padded to the terminal width in columns. Use {attr}`Terminal.display_lines ` (also available on -{attr}`Snapshot.display_lines `, +{attr}`Snapshot.display_lines `, {attr}`Screen.display_lines `, -{attr}`RegionView.display_lines `, and -per-row {attr}`RowView.display_text `) when +{attr}`RegionView.display_lines `, and +per-row {attr}`RowView.display_text `) when callers expect rectangular space-padded lines; use {attr}`Terminal.lines ` for right-trimmed rows or {attr}`Terminal.text ` to omit trailing blank @@ -154,7 +154,7 @@ slice width in terminal columns: 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 ` with a non-negative +{meth}`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 @@ -182,14 +182,14 @@ leave existing snapshots and views unchanged: ## Dirty-row tracking through deltas Instead of clearing a mutable `screen.dirty` set, record a -{class}`~libvt.terminal.SyncToken` with +{class}`~libvt.snapshot.SyncToken` with {meth}`Terminal.sync_token ` and compute a -{class}`~libvt.terminal.ScreenDelta` with -{meth}`Terminal.changes_since `. Check {attr}`ScreenDelta.full_resync ` +{class}`~libvt.snapshot.ScreenDelta` with +{meth}`Terminal.changes_since `. Check {attr}`ScreenDelta.full_resync ` first (triggered on resize, `RIS`, or primary/alternate switches); otherwise -repaint {attr}`ScreenDelta.dirty_rows ` +repaint {attr}`ScreenDelta.dirty_rows ` after applying -{attr}`ScreenDelta.viewport_scroll_up `: +{attr}`ScreenDelta.viewport_scroll_up `: ```python >>> import libvt @@ -281,7 +281,7 @@ Comparison baseline: `pyte 0.8.2`. | 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 ` (`reflow=...`) | Soft-wrapped primary lines reflow by default (`reflow=False` opts out) | -| History paging | `HistoryScreen` mutates `screen.buffer` | {attr}`Terminal.history `, {meth}`Snapshot.viewport ` | Stateless `(rows, cols)` `RegionView` over immutable snapshots | +| History paging | `HistoryScreen` mutates `screen.buffer` | {attr}`Terminal.history `, {meth}`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 | diff --git a/docs/topics/protocols-and-input.md b/docs/topics/protocols-and-input.md index 2bdd746a..d4d16ffc 100644 --- a/docs/topics/protocols-and-input.md +++ b/docs/topics/protocols-and-input.md @@ -96,7 +96,7 @@ observer streams). Notifications (`OSC 0`/`1`/`2` and `ESC k` title, `?2026`, and `DCS tmux;` passthrough) emit typed {class}`~libvt.events.Event` records to `on_event` or {meth}`~libvt.terminal.Terminal.drain_events`, while `OSC 8` hyperlinks attach -to {attr}`Cell.hyperlink `: +to {attr}`Cell.hyperlink `: ```python >>> term = libvt.Terminal(rows=4, cols=20, record_events=True) diff --git a/docs/topics/snapshots.md b/docs/topics/snapshots.md index 79422a71..2fd60c3b 100644 --- a/docs/topics/snapshots.md +++ b/docs/topics/snapshots.md @@ -2,7 +2,7 @@ # Snapshots -{class}`libvt.Snapshot ` freezes a terminal's active +{class}`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 {class}`~libvt.terminal.Terminal` mutates its rows in place on every @@ -109,18 +109,18 @@ frames or raw in-flight buffer state: 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`, +- `snap[row, col]` returns an immutable {class}`~libvt.views.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` +- `snap[row]` returns a {class}`~libvt.views.RowView` with contiguous + {attr}`~libvt.views.RowView.runs` of identically styled text. +- `snap[r0:r1, c0:c1]` returns a rectangular {class}`~libvt.views.RegionView` that also serializes directly as a sub-grid box. -- {attr}`~libvt.terminal.Snapshot.lines` omits unwritten trailing blank cells, - {attr}`~libvt.terminal.Snapshot.display_lines` pads every row to full column +- {attr}`~libvt.snapshot.Snapshot.lines` omits unwritten trailing blank cells, + {attr}`~libvt.snapshot.Snapshot.display_lines` pads every row to full column width with spaces (clipping split wide characters cleanly at slice edges), - and {attr}`~libvt.terminal.Snapshot.unwrapped_text` (along with full-width - {attr}`~libvt.screen.RegionView.unwrapped_text` slices) joins soft-wrapped + and {attr}`~libvt.snapshot.Snapshot.unwrapped_text` (along with full-width + {attr}`~libvt.views.RegionView.unwrapped_text` slices) joins soft-wrapped continuation rows while preserving hard linebreaks (`"\n"`): ```python @@ -172,10 +172,10 @@ extent ends with the text. Both are measured from the start of the row view. ## Stateless scrollback paging (`viewport()`) Primary-screen snapshots retain frozen scrollback alongside the active -viewport. {meth}`Snapshot.viewport ` returns -a `(rows, cols)` {class}`~libvt.screen.RegionView` shifted `offset` lines +viewport. {meth}`Snapshot.viewport ` returns +a `(rows, cols)` {class}`~libvt.views.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` +live `Terminal`. When {attr}`~libvt.snapshot.Snapshot.active_is_alt` is `True` (alternate screen `?1049h`), `viewport()` stays isolated to the alternate screen without blending primary scrollback: @@ -201,25 +201,25 @@ size=12x2 region=True └────────────┘ ``` -Use {meth}`~libvt.terminal.Snapshot.at_abs` to read an absolute row in a +Use {meth}`~libvt.snapshot.Snapshot.at_abs` to read an absolute row in a retained snapshot. When reading that row from a live tmux observer, check the {ref}`bookmark epoch ` before reusing the number. ## 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` (passing `unwrap=True` to join +generation ({attr}`~libvt.snapshot.Snapshot.cursor`, +{attr}`~libvt.snapshot.Snapshot.modes`, {attr}`~libvt.snapshot.Snapshot.title`, +{attr}`~libvt.snapshot.Snapshot.cwd` from `OSC 7`, +{attr}`~libvt.snapshot.Snapshot.prompt_zones` from `OSC 133`, +{attr}`~libvt.snapshot.Snapshot.program_status` from `OSC 7501` and `OSC 9;4`, +{attr}`~libvt.snapshot.Snapshot.appearance`, and +{attr}`~libvt.snapshot.Snapshot.placements`), renders to plain text, VT escape +sequences, or HTML via {meth}`~libvt.snapshot.Snapshot.format` and +{class}`~libvt.format.OutputFormat` (passing `unwrap=True` to join soft-wrapped rows onto a single line in `PLAIN` and `HTML`), and exports a deterministic JSON-compatible dictionary via -{meth}`~libvt.terminal.Snapshot.to_dict`: +{meth}`~libvt.snapshot.Snapshot.to_dict`: ```python >>> import libvt diff --git a/docs/topics/sync-and-asyncio.md b/docs/topics/sync-and-asyncio.md index ca51e003..8c480a64 100644 --- a/docs/topics/sync-and-asyncio.md +++ b/docs/topics/sync-and-asyncio.md @@ -10,7 +10,7 @@ Terminal applications wrap screen redraws in DEC private mode `?2026` During a synchronized redraw, {attr}`term.committed ` retains the previous frame (including -{attr}`Snapshot.appearance ` across `OSC 4` +{attr}`Snapshot.appearance ` across `OSC 4` / `OSC 10`–`12` color updates and `?5` reverse video). {meth}`term.snapshot() ` exposes the screen as it changes: @@ -89,8 +89,8 @@ and {meth}`PtySession.wait_for() ` test a substring or callable predicate against the current committed snapshot, then at synchronized frame and read boundaries, expiring unclosed `?2026` holds after `sync_timeout` seconds. String predicates search -{attr}`~libvt.terminal.Snapshot.unwrapped_text`. Hard linebreaks stay `"\n"`. -Pass a callable using {attr}`~libvt.terminal.Snapshot.text` to match physical +{attr}`~libvt.snapshot.Snapshot.unwrapped_text`. Hard linebreaks stay `"\n"`. +Pass a callable using {attr}`~libvt.snapshot.Snapshot.text` to match physical rows. On timeout or premature EOF, both raise {exc}`~libvt.exc.TerminalTimeoutError` with the boxed screen and recent decoded input attached via `__notes__`: @@ -296,5 +296,5 @@ instance (including capturing state via {meth}`~libvt.terminal.Terminal.snapshot` or {attr}`~libvt.terminal.Terminal.committed`) belongs to a single owning thread or {mod}`asyncio` event loop unless externally synchronized. Returned -{class}`~libvt.terminal.Snapshot` values are immutable and safe to pass across +{class}`~libvt.snapshot.Snapshot` values are immutable and safe to pass across threads without locking. diff --git a/docs/topics/testing.md b/docs/topics/testing.md index 839f829b..e02a2a9a 100644 --- a/docs/topics/testing.md +++ b/docs/topics/testing.md @@ -3,7 +3,7 @@ # Testing Terminal Programs `libvt`'s testing stack builds on top of {class}`~libvt.terminal.Terminal` and -immutable {doc}`snapshots` ({class}`~libvt.terminal.Snapshot` / +immutable {doc}`snapshots` ({class}`~libvt.snapshot.Snapshot` / {attr}`~libvt.terminal.Terminal.committed`), organized into three independent systems so test suites only install what they use: @@ -29,7 +29,7 @@ Core {mod}`libvt.testing` requires neither `pytest` nor `syrupy`. When expected text fits in a few lines, check screens inline with {func}`~libvt.testing.assert_screen` or {func}`~libvt.testing.assert_screen_box`. Attaching a -{class}`~libvt.terminal.FlightRecorder` appends a disassembled trace of recent +{class}`~libvt.recorder.FlightRecorder` appends a disassembled trace of recent VT sequences to {exc}`~libvt.exc.ScreenAssertionError` when an assertion fails: ```python @@ -96,7 +96,7 @@ styles: A boxed golden records the cell's color token, such as `fg=red`. To test a theme change, read the cell and its palette from the same committed -{class}`~libvt.terminal.Snapshot`. {meth}`~libvt.style.Appearance.resolve_rgb` +{class}`~libvt.snapshot.Snapshot`. {meth}`~libvt.style.Appearance.resolve_rgb` returns the color that the palette assigns to that token. ```python @@ -148,7 +148,7 @@ size=16x2 cursor=(1,15,vis=True) alt=True modes=[] ``` Pass the source frame with `region=` to measure replacement glyphs with its -profile and grapheme mode. A standalone {class}`~libvt.screen.RegionView` uses +profile and grapheme mode. A standalone {class}`~libvt.views.RegionView` uses the default profile and grapheme mode for new glyphs. Both forms keep the captured cell widths outside the edited text. @@ -177,7 +177,7 @@ backslash separators and either case of a leading drive letter. The serializer uses captured soft wraps to recognize a URI that spans rows. Pass the original frame with `region=` when the crop omits its prefix. A -standalone {class}`~libvt.screen.RegionView` can use backing columns in its +standalone {class}`~libvt.views.RegionView` can use backing columns in its retained rows. If it starts after a wrapped URI's prefix, a visible continuation can match a literal path. diff --git a/src/libvt/aio/_core.py b/src/libvt/aio/_core.py index 8e956210..d411f9cd 100644 --- a/src/libvt/aio/_core.py +++ b/src/libvt/aio/_core.py @@ -705,16 +705,16 @@ async def wait_for( timeout: float = 2.0, attach_note: bool = True, ) -> Snapshot: - r"""Wait until *predicate* matches :class:`~libvt.terminal.Snapshot`. + r"""Wait until *predicate* matches :class:`~libvt.snapshot.Snapshot`. Parameters ---------- predicate : collections.abc.Callable[[Snapshot], bool] | str Callable evaluated in the waiting task at read and synchronized frame boundaries, or a substring matched against - :attr:`~libvt.terminal.Snapshot.unwrapped_text` across soft-wrapped + :attr:`~libvt.snapshot.Snapshot.unwrapped_text` across soft-wrapped rows. Hard linebreaks remain ``"\n"``. Use a callable with - :attr:`~libvt.terminal.Snapshot.text` to match physical rows. + :attr:`~libvt.snapshot.Snapshot.text` to match physical rows. timeout : float Maximum wait duration in seconds before raising :exc:`~libvt.exc.TerminalTimeoutError`. @@ -725,7 +725,7 @@ async def wait_for( Returns ------- Snapshot - First matching :class:`~libvt.terminal.Snapshot`. + First matching :class:`~libvt.snapshot.Snapshot`. Raises ------ diff --git a/src/libvt/config.py b/src/libvt/config.py index 6a4e7579..b93616ca 100644 --- a/src/libvt/config.py +++ b/src/libvt/config.py @@ -494,7 +494,7 @@ class Limits: max_keyboard_stack : int Maximum entries per screen in the Kitty ``CSI u`` keyboard stack. max_recorder_bytes : int - Maximum raw input bytes retained by :class:`~libvt.terminal.FlightRecorder`. + Maximum raw input bytes retained by :class:`~libvt.recorder.FlightRecorder`. max_images : int Maximum stored Kitty / ``SIXEL`` image metadata entries per screen (default ``256``). diff --git a/src/libvt/contrib/tmux/capture.py b/src/libvt/contrib/tmux/capture.py index 0bbe9ced..04d9469a 100644 --- a/src/libvt/contrib/tmux/capture.py +++ b/src/libvt/contrib/tmux/capture.py @@ -28,9 +28,11 @@ from libvt.events import PromptKind, PromptZone from libvt.modes import DEC_PRIVATE_MASK, Mode from libvt.parser import CsiParams, Parser -from libvt.screen import CursorShape, Screen, ScrollRegion +from libvt.screen import Screen +from libvt.snapshot import Snapshot from libvt.style import DEFAULT_STYLE -from libvt.terminal import Snapshot, Terminal, strip +from libvt.terminal import Terminal, strip +from libvt.views import CursorShape, ScrollRegion #: Accepted input payload shapes for ``tmux capture-pane`` decoders. type CaptureInput = str | bytes | bytearray | collections.abc.Sequence[str] @@ -501,7 +503,7 @@ class TmuxCaptureResult: ``profile`` and ready for subsequent :meth:`~libvt.terminal.Terminal.feed` bytes. snapshot : Snapshot - Immutable :class:`~libvt.terminal.Snapshot` of *terminal*. + Immutable :class:`~libvt.snapshot.Snapshot` of *terminal*. completeness : CaptureCompleteness Fidelity flags and terminal fields not exposed by ``tmux``. line_flags : tuple[TmuxLineFlags, ...] diff --git a/src/libvt/contrib/tmux/control.py b/src/libvt/contrib/tmux/control.py index 3ca1c738..64a7b7b0 100644 --- a/src/libvt/contrib/tmux/control.py +++ b/src/libvt/contrib/tmux/control.py @@ -954,8 +954,8 @@ def resync(self) -> str: Re-runs the atomic pause barrier + ``capture-pane`` + ``-P -p -C`` + ``continue`` sequence and updates any existing :attr:`~libvt.contrib.tmux.control.TmuxPaneSync.terminal` in place - (incrementing its epoch so existing :class:`~libvt.terminal.SyncToken` - consumers receive :attr:`~libvt.terminal.ResyncReason.EPOCH_CHANGED`). + (incrementing its epoch so existing :class:`~libvt.snapshot.SyncToken` + consumers receive :attr:`~libvt.snapshot.ResyncReason.EPOCH_CHANGED`). Returns ------- diff --git a/src/libvt/contrib/tmux/window.py b/src/libvt/contrib/tmux/window.py index 06e9ad71..15709845 100644 --- a/src/libvt/contrib/tmux/window.py +++ b/src/libvt/contrib/tmux/window.py @@ -36,7 +36,8 @@ tmux_profile, ) from libvt.modes import Mode -from libvt.screen import Cursor, Screen +from libvt.screen import Screen +from libvt.snapshot import Snapshot from libvt.style import ( DEFAULT_STYLE, AnsiColor, @@ -47,7 +48,8 @@ Style, UnderlineStyle, ) -from libvt.terminal import _DEC_SPECIAL_GRAPHICS, Snapshot, Terminal +from libvt.terminal import _DEC_SPECIAL_GRAPHICS, Terminal +from libvt.views import Cursor _THEME_SLOTS: tuple[tuple[str, str, AnsiColor], ...] = ( ("themeblack", "black", AnsiColor.BLACK), @@ -1992,7 +1994,7 @@ def composite_tmux_window( Window dimensions, border options, and pane geometry descriptors. panes : Mapping[str, TmuxPaneSource] Mapping from ``pane_id`` (e.g. ``"%0"``) to each pane's - :class:`~libvt.terminal.Snapshot`, :class:`~libvt.screen.Screen`, + :class:`~libvt.snapshot.Snapshot`, :class:`~libvt.screen.Screen`, :class:`~libvt.terminal.Terminal`, :class:`TmuxCaptureResult`, or live :class:`~libvt.contrib.tmux.control.TmuxPaneSync` handle. tmux_version : tuple[int, int] | str, default "3.8a" @@ -2002,7 +2004,7 @@ def composite_tmux_window( ``tmux <= 3.6`` keeps it visible at ``cols - 1``). profile : Profile | None, default None Terminal compatibility profile for width calculations and the returned - :class:`~libvt.terminal.Snapshot`. + :class:`~libvt.snapshot.Snapshot`. Returns ------- @@ -2798,7 +2800,7 @@ class TmuxWindowCaptureResult: Attributes ---------- snapshot : Snapshot - Composited application-screen :class:`~libvt.terminal.Snapshot`, + Composited application-screen :class:`~libvt.snapshot.Snapshot`, excluding copy-mode overlays (use :func:`~libvt.aio.open_pty` for client views) and inheriting ``capture-pane`` erased-bg and emoji-width limits. panes : collections.abc.Mapping[str, TmuxCaptureResult] diff --git a/src/libvt/exc.py b/src/libvt/exc.py index 8a599adc..ef0b8d79 100644 --- a/src/libvt/exc.py +++ b/src/libvt/exc.py @@ -70,7 +70,7 @@ class TerminalTimeoutError(LibVtError, TimeoutError): screen_text : str Visible screen text at failure time. recent_bytes : collections.abc.Buffer - Trailing raw bytes from :class:`~libvt.terminal.FlightRecorder`. + Trailing raw bytes from :class:`~libvt.recorder.FlightRecorder`. eof : bool ``True`` when the stream closed before the predicate matched. diagnostics : str diff --git a/src/libvt/format.py b/src/libvt/format.py index 0056553e..3aa8d8e2 100644 --- a/src/libvt/format.py +++ b/src/libvt/format.py @@ -218,11 +218,11 @@ def runs() -> collections.abc.Iterator[tuple[str, Style, Hyperlink | None]]: class Formatter: - r"""Serialize a :class:`~libvt.terminal.Snapshot` to plain text, VT, or HTML. + r"""Serialize a :class:`~libvt.snapshot.Snapshot` to plain text, VT, or HTML. Replay VT output into a fresh :class:`~libvt.terminal.Terminal` of the same size and profile. - See :meth:`~libvt.terminal.Snapshot.format` for the VT export contract. + See :meth:`~libvt.snapshot.Snapshot.format` for the VT export contract. Attributes ---------- diff --git a/src/libvt/pytest_plugin.py b/src/libvt/pytest_plugin.py index 3a50fc5b..46448499 100644 --- a/src/libvt/pytest_plugin.py +++ b/src/libvt/pytest_plugin.py @@ -71,7 +71,7 @@ def __call__( @pytest.fixture def vt_recorder() -> FlightRecorder: - r"""Return a fresh 4 KiB :class:`~libvt.terminal.FlightRecorder`. + r"""Return a fresh 4 KiB :class:`~libvt.recorder.FlightRecorder`. Returns ------- diff --git a/src/libvt/screen.py b/src/libvt/screen.py index 0bce6600..fd50e446 100644 --- a/src/libvt/screen.py +++ b/src/libvt/screen.py @@ -1136,7 +1136,7 @@ def snapshot( generation: int | None = None, profile: Profile | None = None, ) -> Snapshot: - r"""Freeze this screen into an immutable :class:`~libvt.terminal.Snapshot`. + r"""Freeze this screen into an immutable :class:`~libvt.snapshot.Snapshot`. Clones visible viewport rows and CoW scrollback blocks so subsequent edits on this :class:`Screen` never mutate the returned snapshot. diff --git a/src/libvt/snapshot.py b/src/libvt/snapshot.py index aa63e15f..e50cb1df 100644 --- a/src/libvt/snapshot.py +++ b/src/libvt/snapshot.py @@ -746,7 +746,7 @@ def viewport(self, offset: int = 0) -> RegionView: Zero-based upward scroll offset in terminal rows. ``0`` returns the captured active viewport; positive values scroll into retained primary history (clamped to ``len(history)``). Alternate-screen - snapshots (:attr:`~libvt.terminal.Snapshot.active_is_alt` is + snapshots (:attr:`~libvt.snapshot.Snapshot.active_is_alt` is ``True``) always return their alternate viewport without blending primary scrollback. @@ -754,8 +754,8 @@ def viewport(self, offset: int = 0) -> RegionView: ------- RegionView Immutable rectangular view with height - :attr:`~libvt.terminal.Snapshot.rows` and width - :attr:`~libvt.terminal.Snapshot.cols`. + :attr:`~libvt.snapshot.Snapshot.rows` and width + :attr:`~libvt.snapshot.Snapshot.cols`. Raises ------ diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py index 3db176e1..44d08dc7 100644 --- a/src/libvt/terminal.py +++ b/src/libvt/terminal.py @@ -955,12 +955,12 @@ def screens(self) -> ScreenSet: @property def history(self) -> collections.abc.Sequence[RowView]: - """Return sealed scrollback :class:`~libvt.screen.RowView` lines.""" + """Return sealed scrollback :class:`~libvt.views.RowView` lines.""" return self._screens.primary.history @property def cursor(self) -> Cursor: - """Return current zero-based :class:`~libvt.screen.Cursor`.""" + """Return current zero-based :class:`~libvt.views.Cursor`.""" return self._screens.active.cursor @property diff --git a/src/libvt/testing.py b/src/libvt/testing.py index 2e898533..6973a63e 100644 --- a/src/libvt/testing.py +++ b/src/libvt/testing.py @@ -25,7 +25,8 @@ from libvt.exc import ScreenAssertionError from libvt.modes import ALT_SCREEN_MODES, TRANSIENT_SNAPSHOT_MODES, Mode from libvt.recorder import find_flight_recorder -from libvt.screen import Cell, RegionView, RowView, Screen +from libvt.screen import Screen +from libvt.snapshot import Snapshot from libvt.style import ( DEFAULT_STYLE, AnsiColor, @@ -34,7 +35,8 @@ Style, UnderlineStyle, ) -from libvt.terminal import Snapshot, Terminal +from libvt.terminal import Terminal +from libvt.views import Cell, RegionView, RowView def _box_row_cells(row: RowView) -> list[str]: @@ -477,8 +479,8 @@ class VtScreenView: Attributes ---------- target : VtTarget - :class:`~libvt.terminal.Terminal`, :class:`~libvt.terminal.Snapshot`, - :class:`~libvt.screen.Screen`, :class:`~libvt.screen.RegionView`, + :class:`~libvt.terminal.Terminal`, :class:`~libvt.snapshot.Snapshot`, + :class:`~libvt.screen.Screen`, :class:`~libvt.views.RegionView`, :class:`SupportsVtTarget` provider, or pane handle exposing ``.terminal``, ``.snapshot``, or ``.capture_vt()``. diff : VtTarget | VtScreenView | None @@ -1144,14 +1146,14 @@ def serialize_vt_snapshot( A terminal supplies its committed frame. Visible row order and soft-wrap markers come from the captured grid. A standalone - :class:`~libvt.screen.RegionView` uses the default profile and grapheme + :class:`~libvt.views.RegionView` uses the default profile and grapheme mode for replacement glyphs. Parameters ---------- target : VtTarget | VtScreenView - :class:`~libvt.terminal.Terminal`, :class:`~libvt.terminal.Snapshot`, - :class:`~libvt.screen.Screen`, :class:`~libvt.screen.RegionView`, + :class:`~libvt.terminal.Terminal`, :class:`~libvt.snapshot.Snapshot`, + :class:`~libvt.screen.Screen`, :class:`~libvt.views.RegionView`, :class:`SupportsVtTarget` provider, :class:`VtScreenView`, or pane wrapper exposing ``.terminal``, ``.snapshot``, or ``.capture_vt()``. scrubbers : Sequence[ScrubberSpec], optional diff --git a/src/libvt/views.py b/src/libvt/views.py index a571ed44..a1c0c20c 100644 --- a/src/libvt/views.py +++ b/src/libvt/views.py @@ -980,7 +980,7 @@ def unwrapped_text(self) -> str: r"""Return newline-joined text, unwrapping full-width soft-wrapped rows. Full-width row slices (such as ``snap[0:5]`` or - :meth:`~libvt.terminal.Snapshot.viewport`) join contiguous + :meth:`~libvt.snapshot.Snapshot.viewport`) join contiguous ``row.wrapped`` rows without ``"\n"`` when their original right margin is visible. The current frame determines the slice width even when history contains rows sealed at a different diff --git a/tests/test_libvt.py b/tests/test_libvt.py index dbbf16d8..e59a2ce1 100644 --- a/tests/test_libvt.py +++ b/tests/test_libvt.py @@ -303,7 +303,7 @@ def test_documented_examples_include_explicit_imports( "docs/topics/testing.md", "docs/api/testing.md", "docs/api/pytest_plugin.md", - "docs/api/contrib_syrupy.md", + "docs/api/contrib/syrupy.md", ) has_syrupy = importlib.util.find_spec( "syrupy" @@ -413,3 +413,31 @@ def test_core_split_has_no_screen_to_terminal_cycle_and_keeps_reexports() -> Non assert callable(util_mod._byte_view) assert callable(util_mod._parse_ascii_uint) assert callable(util_mod._parse_ascii_int) + + +def test_every_public_module_has_api_doc_page() -> None: + """Every public module and package has its own API reference page.""" + repo_root = pathlib.Path(__file__).resolve().parent.parent + src_root = repo_root / "src" / "libvt" + api_root = repo_root / "docs" / "api" + + missing: list[str] = [] + for path in sorted(src_root.rglob("*.py")): + rel = path.relative_to(src_root) + parts = rel.parts + if any(p.startswith("_") and p != "__init__.py" for p in parts): + continue + if parts == ("__init__.py",): + expected = api_root / "libvt.md" + elif parts[-1] == "__init__.py": + expected = api_root.joinpath(*parts[:-1], "index.md") + else: + expected = api_root.joinpath(*parts[:-1], f"{path.stem}.md") + if not expected.is_file(): + missing.append( + f"{path.relative_to(repo_root)} -> {expected.relative_to(repo_root)}" + ) + assert missing == [] + + for aio_page in ("index.md", "core.md", "stream.md", "pty.md"): + assert (api_root / "aio" / aio_page).is_file(), f"docs/api/aio/{aio_page}"