From d5b6818755c1533c03a82be603750cd35488a73c Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 21 Nov 2026 14:41:05 -0600 Subject: [PATCH 01/29] Docs(feat[adr]): Add ADRs 0001-0010 for libvt why: Record clean-room MIT boundaries, two-tier storage, Unicode 17 clustering, Rex OSC 7501, input encoding, and safety contracts before implementing the v0.1 engine. what: - Add ADRs 0001-0010 covering provenance, Profile/Policy/Limits, packed viewport + FrozenRow RLE scrollback, (row, col) coordinates and reflow, UTF-8/C1 isolation + Unicode 17 block table, G0-G3 charsets + single-truth DECRQM, Rex OSC 7501 + semantic prompts, mode-aware input encoding + fail-closed paste, sequence explain codec, and asyncio/PTY/pytest diagnostics - Register ADRs 0001-0010 in docs/project/adr/index.md --- ...an-room-provenance-and-license-firewall.md | 94 ++++++++++++++ ...ns-io-layers-profiles-and-closed-events.md | 121 ++++++++++++++++++ ...tier-packed-viewport-and-rle-scrollback.md | 121 ++++++++++++++++++ ...d-row-col-coordinates-and-sync-stepping.md | 100 +++++++++++++++ ...isolation-and-unicode-17-grapheme-width.md | 105 +++++++++++++++ ...ns-and-single-truth-mode-reconciliation.md | 95 ++++++++++++++ ...501-program-status-and-semantic-prompts.md | 110 ++++++++++++++++ ...e-aware-input-encoding-and-paste-safety.md | 96 ++++++++++++++ ...ive-sequence-codec-and-stream-explainer.md | 68 ++++++++++ ...ly-asyncio-and-diagnostic-pytest-plugin.md | 100 +++++++++++++++ docs/project/adr/index.md | 21 ++- 11 files changed, 1028 insertions(+), 3 deletions(-) create mode 100644 docs/project/adr/0001-clean-room-provenance-and-license-firewall.md create mode 100644 docs/project/adr/0002-sans-io-layers-profiles-and-closed-events.md create mode 100644 docs/project/adr/0003-two-tier-packed-viewport-and-rle-scrollback.md create mode 100644 docs/project/adr/0004-zero-based-row-col-coordinates-and-sync-stepping.md create mode 100644 docs/project/adr/0005-utf8-c1-isolation-and-unicode-17-grapheme-width.md create mode 100644 docs/project/adr/0006-charset-designations-and-single-truth-mode-reconciliation.md create mode 100644 docs/project/adr/0007-rex-osc-7501-program-status-and-semantic-prompts.md create mode 100644 docs/project/adr/0008-mode-aware-input-encoding-and-paste-safety.md create mode 100644 docs/project/adr/0009-declarative-sequence-codec-and-stream-explainer.md create mode 100644 docs/project/adr/0010-transport-only-asyncio-and-diagnostic-pytest-plugin.md diff --git a/docs/project/adr/0001-clean-room-provenance-and-license-firewall.md b/docs/project/adr/0001-clean-room-provenance-and-license-firewall.md new file mode 100644 index 0000000..cca87d5 --- /dev/null +++ b/docs/project/adr/0001-clean-room-provenance-and-license-firewall.md @@ -0,0 +1,94 @@ +(adr-clean-room-provenance)= + +# ADR 0001: Clean-room MIT provenance, PyPI namespace, and Python 3.12+ floor + +## Status + +Accepted. 2026-11-21. + +## Context + +`libtmux` (`>= 3.11`), `tmuxp` (`>= 3.11`), and Python terminal test suites +need an in-memory virtual terminal emulator and streaming VT parser without +copyleft license obligations (`tmux-python/libtmux#886`). Existing pure-Python +and GTK terminal libraries carry copyleft terms (`pyte` under `LGPL-3.0`, +`libvte` under `LGPL-3.0`, and `asciinema`'s virtual terminal engine under +`GPL-3.0-or-later`) and omit contemporary terminal extensions used by `tmux` +and modern TUIs: DEC mode `?2026` synchronized output, DEC mode `?2027` +Unicode grapheme clustering, ITU T.416 colon-delimited `SGR` subparameters +(`4:3`, `38:2::R:G:B`, `58:2::R:G:B`), `OSC 8` hyperlinks, `OSC 133` semantic +shell prompts, `OSC 7501` program status, Kitty keyboard stacks (`CSI u`), and +`SIXEL` / Kitty graphics placement and erase tracking. + +Three packaging and runtime constraints govern the package boundary: + +1. **Distribution and import name availability**: Candidate package names + `pyvt` (`https://pypi.org/project/pyvt/`) and `vt` + (`https://pypi.org/project/vt/`, also used as `import vt` by `vt-py`) are + already registered on PyPI, whereas `libvt` is available and matches the + `libtmux` / `libvcs` naming family. +2. **Python interpreter floor**: Raising `requires-python` to `>= 3.14` (to + use stdlib `compression.zstd` or PEP 649 runtime semantics) would block + adoption in `libtmux`, `tmuxp`, and downstream CI matrices running Python + 3.12 and 3.13. +3. **Pure-Python wheel portability**: Shipping a mandatory C, Zig, or Rust + extension complicates universal wheels, free-threaded CPython builds + (`PYTHON_GIL=0`), PyPy, WebAssembly sandboxes, and offline CI runners. + +## Decision + +`libvt` ships as a standalone, MIT-licensed, pure-Python (`py3-none-any.whl`) +distribution under the `libvt` package and import name with +`dependencies = []` and `requires-python = ">=3.12,<4.0"`: + +- **Clean-room license firewall**: Every parser transition, escape parameter + rule, character-width table, and test vector is derived strictly from public + standards (ECMA-48, DEC STD 070, ITU T.416, Paul Flo Williams' VT500 parser + state diagram, Unicode UAX #11 and UAX #29) and permissively licensed + (`MIT`, `ISC`, `Apache-2.0`, `BSD`) specifications and implementations + (`tmux`, `ghostty` / `libghostty-vt`, `alacritty_terminal`, `wezterm` VT + crates, `zellij`, `ratatui`, and the Rex `OSC 7501` specification). +- **Copyleft quarantine**: Source code under `LGPL`, `GPL`, `AGPL`, or `MPL` + (including `pyte`, `libvte`, `asciinema`, `fish-shell`, and `helix`) MUST + never be read, translated, or copied when developing or testing `libvt`. +- **Acyclic ecosystem dependency graph**: `stdlib -> libvt -> libtmux -> tmuxp`. + `libvt` never imports `libtmux`. +- **Zero-GIL thread safety**: Mutable parser and SGR memoization tables live on + `Parser` / `Terminal` instances rather than unlocked module-global + dictionaries so concurrent `Terminal` instances run without data races on + free-threaded CPython (`3.13t` / `3.14t`). + +## Alternatives considered + +| Candidate | License | PyPI name | Wheel | Python floor | Disqualifier or trade-off | +|---|---|---|---|---|---| +| `libvt` standalone pure-Python (chosen) | MIT | available | `py3-none-any.whl` | `>= 3.12` | Pure-Python CPU ceiling (~10-35 MiB/s vs SIMD native) | +| `pyvt` / `vt` standalone naming | MIT | occupied | `py3-none-any.whl` | `>= 3.12` | Name collision on PyPI and `import vt` conflict | +| Python `>= 3.14`-only pure-Python engine | MIT | occupied (`vt`) | `py3-none-any.whl` | `>= 3.14` | Excludes Python 3.12 and 3.13 consumers (`libtmux`, `tmuxp`) | +| Inline helper inside `libtmux.test.vt` | MIT | n/a | `py3-none-any.whl` | `>= 3.11` | Unusable without installing `libtmux` | +| Mandatory `libghostty-vt` C ABI FFI wheel | MIT | available | platform wheels | `>= 3.12` | Requires Zig build matrix; omits `SIXEL` | +| Retain `pyte` | LGPL-3.0 | occupied | `py3-none-any.whl` | `>= 3.8` | Copyleft license; lacks `?2026`, `?1049`, colon SGR, `OSC 8/133/7501` | + +## Consequences + +### Positive + +- Downstream MIT, BSD, Apache-2.0, and proprietary consumers depend on `libvt` + without copyleft review or native C/Zig/Rust toolchains. +- Python 3.12, 3.13, 3.14, 3.15, and PyPy share a single `py3-none-any.whl` + artifact. +- Instance-local caches allow parallel test workers and free-threaded Python + threads to drive separate `Terminal` instances concurrently. + +### Tradeoffs + +- Pure-Python byte ingestion (`~10-35 MiB/s` on ASCII/ANSI streams) is slower + than SIMD-accelerated native engines (`>100 MiB/s`), while still processing + typical `80x24` TUI frames in well under a millisecond. + +### Risks + +- Contributors consulting copyleft terminal emulators during bug fixes. + Mitigation: state the quarantine in `AGENTS.md`, `.github/CONTRIBUTING.md`, + and this ADR, and cite ECMA-48, DEC, `tmux`, or `ghostty` references in + tests and commit messages. diff --git a/docs/project/adr/0002-sans-io-layers-profiles-and-closed-events.md b/docs/project/adr/0002-sans-io-layers-profiles-and-closed-events.md new file mode 100644 index 0000000..3f3b448 --- /dev/null +++ b/docs/project/adr/0002-sans-io-layers-profiles-and-closed-events.md @@ -0,0 +1,121 @@ +(adr-sans-io-layers)= + +# ADR 0002: Sans-I/O layering, Profile/Policy/Limits separation, and closed Events + +## Status + +Accepted. 2026-11-21. + +## Context + +A virtual terminal package serves four audiences with competing ergonomic and +performance requirements: + +1. **One-line script and CLI callers** that want rendered plain text or + ANSI-stripped text from a `bytes` capture (`libvt.render(raw)` / + `libvt.strip(raw)`) without instantiating classes. +2. **Deterministic unit tests** (`term = Terminal(rows=24, cols=80); + term.feed(raw)`) that inspect `term.text`, `term[row, col]`, and + `term.cursor` with zero file descriptors, sockets, clocks, or threads. +3. **Interactive PTY harnesses** (`tmux attach-session`, shells, full-screen + TUIs) that must flush bidirectional capability replies (`DA1`, `DA2`, + `XTVERSION`, `DSR`, `DECRQM`, `DECRQSS`, `XTGETTCAP`, `OSC 7501 ; ?`, + `CSI ? u`) back to the child PTY while blocking untrusted sequences from + exfiltrating clipboard data or window titles. +4. **Protocol tools and host integrators** that subscribe to structured side + effects (`Bell`, `TitleChanged`, `WorkingDirectoryChanged`, `ClipboardWrite`, + `PromptMark`, `ProgramStatusChanged`, `SixelGraphic`, `KittyGraphic`, + `ScreenErased`) with exhaustive static type narrowing. + +Three anti-patterns surfaced when evaluating candidate designs: + +- **Returning `list[Effect]` or `Update` from every `feed()` call**: Allocates + wrapper lists/objects on 100% of chunks even when callers only inspect grid + state at quiescence, and encourages callers to treat arbitrary `os.read()` + chunk cuts as semantic transaction boundaries. +- **Mixing security policy booleans and event callbacks on a single `Effects` + bag**, or exposing `ActionSink` methods (`on_print`, `on_csi`, `on_osc`) + publicly on `Terminal`: Confuses IDE autocompletion between internal parser + dispatch methods and host event hooks. +- **Splitting every CSI/OSC sequence into ~40 micro-modules and dispatching + hot-path `feed()` via boxed `Token` -> `Command` dataclasses**: Inflates + import time and object allocation on SGR/cursor-heavy streams. + +## Decision + +Organize `libvt` as a flat ~15-module Sans-I/O package with progressive +disclosure and explicit separation between terminal identity (`Profile`), +security gates (`Policy`), resource bounds (`Limits`), outbound wire replies +(`drain_replies()`), and semantic host events (`Event`): + +1. **Progressive-disclosure entry points (`libvt`)**: + - Level 0 pure helpers: `render(data, *, rows=24, cols=80) -> str`, + `strip(data) -> str`, and `explain(data) -> tuple[ExplainedSpan, ...]`. + - Level 1 stateful facade: `Terminal(*, rows=24, cols=80, ...)`. + - Level 2 standalone building blocks: `Parser`, `parse_sgr`, `encode_input`, + `Formatter`, `AsyncTerminalStream`, `open_pty`, and `assert_screen`. +2. **Three immutable configuration objects (`libvt.config`)**: + - `Profile`: Terminal identity and compatibility behavior (`name`, `da1`, + `da2`, `xtversion`, `osc_7501_capabilities`, `color_scheme`, + `fg_rgb`, `bg_rgb`, `pending_wrap_phantom_col`), with presets + `DEFAULT_PROFILE` (`XTERM_PROFILE`) and `TMUX_PROFILE`. + - `Policy`: Default-deny host security gates (`allow_title_report=False`, + `allow_checksum_report=False`, `allow_clipboard_read=False`, + `allow_clipboard_write=False`, `allow_color_queries=True`, + `allow_program_status_query=False`, `allow_unsafe_uris=False`, + `unwrap_tmux_passthrough=True`, `strict=False`). + - `Limits`: Hard memory and CPU bounds (`max_grapheme_codepoints=32`, + `max_csi_params=32`, `max_osc_bytes=131_072`, `max_dcs_bytes=4_194_304`, + `max_apc_bytes=4_194_304`, `max_reply_bytes=65_536`, + `max_rep_count=4_096`, `max_prompt_zones=1_024`, + `max_status_records=64`, `max_events=4_096`, `max_keyboard_stack=8`). +3. **Zero-allocation hot path with private `_TerminalSink`**: + - `Terminal.feed(data, /) -> None` mutates terminal state in place through + an internal `_TerminalSink` passed to `Parser.feed_to()`. Public + `Terminal` attributes contain no `on_print` / `on_csi` plumbing methods. + - Outbound wire replies accumulate in a `Limits.max_reply_bytes`-bounded + `bytearray` drained via `term.drain_replies() -> bytes` (or forwarded via + `on_pty_write` when attached). +4. **Closed algebraic `Event` union (`libvt.events`)**: + - `type Event = Bell | TitleChanged | WorkingDirectoryChanged | + ClipboardWrite | PromptMark | ProgramStatusChanged | RenderHoldChanged | + ColorSchemeQueried | InBandResize | SixelGraphic | KittyGraphic | + ScreenErased | UnhandledSequence`. + - Callers either pass `on_event: Callable[[Event], None]` (push) or set + `record_events: bool = True` and call `term.drain_events() -> + tuple[Event, ...]` (pull). When neither is enabled, `feed()` allocates + zero `Event` objects. + +## Alternatives considered + +- **`feed(data) -> list[Effect]` or `feed(data) -> Update`**: Rejected because + allocating return containers on every `os.read()` chunk penalizes the 95% + case where callers inspect `term.text` or `term.committed` after feeding. +- **Two-object `Screen` + `Stream(screen)` split**: Rejected because sans-I/O + reply generation (`DA1`, `DSR`, `DECRQM`), dual-screen mode reconciliation, + and `?2026` held snapshots span parser dispatch and screen state together. +- **40+ file per-sequence subpackage hierarchy**: Rejected per `AGENTS.md` + file-boundary rules; keeping ~15 cohesive modules preserves fast imports and + direct dispatch. + +## Consequences + +### Positive + +- Callers match `Event` exhaustively (`case _: t.assert_never(ev)`) under `ty`, + `mypy`, and `pyright`. +- `Policy`, `Profile`, and `Limits` separate security review from capability + emulation and DoS budgets. +- `Terminal` keeps a small, discoverable method surface without leaking parser + sink callbacks. + +### Tradeoffs + +- Callers wanting pull-based event inspection pass `record_events=True` (or an + `on_event` callback) instead of receiving events implicitly from `feed()`. + +### Risks + +- Event queue growth when `record_events=True` and `drain_events()` is never + called. Mitigation: store buffered events in a `collections.deque` bounded by + `Limits.max_events`. diff --git a/docs/project/adr/0003-two-tier-packed-viewport-and-rle-scrollback.md b/docs/project/adr/0003-two-tier-packed-viewport-and-rle-scrollback.md new file mode 100644 index 0000000..43cbff9 --- /dev/null +++ b/docs/project/adr/0003-two-tier-packed-viewport-and-rle-scrollback.md @@ -0,0 +1,121 @@ +(adr-two-tier-storage)= + +# ADR 0003: Two-tier lazy packed viewport rows and RLE FrozenRow scrollback + +## Status + +Accepted. 2026-11-21. + +## Context + +Grid and scrollback storage in pure Python faces three simultaneous traps: + +1. **Object-per-cell heap blowup**: Representing a `10,000 x 80` scrollback + buffer as `list[list[Cell]]` (800,000 frozen slotted dataclasses) consumes + `56.46 MiB` of traced CPython 3.15 heap (`>130 MiB` without `__slots__`) + and amplifies garbage-collection pause times. +2. **Pooled `StyleId` RGB leaks and `u16` overflows**: Designs that intern + `Style` objects into a `StylePool` indexed by `array("I")` (`u32`) or + `array("H")` (`u16`) break on 24-bit RGB (`SGR 38;2;r;g;b`) streams + (`btop`, `chafa`, `timg`, smooth fades, or hostile PTYs). Without eviction, + 16.7 million RGB combinations leak gigabytes of `Style` objects across + `RIS`; with `array("H")` (`u16`), style `#65,536` (reached in `<50 ms` of + `240x80` truecolor frames) raises `OverflowError` or requires expensive + stop-the-world reference counting across active and historical cells. +3. **Unwritten-blank vs space vs wide-spacer ambiguity**: Using `""` for + unwritten blank cells causes cursor jumps (`CSI 1;10 H` + `"OK"`) to + collapse interior columns when joining cell text (`"OK"` instead of + `" OK"`) and collides with `""` on wide-character `SPACER_TAIL` + cells. Conversely, scanning backward across `" "` cells during `EL 0` + (`CSI K`) must never erase explicit `" "` characters printed to the left of + the erase start column. + +## Decision + +Adopt a two-tier memory architecture that uses **inline 64-bit bit-packed +attribute words** (zero `StylePool`) across both hot mutable viewport rows and +cold run-length-encoded (`RLE`) scrollback lines: + +1. **Hot viewport `_Row` (`libvt._grid`)**: + - `chars: list[str]` of length `cols`: `" "` for narrow blank or erased + cells, single-codepoint or multi-codepoint grapheme strings for printed + cells, and `""` reserved strictly for `WidthRole.SPACER_TAIL` and + `WidthRole.SPACER_HEAD`. + - `used: int`: High-water column index (`0..cols`) of explicitly written or + non-default `BCE`-erased content. `clear_range(lo, cols, bce_word=0)` + clamps `used = min(used, lo)` without scanning left past `lo`, preserving + explicit spaces printed left of `lo`. + - **Lazy 64-bit `attrs`**: Starts as `attrs: array.array[int] | None = None` + with scalar `uniform_attr: int = 0` and `has_wide: bool = False`. Plain + default-styled ASCII writes slice-assign `chars[col:end] = list(seg)` + with zero `array("Q")` allocation. On the first non-uniform style, + wide glyph, protected attribute, or `HAS_EXT` cell, `_Row` promotes + `attrs = array.array("Q", [uniform_attr]) * cols`. + - **64-bit inline bit layout (`0` == blank default narrow unprotected cell)**: + - bits `0..24` (`25`b): foreground color (`0` = default, `1..16` = + `AnsiColor`, `256..511` = `IndexedColor(0..255)` keeping `0..15` + distinct from `AnsiColor`, `(1 << 24) | 0xRRGGBB` = `RgbColor`). + - bits `25..49` (`25`b): background color (same encoding). + - bits `50..56` (`7`b): `bold`, `dim`, `italic`, `blink`, `reverse`, + `hidden`, `strikethrough`. + - bits `57..59` (`3`b): `UnderlineStyle` (`0..5`). + - bits `60..61` (`2`b): `WidthRole` (`NARROW=0`, `WIDE=1`, + `SPACER_TAIL=2`, `SPACER_HEAD=3`). + - bit `62` (`1`b): `overline`. + - bit `63` (`1`b): `HAS_EXT`, gating lazy `ext: dict[int, _CellExt] | None` + holding `underline_color: Color`, `hyperlink: Hyperlink | None`, and + `protected: bool` (`DECSCA`). +2. **Cold scrollback `FrozenRow` (`libvt._grid`) and `_Row` recycling**: + - When `Screen.scroll_up` evicts a full-width top row into `history`, it + seals the row into an immutable `FrozenRow(text: str, cols: int, + runs: tuple[tuple[int, int], ...], exts: tuple[tuple[int, _CellExt], ...], + wrapped: bool)` where `runs` stores `(end_col, attr_u64)` RLE spans + (sharing a singleton `()` tuple when completely default-styled) and + recycles the cleared `_Row` instance to the bottom of the viewport. + - Measured on CPython 3.15.1 (`10,000 x 80` styled CLI log rows), + `FrozenRow` RLE scrollback consumes `~2.66 MiB` vs `22.59 MiB` for cloned + mutable `_Row`s (`8.5x` reduction) and `56.46 MiB` for `Cell` grids + (`21.2x` reduction) — with zero `zstd` dependency and zero `StylePool` + leak. +3. **Unified public `RowView`, `RowRun`, and `Cell` views (`libvt.screen`)**: + - `RowView` wraps either a live `_Row` or a `FrozenRow`, exposing `.text`, + `.wrapped`, `row[col] -> Cell` (returning `BLANK_CELL` when default), and + `.runs -> tuple[RowRun, ...]` for `O(runs)` styled span rendering. + - Both `Screen.history` and `Snapshot.history` return `tuple[RowView, ...]` + without leaking mutable `deque` or private `_Row` internals. + +## Alternatives considered + +| Storage model | `10,000 x 80` heap (Py 3.15) | 24-bit RGB safety | Multi-codepoint graphemes | Verdict | +|---|---|---|---|---| +| Lazy 64-bit `_Row` + RLE `FrozenRow` (chosen) | `~2.66 MiB` | inline 64b (leak-free) | native `str` per cell | Adopted | +| Uncompressed cloned `_Row` scrollback | `22.59 MiB` | inline 64b (leak-free) | native `str` per cell | `8.5x` heavier scrollback | +| `array("I")` codepoint + `u32` `StylePool` | `11.04 MiB` + pool | leaks unbounded RGB styles | side-dict per cluster | OOM on RGB streams | +| `CompactRow` `array("H")` `u16` `StyleId` | `~1.7-3.0 MiB` + pool | `OverflowError` at 65,536 styles | native `str` per cell | Crashes/corrupts on truecolor | +| `list[list[Cell]]` grid | `56.46 MiB` | per-cell objects | native `str` per cell | High RAM and GC pressure | + +## Consequences + +### Positive + +- Truecolor animations (`16.7M` colors) allocate zero persistent style-table + entries and never overflow 16-bit IDs. +- Unstyled ASCII logs skip `array("Q")` allocation on active rows and compress + to one `str` + shared empty tuple in scrollback, recycling `_Row` buffers on + every scroll. +- `IndexedColor(0..15)` (`SGR 38;5;0..15`) round-trips distinctly from + `AnsiColor(0..15)` (`SGR 30..37`, `90..97`). + +### Tradeoffs + +- Random cell indexing into `FrozenRow` (`history[i][col]`) performs a short + tuple scan (`bisect` / linear over typically 1-6 RLE spans) rather than + `O(1)` array indexing. + +### Risks + +- Wide-character `WIDE` / `SPACER_TAIL` pairing corruption during `ICH` + (`CSI @`) or `DCH` (`CSI P`). Mitigation: heal split wide pairs *after* or at + the exact cut boundaries (`col` when `col` is `SPACER_TAIL`, and `right` when + a shifted `WIDE` head loses its tail at the right margin), verified by + 400+ randomized fuzz trials. diff --git a/docs/project/adr/0004-zero-based-row-col-coordinates-and-sync-stepping.md b/docs/project/adr/0004-zero-based-row-col-coordinates-and-sync-stepping.md new file mode 100644 index 0000000..e3bf199 --- /dev/null +++ b/docs/project/adr/0004-zero-based-row-col-coordinates-and-sync-stepping.md @@ -0,0 +1,100 @@ +(adr-coordinates-and-sync-stepping)= + +# ADR 0004: Zero-based (row, col) coordinates, resize reflow, and ?2026 stepping + +## Status + +Accepted. 2026-11-21. + +## Context + +Three coordinate and frame-lifecycle problems recur across terminal APIs: + +1. **Axis inversion**: Legacy Python libraries pass `(cols, rows)` to + constructors and `(x, y)` on cursors while indexing `screen[row][col]`, + inverting horizontal and vertical axes between construction and indexing. +2. **Cursor allocation churn and `pending_wrap` edge cases**: Storing `Screen`'s + live cursor as a frozen dataclass re-allocated on every character, `CR`, and + `LF` consumed `28%` of total CPU in `cProfile` runs (`90,000+` allocations + per `30,000` lines). In addition, `xterm`/`Ghostty` and `tmux` (`s->cx == sx` + in `screen-write.c`) differ subtly when `CUB` (`CSI D`) or `BS` (`0x08`) + arrives during `pending_wrap` at the right margin. +3. **Torn `?2026` frames, timer races, and resize reflow**: Eagerly cloning all + 24 rows on every `CSI ? 2026 h` wastes work when `CSI ? 2026 l` arrives in + the same `feed()` buffer, while untagged async timeouts clearing a held + snapshot can clobber a *subsequent* `?2026` batch. On `resize()`, cropping + rows without rejoining soft-wrapped (`wrapped=True`) primary lines breaks + shell prompts and wrapped CLI output compared to `tmux` and `Ghostty`. + +## Decision + +1. **Universal 0-based `(row, col)` order**: + - Every constructor, helper, and `resize()` method accepts keyword-only + `(*, rows: int = 24, cols: int = 80)`. Zero `(col, row)` types exist in + `libvt`; `Terminal.from_size(os.terminal_size)` converts `os.terminal_size` + (`columns`, `lines`) explicitly. + - `Screen` stores `_cur_row: int`, `_cur_col: int`, `_pending_wrap: bool`, + `_cur_visible: bool`, `_cur_shape: CursorShape`, and `_cur_blinking: bool` + as scalars on the hot path, materializing a frozen `Cursor` dataclass on + demand in `@property def cursor`. + - Indexing uses NumPy-style 2D syntax on `Terminal`, `Screen`, and + `Snapshot`: `term[row] -> RowView`, `term[row, col] -> Cell`, and + `term[r1:r2, c1:c2] -> RegionView` (supporting negative indices such as + `term[-1]` for status lines). + - `Profile.pending_wrap_phantom_col` + `Mode.REVERSE_WRAP` (`?45`) model + both `xterm`/`Ghostty` (`DEFAULT_PROFILE`) and `tmux` (`TMUX_PROFILE`, + where `pending_wrap` acts as phantom column `cols` on `CUB`/`BS` and `BS` + at column `0` reverse-wraps across `wrapped` lines). +2. **Copy-on-write `?2026` render hold and generation-tagged expiry**: + - On `CSI ? 2026 h`, `Terminal` increments `_sync_generation: int` and + marks `_sync_hold_pending = True` without cloning rows immediately; only if + `term.committed` is read while `?2026` remains active (or before the first + post-hold mutation when a waiter is attached) is the pre-batch `Snapshot` + materialized, and `CSI ? 2026 l` in the same chunk skips cloning altogether. + - `term.expire_synchronized_output(sync_generation: int | None = None) -> + bool` releases a stalled `?2026` hold, clears `Mode.SYNCHRONIZED_OUTPUT`, + and emits `RenderHoldChanged(active=False, expired=True)` only when + `sync_generation` matches `_sync_generation`, preventing stale async timers + from releasing a newer frame. + - `term.feed_until(data, *, offset=0, stop=...)` bulk-scans `GROUND` and + control-string interiors (`OSC`/`DCS`/`APC`) to `\x07`/`\x1b` boundaries + and checks `not parser.utf8_pending` before reporting `StopOn.GROUND`. +3. **Primary-screen soft-wrap resize reflow (`resize(*, rows, cols, reflow=True)`)**: + - Resizing `primary` when `cols` changes and `reflow=True` rejoins + `wrapped=True` logical lines across `history + viewport` (eliding + `WidthRole.SPACER_HEAD` wrap-padding cells), re-wraps them to the new + column width while tracking cursor `(row, col)`, and pushes excess top + rows into `FrozenRow` scrollback rather than truncating bottom lines. + - Resizing `alternate` (`?1049`) crops/pads in place without reflow, matching + full-screen TUI `SIGWINCH` redraw expectations; when `Mode.IN_BAND_RESIZE` + (`?2048`) is enabled, `resize()` also queues `CSI 48 ; rows ; cols ; 0 ; 0 t` + and emits `InBandResize`. + +## Alternatives considered + +- **Positional `Terminal(80, 24)` or `Terminal(columns=80, rows=24)`**: Rejected + because mixing `(X, Y)` construction with `[row, col]` indexing invites silent + axis transposition. +- **Exposing four `CoordSpace` enums and `StaleGridRefError` cell handles**: + Rejected because immutable `Cell` values, `Snapshot`, and `term.history` + provide safe inspection without runtime borrow-checker exceptions in Python. + +## Consequences + +### Positive + +- Eliminating per-character `Cursor` allocation and `feed_until` 1-byte slicing + removes the primary pure-Python CPU bottlenecks. +- Primary-screen `resize()` matches `tmux` and `Ghostty` soft-wrap reflow. +- Generation-tagged `?2026` expiry eliminates async timer races. + +### Tradeoffs + +- `reflow=True` unpacks wrapped lines during `cols` changes (`O(history + rows)`), + which callers can bypass with `reflow=False` when batch-resizing. + +### Risks + +- Wide characters landing on `cols - 1` during reflow. Mitigation: emit + `SPACER_HEAD` at `cols - 1` and wrap the 2-column glyph cleanly to column `0` + of the next reflowed row. diff --git a/docs/project/adr/0005-utf8-c1-isolation-and-unicode-17-grapheme-width.md b/docs/project/adr/0005-utf8-c1-isolation-and-unicode-17-grapheme-width.md new file mode 100644 index 0000000..46441bf --- /dev/null +++ b/docs/project/adr/0005-utf8-c1-isolation-and-unicode-17-grapheme-width.md @@ -0,0 +1,105 @@ +(adr-utf8-and-unicode-17)= + +# ADR 0005: UTF-8/C1 isolation, grapheme caps, and Unicode 17 two-stage table + +## Status + +Accepted. 2026-11-21. + +## Context + +Adversarial testing and differential fuzzing uncovered four Unicode and byte +framing hazards in terminal emulators: + +1. **UTF-8 continuation `0x9C` vs 8-bit `C1` `ST` escape-injection breakout**: + In UTF-8, valid multi-byte characters including `“` (`U+201C` = + `\xe2\x80\x9c`), `本` (`U+672C` = `\xe6\x9c\xac`), `Ü` (`\xc3\x9c`), and `😜` + (`\xf0\x9f\x98\x9c`) contain byte `0x9C`. Treating raw `0x9C` as 8-bit + String Terminator (`ST`) inside `OSC`, `DCS`, or `APC` strings truncates + non-ASCII titles/hyperlinks mid-codepoint and executes the remaining payload + directly in `GROUND` state — enabling escape-sequence injection past callers + that filter `\x07` and `\x1b`. +2. **Incomplete UTF-8 ordering before C0 controls and combining-mark + teleportation**: Flushing incomplete UTF-8 lead bytes only on `ESC` (and not + C0 controls like `\n` or `\r`) emits `U+FFFD` on the wrong line, while + retaining `_last_printed_pos` across cursor movements (`CUP`, `CUB`, `LF`), + erases, scrolls, or `?1049` switches causes subsequent combining marks to + mutate a stale cell elsewhere on screen. +3. **Single-cell combining-mark DoS ("grapheme bomb")**: Appending combining + marks without a per-cell codepoint cap or scanning the growing cluster string + on every mark causes quadratic CPU freeze (`10+ s` on 200 KB of `U+0301`) + and multi-megabyte single-cell strings. +4. **Unicode version drift across Python 3.12-3.15 and missing UAX #29 rules**: + Python's `unicodedata` module bundles Unicode 15.0 in 3.12, 15.1 in 3.13, + 16.0 in 3.14, and 17.0 in 3.15, and lacks `Extended_Pictographic`, + `Regional_Indicator` pair clustering (`🇯🇵`, `🇺🇸`), and UAX #29 `GB9c` Indic + `InCB` (`Linker` / `Consonant` / `Extend`) properties needed for DEC mode + `?2027`. + +## Decision + +1. **7-bit string termination by default in UTF-8 streams (`libvt.parser`)**: + - `Parser(c1_controls: bool = False)` ignores raw `0x80..0x9F` 8-bit `C1` + bytes as control introducers/terminators unless `c1_controls=True` is + explicitly requested for legacy 8-bit Latin-1 streams. `OSC` terminates on + `BEL` (`0x07`) or 7-bit `ESC \` (`0x1B 0x5C`), and `DCS`/`APC`/`SOS`/`PM` + terminate strictly on `ESC \`, matching `tmux` (`input.c`) and `Ghostty`. + - Incomplete UTF-8 sequences flush `U+FFFD` *before* executing any C0 + control (`< 0x20`), `ESC`, `CAN` (`0x18`), or `SUB` (`0x1A`). + - A second `ESC` inside `ESCAPE` when `_return_from_esc_st` is set aborts + the pending control string cleanly before entering `ESCAPE` so `ESC ESC \` + never dispatches a cancelled `OSC`. +2. **Strict `_last_printed_pos` invalidation and `O(1)` combining cap**: + - Any cursor motion, C0 execution, erase, scroll, resize, reset, or screen + switch clears `_last_printed_pos = None`. + - `Terminal` tracks `_cluster_codepoints: int` and enforces + `Limits.max_grapheme_codepoints` (default `32`), dropping excess zero-width + extenders in `O(1)` time without re-scanning the cluster string. + - When `VS16` (`\ufe0f`) widens a 1-column base glyph at `col == right` + (right margin), `Terminal` replaces `col` with `SPACER_HEAD` (`""`), + soft-wraps to the next line, and writes the widened 2-column cluster at + `left` (`col 0`). `VS15` (`\ufe0e`) narrows default-wide emoji to `1` + column under `?2027`. +3. **Generated two-stage Unicode 17.0 block table (`libvt._ucd`)**: + - `scripts/generate_ucd.py` compiles Unicode 17.0 East Asian Width, + `General_Category`, `Extended_Pictographic`, `Regional_Indicator`, + variation selectors, and `InCB` (`Consonant`, `Linker`, `Extend`) into a + compact zlib-compressed base85 2-stage 256-codepoint block table in + `libvt._ucd` (`stage2[(stage1[cp >> 8] << 8) | (cp & 0xFF)]`, `~90 KiB` + unpacked `bytes` in RAM, zero runtime dependencies). + - Python 3.12, 3.13, 3.14, and 3.15 therefore compute identical cell widths + and UAX #29 `?2027` cluster boundaries (`GB9`, `GB9a`, `GB9c` Indic + conjuncts, `GB11` ZWJ pictographics, and `GB12`/`GB13` Regional Indicator + pairs). + +## Alternatives considered + +- **Calling stdlib `unicodedata` directly at runtime**: Rejected because emoji + and Indic conjunct properties (`Extended_Pictographic`, `InCB`) are absent + from `unicodedata` in Python 3.12-3.14, and Unicode table versions drift + across interpreter versions. +- **Runtime `wcwidth` / `grapheme` PyPI dependency**: Violates ADR 0001's + `dependencies = []` invariant. + +## Consequences + +### Positive + +- UTF-8 titles, hyperlinks, and status messages containing `0x9C` continuation + bytes never break out of `OSC`/`DCS`/`APC` framing. +- Hostile combining-mark floods stay bounded at `<= 32` codepoints per cell in + `O(1)` time per byte. +- Flag emoji (`🇯🇵`), ZWJ sequences (`🧑‍🌾`), variation selectors (`❤️`), and + Devanagari conjuncts cluster identically on Python 3.12 through 3.15. + +### Tradeoffs + +- `src/libvt/_ucd.py` embeds `~14 KiB` of compressed base85 lookup data, + regenerated via `scripts/generate_ucd.py` when upgrading Unicode versions. + +### Risks + +- BiDi override characters (`U+202A..U+202E`, `U+2066..U+2069`) spoofing + visual test diagnostics. Mitigation: `libvt._ucd.sanitize_terminal_text()` + escapes C0, C1, and BiDi override codepoints in diagnostic views and rejects + them in `OSC 7501` status fields. diff --git a/docs/project/adr/0006-charset-designations-and-single-truth-mode-reconciliation.md b/docs/project/adr/0006-charset-designations-and-single-truth-mode-reconciliation.md new file mode 100644 index 0000000..99c6d3d --- /dev/null +++ b/docs/project/adr/0006-charset-designations-and-single-truth-mode-reconciliation.md @@ -0,0 +1,95 @@ +(adr-charsets-and-mode-truth)= + +# ADR 0006: G0-G3 charsets, selective erase, and single-truth mode reconciliation + +## Status + +Accepted. 2026-11-21. + +## Context + +Differential testing against `tmux` and `ncurses` applications exposed three +classic VT100/VT420 gaps that break real-world terminal UIs even when modern +sequences work: + +1. **DEC Special Graphics (`ESC ( 0` / `SO` / `SI`)**: `tmux` (`tty-acs.c`), + `ncurses`, `dialog`, `make menuconfig`, and `htop` designate `G0` or `G1` as + DEC Special Graphics (`0`) and print `l q k x m j w u t v n` to draw + `┌ ─ ┐ │ └ ┘ ┬ ┤ ├ ┴ ┼`. Dropping charset designations renders literal + `lqqqk` ASCII letters instead of box-drawing glyphs. +2. **Tabulation and selective erase**: `CBT` (`CSI Ps Z` backward tab) and + `CHT` (`CSI Ps I` forward tab) are standard horizontal cursor primitives, + and VT220/VT420 applications use `DECSCA` (`CSI Ps " q`) with `DECSED` + (`CSI ? Ps J`) and `DECSEL` (`CSI ? Ps K`) to clear unprotected fields while + preserving protected form labels. Kitty-compatible shells also emit + `CSI 22 J` to push the visible screen into scrollback before clearing. +3. **Alternate-screen `DECRQM` desynchronization (`?47` / `?1047` / `?1049`)**: + Tracking `ALT_SCREEN_47`, `ALT_SCREEN_1047`, and `ALT_SCREEN` (`?1049`) as + independent booleans in `ModeState` causes `CSI ? 47 h` followed by + `CSI ? 1049 l` (or `?1049h` followed by `?47l`) to return to the primary + screen while `CSI ? 47 $ p` falsely replies `1` (`SET`) instead of `2` + (`RESET`), and `Formatter(OutputFormat.VT)` re-emits `\x1b[?47h`! + +## Decision + +1. **Per-screen `G0`-`G3` charset slots and shifts (`libvt.terminal`)**: + - Track four charset slots (`G0`, `G1`, `G2`, `G3`, each `'B'` US-ASCII, + `'0'` DEC Special Graphics, or `'A'` UK), active locking-shift slot + `gl: int` (`0` via `SI` `0x0F`, `1` via `SO` `0x0E`, `2` via `LS2` + `ESC n`, `3` via `LS3` `ESC o`), and one-shot single shift + `single_shift: int | None` (`2` via `SS2` `ESC N`, `3` via `SS3` `ESC O`). + - Designate slots via `ESC ( F` (`G0`), `ESC ) F` (`G1`), `ESC * F` (`G2`), + and `ESC + F` (`G3`). When the active slot for the next printed character + is `'0'`, map `0x5F..0x7E` through the 32-entry DEC Special Graphics table + (`┌`, `─`, `┐`, `│`, `└`, `┘`, `┼`, `◆`, `▒`, `°`, `±`, `≤`, `≥`, `π`, + `≠`, `£`, `·`, etc.) before writing to `_Row`. + - Save and restore `(g_sets, gl)` inside `_SavedCursor` (`DECSC` / `DECRC` / + `?1049`) and reset to `('B', 'B', 'B', 'B'), gl=0` on `DECSTR` and `RIS`. +2. **Tab navigation, selective erase, and scroll-clear**: + - Implement `CHT` (`CSI Ps I`: advance `Ps` tabstops clamped to right margin) + and `CBT` (`CSI Ps Z`: retreat `Ps` tabstops clamped to left margin, + clearing `pending_wrap`). Keep sorted tabstops cached on `Screen`. + - Implement `DECSCA` (`CSI 0 " q` / `CSI 2 " q` unprotected, `CSI 1 " q` + protected) stored on `_CellExt.protected`, respected by `DECSED` + (`CSI ? Ps J`) and `DECSEL` (`CSI ? Ps K`) while `ED` / `EL` erase + unconditionally. + - Support `CSI 22 J` (push non-blank primary viewport lines into `FrozenRow` + scrollback before clearing the viewport). +3. **Single-truth alternate-screen reconciliation (`libvt.modes`)**: + - `ScreenSet.active_is_alt` is the sole source of truth for whether the + alternate buffer is active. Exiting via *any* of `?47l`, `?1047l`, or + `?1049l` clears all three alt-screen mode bits in `ModeState`, and + `ModeState.decrpm()` reconciles `?47`, `?1047`, and `?1049` against + `active_is_alt` so `DECRQM` and `Formatter(OutputFormat.VT)` never report + stale alt-screen state. + +## Alternatives considered + +- **Ignoring `ESC ( 0` in UTF-8 mode**: Rejected because `ncurses`, `dialog`, + and `tmux` still emit `ESC ( 0` whenever `acsc` terminfo capabilities are + active. +- **Reporting `SET` for `?47` whenever `?1049` is active**: Keep `?1049` as the + canonical bit set when entering via `?1049h` (and `?47` when entering via + `?47h`), while clearing *all* three bits whenever *any* exit sequence returns + `active_is_alt` to `False`. + +## Consequences + +### Positive + +- `ncurses` and `tmux` ACS box-drawing borders render as real Unicode box + characters (`┌───┐`) in `term.text` and `assert_screen()`. +- `?47` / `?1047` / `?1049` transitions never leave ghost mode flags in + `DECRQM` replies or `VT` snapshot exports. + +### Tradeoffs + +- `on_print`'s ASCII slice fast path runs unhindered when the active charset is + `'B'` (99%+ of traffic) and translates via `str.translate` when `'0'` or `'A'` + is active. + +### Risks + +- Applications leaving `SO` (`0x0E` -> `G1 = '0'`) latched after crashing. + Mitigation: `DECSTR` (`CSI ! p`), `RIS` (`ESC c`), and `sgr0` (`ESC ( B` + emitted by `tput sgr0`) restore `G0` US-ASCII. diff --git a/docs/project/adr/0007-rex-osc-7501-program-status-and-semantic-prompts.md b/docs/project/adr/0007-rex-osc-7501-program-status-and-semantic-prompts.md new file mode 100644 index 0000000..e65eeaf --- /dev/null +++ b/docs/project/adr/0007-rex-osc-7501-program-status-and-semantic-prompts.md @@ -0,0 +1,110 @@ +(adr-osc-7501-and-prompts)= + +# ADR 0007: Rex OSC 7501 program status, semantic prompts, and host queries + +## Status + +Accepted. 2026-11-21. + +## Context + +Modern CLI tools, build runners, and AI coding agents report structured task +progress via the Program Status protocol (`OSC 7501`), supported in `tmux` +([`input.c` at `cce5f10`](https://github.com/tmux/tmux/blob/cce5f10/input.c)) +and `Ghostty` / `libghostty-vt` +([`terminal.zig` at `5b0690d`](https://github.com/ghostty-org/ghostty/blob/5b0690d/src/terminal/c/terminal.zig)), +alongside FinalTerm / shell-integration prompt markers (`OSC 133`), ConEmu/OSC +`9;4` progress bars, `OSC 7` working-directory notifications, `OSC 52` +clipboard writes, and startup capability queries (`XTVERSION`, `DECRQSS`, +`XTGETTCAP`, `OSC 10/11;?`, `?2031` / `CSI ? 996 n`). + +Upstream sources exhibit a concrete behavioral divergence on the `OSC 7501 ; ?` +capability query: + +- `tmux` (`cce5f10`) replies unconditionally with bare `"\033]7501;?\033\\"`. +- Full Rex `OSC 7501` registries advertise supported states and kinds: + `"\033]7501;?:states=idle,working,done,blocked,error:kinds=permission,question,auth\033\\"`. +- `libghostty-vt` (`5b0690d`) suppresses the `OSC 7501 ; ?` reply unless a + `program_status` effect consumer is attached, so applications avoid sending + status updates nobody observes. + +## Decision + +1. **Spec-compliant `ProgramStatusStore` (`libvt.status`)**: + - Enforce wire payload ceiling `<= 4,096` bytes before parsing. + - Parse colon-delimited `[a-z]{1,16}=value` pairs: + - `state`: `idle | working | done | blocked | error | clear` (required on + non-query payloads). + - `id`: optional slash-delimited hierarchical task identifier (`<= 128` + bytes, `<= 8` `/` segments, `[A-Za-z0-9_.-]` segments; `""` = root). + - `kind`: optional `permission | question | auth` (valid with + `state=blocked`). + - `progress`: optional integer `0..100`. + - `app`: optional `[A-Za-z0-9_.+-]{1,32}`, inheriting `effective_app` from + nearest ancestor `id` prefix when omitted on child tasks. + - `title`: optional base64-encoded UTF-8 (`<= 256` encoded / `<= 192` + decoded bytes); `msg`: optional base64-encoded UTF-8 (`<= 2,732` encoded + / `<= 2,048` decoded bytes). Reject malformed base64, invalid UTF-8, C0 + controls (`< 0x20` except `\t` in `msg`), `DEL`/C1 (`0x7F..0x9F`), and + Unicode BiDi overrides. + - `state=clear` removes `id` and all `id/*` descendants (when `id == ""`, + clears the entire store). Total active records stay bounded by + `Limits.max_status_records` (`64`). + - Expose `term.program_status` (most urgent active `ProgramStatus` ordered + `blocked > error > working > done > idle`, or root record) and + `term.program_statuses -> dict[str, ProgramStatus]`. + - **Consumer-gated `OSC 7501 ; ?` reply**: Reply only when + `Policy.allow_program_status_query` is `True` *or* an event consumer + (`on_event` or `record_events=True`) is attached (matching `libghostty-vt` + `5b0690d`), formatting the capability payload from + `Profile.osc_7501_capabilities` (full `states=...:kinds=...` on + `DEFAULT_PROFILE`, bare `?` on `TMUX_PROFILE`) and mirroring the incoming + `BEL` (`\x07`) vs `ST` (`\x1b\\`) terminator. + - **Lifecycle and `OSC 9;4` fallback**: Map `OSC 9;4;st;prog` into synthetic + root status until the first native `OSC 7501` arrives (re-enabled on + `RIS`). On `OSC 133;A` prompt start (ignoring `k=s` secondary continuation + prompts) or `term.notify_process_exit()`, prune transient `working`, + `blocked`, and `idle` entries while retaining `done` and `error`; survive + `DECSTR` soft reset and clear all records on `RIS`. +2. **Monotonic `OSC 133` prompt zones and host queries (`libvt.terminal`)**: + - Store `PromptZone(kind: PromptKind, row: int, abs_row: int, col: int, + exit_code: int | None)` in a `collections.deque` bounded by + `Limits.max_prompt_zones` (`1,024`), updating viewport `row` via + `abs_row - scr.scrolled_total` so scrolling never desyncs prompt zones. + - Support `OSC 7` and `OSC 9;9` (`term.cwd` + `WorkingDirectoryChanged`), + `OSC 52` write (`ClipboardWrite` when `Policy.allow_clipboard_write` or + recorded as event; `OSC 52 ; c ; ?` denied unless + `Policy.allow_clipboard_read`), `XTVERSION` (`CSI > q` -> `DCS > | ... ST`), + `DECRQSS` (`DCS $ q ... ST` for `m` SGR, `r` `DECSTBM`, `s` `DECSLRM`, + ` q` `DECSCUSR`, `"q` `DECSCA`), `XTGETTCAP` (`DCS + q ST` for + `TN`/`Co`/`RGB`/`Smulx`), `OSC 10;?` / `OSC 11;?` foreground/background + queries, `?2031` + `CSI ? 996 n` color-scheme DSR, and `DCS tmux; ESC ESC + ... ST` passthrough unwrapping (gated by `Policy.unwrap_tmux_passthrough`). + +## Alternatives considered + +- **Simplified `OSC 7501;value;progress` string split**: Rejected because it is + wire-incompatible with `tmux`, `Ghostty`, and Rex CLI emitters. +- **Unconditional `OSC 7501 ; ?` reply when no consumer is listening**: + Rejected in favor of `libghostty-vt`'s consumer/policy gate so passive text + scrapers do not solicit unused status traffic. + +## Consequences + +### Positive + +- `libvt` interoperates out of the box with `tmux` 3.6+/3.8+, `Ghostty`, and + CLI tools emitting Rex `OSC 7501`, `OSC 9;4`, and `OSC 133`. +- Startup capability handshakes (`tmux attach`, Neovim, Fish, Helix) complete + immediately via `drain_replies()` without 1-2 second query timeouts. + +### Tradeoffs + +- `ProgramStatusStore` validates base64 and UTF-8 bounds eagerly on `OSC 7501` + frames (`<= 4 KiB`), dropping non-conformant fields safely. + +### Risks + +- Untrusted PTY output flooding `OSC 133;A` or `OSC 7501` unique IDs. + Mitigation: `Limits.max_prompt_zones = 1_024` (`deque` FIFO) and + `Limits.max_status_records = 64`. diff --git a/docs/project/adr/0008-mode-aware-input-encoding-and-paste-safety.md b/docs/project/adr/0008-mode-aware-input-encoding-and-paste-safety.md new file mode 100644 index 0000000..b00f73b --- /dev/null +++ b/docs/project/adr/0008-mode-aware-input-encoding-and-paste-safety.md @@ -0,0 +1,96 @@ +(adr-input-encoding)= + +# ADR 0008: Mode-aware input encoding, Kitty keyboard stacks, and paste safety + +## Status + +Accepted. 2026-11-21. + +## Context + +Driving interactive PTY sessions (`tmux`, shells, editors, modal TUIs) requires +the outbound half of the terminal contract: encoding structured key, mouse, +focus, and paste events into the exact byte sequences negotiated by the child +application's active modes (`DECCKM` `?1`, mouse `?1000`/`?1002`/`?1003`/`?1006` +/`?1016`, focus `?1004`, bracketed paste `?2004`, and the Kitty Keyboard +Protocol `CSI u`). + +Two defects commonly break terminal input encoders: + +1. **Shared primary/alternate Kitty keyboard state**: Full-screen TUIs push + Kitty keyboard flags (`CSI > 1 u`) on the `?1049` alternate screen and crash + without popping (`CSI < u`); sharing one stack corrupts primary-shell key + encoding after `?1049l`. Furthermore, unprefixed `CSI u` is `SCORC` (restore + cursor) and MUST NOT be confused with `CSI ? u` / `CSI > u` / `CSI < u` / + `CSI = u`. +2. **Single-pass `.replace("\x1b[201~", "")` bracketed-paste RCE bypass**: + Sanitizing pasted text with `text.replace("\x1b[201~", "")` stitches + `"\x1b[20\x1b[201~1~; id\r"` directly back into `"\x1b[201~; id\r"`, + breaking out of bracketed paste and executing arbitrary shell commands! It + also misses 8-bit `CSI` (`\x9b201~`) and raw `\r`/`\n` command execution + when `?2004` bracketed paste is disabled. + +## Decision + +Provide a pure, zero-dependency `libvt.input` module integrated with +`Terminal.encode(event: InputEvent) -> bytes`: + +1. **Typed input events (`libvt.input`)**: + - `KeyEvent(key: str, modifiers: KeyMod = KeyMod.NONE, action: KeyAction = + KeyAction.PRESS, text: str = "")` with `KeyEvent.parse("ctrl+shift+p")` + shorthand. + - `MouseEvent(button: MouseButton, action: MouseAction, row: int, col: int, + modifiers: KeyMod = KeyMod.NONE, pixel_x: int = 0, pixel_y: int = 0)` using + 0-based `(row, col)` matching `Terminal`. + - `FocusEvent(focused: bool)` (`\x1b[I` / `\x1b[O` when `?1004` is set, else + `b""`). + - `PasteEvent(text: str)`. +2. **Independent Primary and Alternate Kitty keyboard stacks**: + - `ScreenSet` maintains separate 8-entry (`Limits.max_keyboard_stack`) + `KittyKeyboardStack` instances on `primary` and `alternate`. + - `CSI > flags u` pushes `flags`, `CSI < count u` pops `count` entries, + `CSI = flags ; mode u` sets/ORs/clears `flags` (`mode` `1`=`set`, `2`=`or`, + `3`=`not`), and `CSI ? u` queues `b"\x1b[?" + str(flags) + b"u"` into + `drain_replies()`. Unprefixed `CSI u` remains `SCORC`. + - `DECSTR` and `RIS` clear the active (or both) keyboard stacks. + - When active `KittyKeyboardFlags` is non-zero, `encode_input` encodes + disambiguated `CSI codepoint ; modifiers [: event_type] u` sequences; + otherwise it encodes legacy xterm / `DECCKM` (`\x1bOA` vs `\x1b[A`) bytes. +3. **Fail-closed `encode_paste()` (`UnsafePasteError`)**: + - By default (`sanitize=False`), `encode_paste(text, *, bracketed: bool)` + raises `UnsafePasteError(LibVtError)` if `text` contains `ESC` (`\x1b`), + 8-bit `C1` (`\x80..\x9f`, including `\x9b`), `NUL` (`\x00`), `DEL` + (`\x7f`), or C0 controls other than `\t` and (when `bracketed=True`) `\n` + / `\r`. When `bracketed=False`, `\r` and `\n` also raise `UnsafePasteError` + so multi-line paste never executes unbracketed shell lines silently. + - When callers explicitly opt into `sanitize=True`, all C0/C1/`ESC`/`DEL` + codepoints are stripped character-by-character in a single pass over + codepoints (never substring `.replace`), which cannot re-stitch `\x1b[201~`. + +## Alternatives considered + +- **Silent `.replace("\x1b[201~", "")` sanitization**: Rejected due to the + nested-substring stitching exploit (`"\x1b[20\x1b[201~1~"` -> `"\x1b[201~"`). +- **Encoding mouse events with 1-based `(x, y)` coordinates**: Rejected by ADR + 0004; `MouseEvent(row=0, col=0)` stays 0-based `(row, col)` in Python and adds + `+ 1` on the wire (`\x1b[ `Registry` -> `Command` objects degrades +throughput by `4-8x`. + +## Decision + +Keep hot-path emulation and cold-path sequence disassembly cleanly separated: + +1. **Cold-path `libvt.codec` (`explain` and `format_explain`)**: + - `explain(data: Buffer | str) -> tuple[ExplainedSpan, ...]` drives `Parser` + with a cold-path `_ExplainSink` and maps each action (`Print`, `Execute`, + `EscDispatch`, `CsiDispatch`, `OscDispatch`, `DcsDispatch`, `ApcDispatch`) + through compact lookup tables to produce frozen `ExplainedSpan(kind, + mnemonic, summary, raw)` records (e.g. `CSI`, `"DECSET"`, + `"?2026 (SYNCHRONIZED_OUTPUT) = set"`). + - `format_explain(data: Buffer | str) -> str` formats one human-readable + line per span for terminal debugging and pytest failure reports. +2. **Zero-dependency CLI (`src/libvt/__main__.py`)**: + - `python -m libvt explain` reads stdin (or a file path) and prints + `format_explain` output. + - `python -m libvt render [--rows 24] [--cols 80]` renders final plain-text + screen state. + - `python -m libvt strip` strips VT escape sequences from stdin/file. +3. **Hot path untouched**: + - `Terminal.feed()` never imports `libvt.codec` and never instantiates + `ExplainedSpan` objects. + +## Alternatives considered + +- **Unified hot/cold `@csi` `Command` registry**: Rejected because allocating a + `Command` dataclass per `SGR` or `CUP` sequence penalizes every `Terminal.feed` + call for metadata only humans read during debugging. +- **Registering a global `vt` console-script binary in `[project.scripts]`**: + Omitted to avoid colliding with external `vt` binaries on user `PATH`; + `python -m libvt` is zero-collision and always matches the active virtualenv. + +## Consequences + +### Positive + +- Developers and pytest failure hooks (`FlightRecorder`) disassemble arbitrary + VT traces with `libvt.explain()` or `python -m libvt explain` with zero + impact on `Terminal.feed()` speed. + +### Tradeoffs + +- Sequence mnemonics in `libvt.codec` are maintained alongside `Terminal`'s + dispatch handlers, tested for parity in `tests/test_codec.py`. + +### Risks + +- Raw untrusted bytes inside `format_explain` emitting live escape sequences to + the developer's own terminal. Mitigation: `format_explain` escapes all C0, + C1, `ESC`, and BiDi override characters in both `raw` and `summary` columns. diff --git a/docs/project/adr/0010-transport-only-asyncio-and-diagnostic-pytest-plugin.md b/docs/project/adr/0010-transport-only-asyncio-and-diagnostic-pytest-plugin.md new file mode 100644 index 0000000..9b995b5 --- /dev/null +++ b/docs/project/adr/0010-transport-only-asyncio-and-diagnostic-pytest-plugin.md @@ -0,0 +1,100 @@ +(adr-asyncio-and-pytest-plugin)= + +# ADR 0010: Transport-only asyncio/PTY adapters and diagnostic pytest plugin + +## Status + +Accepted. 2026-11-21. + +## Context + +`libvt` ships an `asyncio` / POSIX PTY transport layer (`libvt.aio`), visual +assertion helpers (`libvt.testing`), and a `pytest11` plugin +(`libvt.pytest_plugin`). Four concrete failure modes emerged during review and +empirical testing: + +1. **Import pollution**: Importing `asyncio`, `pty`, or `pytest` inside + `libvt/__init__.py` slows every `import libtmux` call. +2. **Fixture namespace collisions**: Auto-discovered `pytest11` plugins that + register unprefixed fixture names (`terminal`, `spawn`, `shell`) collide + with fixtures in `pytest-shell-utilities`, `pexpect`, and downstream test + suites, whereas splitting a separate `pytest-vt` PyPI package creates + cross-package version skew relative to `libtmux.pytest_plugin`. +3. **Wide-glyph box misalignment and terminal-escape injection in failure + diffs**: Padding `format_screen_box` rows with `str.ljust(w)` counts Python + codepoints instead of terminal display columns, pushing right `│` borders + out of alignment on every 2-column CJK/emoji character (`"日本"`), while + unescaped C0/C1/BiDi characters in failure messages can corrupt the test + runner's terminal. +4. **POSIX vs Windows PTY scope**: Both `libtmux` and `tmuxp` declare + `Operating System :: POSIX` and `Operating System :: MacOS :: MacOS X` + classifiers only (`tmux` itself is POSIX-only). Adding a `pywinpty` C/Rust + ConPTY dependency for Windows subprocess PTYs would break ADR 0001's pure + `py3-none-any.whl` zero-dependency guarantee. + +## Decision + +1. **Strict import isolation (`libvt/__init__.py`)**: + - `import libvt` never loads `asyncio`, `pty`, `termios`, or `pytest` + (enforced by a clean-interpreter subprocess test in `tests/test_libvt.py`). +2. **`AsyncTerminalStream` and POSIX `open_pty()` (`libvt.aio`)**: + - `AsyncTerminalStream` drives `Terminal` from `(StreamReader, StreamWriter)` + pairs, flushing `drain_replies()` automatically and enforcing + `sync_timeout` via `Terminal.expire_synchronized_output(sync_gen)` in both + background-task (`async with`) and on-demand `wait_for()` modes. + - `open_pty(argv, *, rows=24, cols=80, env=None, cwd=None)` spawns a child + process attached to a stdlib `pty.openpty()` master/slave pair on POSIX, + sets `TIOCSWINSZ`, pumps output + `drain_replies()`, and exposes + `send()`, `send_key()`, `paste()`, `resize()`, and `wait_for()`. On + Windows (`sys.platform == "win32"`), `open_pty()` raises + `NotImplementedError` cleanly while the entire Sans-I/O core works + unchanged. +3. **Strictly `vt_`-prefixed, `Protocol`-typed `pytest11` plugin + (`libvt.pytest_plugin`)**: + - Register `vt_terminal`, `vt_factory` (typed via `TerminalFactory` + `t.Protocol` so static type checkers verify keyword arguments), + `vt_parser`, `vt_recorder` (`FlightRecorder`), and `vt_pty` (calling + `pytest.skip("POSIX pty required")` on `win32`), with lazy imports inside + fixture bodies. +4. **Column-exact, sanitized `assert_screen` and `FlightRecorder` + (`libvt.testing`)**: + - `format_screen_box` and `assert_screen` measure cells by terminal display + width (`WidthRole` / `display_width`), sanitize C0/C1 and BiDi overrides, + display `W` soft-wrap markers, and append `FlightRecorder` diagnostics + (cursor, active modes, `OSC 7501` status, `Parser.state`, and disassembled + recent raw bytes via `format_explain`) when a `FlightRecorder` is attached + to `Terminal`. + - `Snapshot.to_dict()` returns a deterministic JSON-compatible dictionary + for snapshot testing (`inline-snapshot` / `syrupy`). + +## Alternatives considered + +- **Unprefixed `terminal`, `spawn`, `shell` fixtures**: Rejected due to global + `pytest11` namespace collisions. +- **Separate `pytest-vt` PyPI package**: Rejected to match `libtmux.pytest_plugin` + single-package ergonomics. +- **Optional `pywinpty` dependency**: Deferred; `libtmux` and `tmuxp` target + POSIX/macOS exclusively, and keeping `dependencies = []` preserves universal + pure-Python wheels. + +## Consequences + +### Positive + +- `assert_screen` aligns CJK, emoji, and combining marks to exact terminal + columns and never leaks raw escape or BiDi spoofing sequences into pytest + logs. +- Failed async or PTY tests include the exact disassembled tail of VT bytes + that produced the mismatch. + +### Tradeoffs + +- Live subprocess `vt_pty` tests run on Linux/macOS/BSD and skip on native + Windows, whereas all in-memory `vt_terminal` / `AsyncTerminalStream` tests + run on every OS. + +### Risks + +- Leaked PTY file descriptors or child processes if a test fails mid-wait. + Mitigation: `PtySession.__aexit__` closes the master fd, terminates/reaps the + child process, and cancels the pump task inside `try / finally`. diff --git a/docs/project/adr/index.md b/docs/project/adr/index.md index 188cb2b..28c533c 100644 --- a/docs/project/adr/index.md +++ b/docs/project/adr/index.md @@ -2,6 +2,21 @@ # Architecture Decision Records -Design decisions and rationale for `libvt`. Copy `_template.md` to -`NNNN-short-slug.md` and add the new document to the table of contents -below when recording a decision. +Design decisions, protocol contracts, storage layouts, and security boundaries +for `libvt`. Copy `_template.md` to `NNNN-short-slug.md` and add the new +document to the table of contents below when recording a decision. + +```{toctree} +:maxdepth: 1 + +0001-clean-room-provenance-and-license-firewall +0002-sans-io-layers-profiles-and-closed-events +0003-two-tier-packed-viewport-and-rle-scrollback +0004-zero-based-row-col-coordinates-and-sync-stepping +0005-utf8-c1-isolation-and-unicode-17-grapheme-width +0006-charset-designations-and-single-truth-mode-reconciliation +0007-rex-osc-7501-program-status-and-semantic-prompts +0008-mode-aware-input-encoding-and-paste-safety +0009-declarative-sequence-codec-and-stream-explainer +0010-transport-only-asyncio-and-diagnostic-pytest-plugin +``` From 1f71633c3c257f7673f3ea2a2a8e8bc7f5aace39 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 21 Nov 2026 15:20:43 -0600 Subject: [PATCH 02/29] Core(feat[vt]): Add VT engine, RLE grid, and tests why: Downstream TUI and libtmux test harnesses require a clean-room MIT, zero-dependency virtual terminal with compact scrollback, Unicode 17 grapheme clustering, bidirectional query replies, mode-aware input encoding, and Rex OSC 7501 program status support. what: - Add streaming VT500 parser with 7-bit string isolation, colon SGR subparameters, DCS intermediate preservation, and tmux passthrough ESC-ESC collapsing - Add two-tier grid with lazy 64-bit inline attributes, wide-spacer boundary healing, RLE FrozenRow scrollback, and primary resize reflow - Add Unicode 17.0.0 two-stage width and UAX #29 clustering tables - Add Terminal, Profile/Policy/Limits, ?2026 CoW stepping, Rex OSC 7501 store, OSC 133/7/52, DECRQM/DECRQSS/XTGETTCAP, and Formatter - Add mode-aware input encoders, KittyKeyboardStack, and fail-closed bracketed paste validation - Add codec explainer, CLI, AsyncTerminalStream, POSIX open_pty, protocol-typed pytest fixtures, and 400-trial property fuzz tests --- conftest.py | 6 +- scripts/generate_ucd.py | 401 +++++ src/libvt/__init__.py | 190 +++ src/libvt/__main__.py | 54 + src/libvt/_grid.py | 787 +++++++++ src/libvt/_ucd.py | 227 +++ src/libvt/aio.py | 445 +++++ src/libvt/codec.py | 232 +++ src/libvt/config.py | 174 ++ src/libvt/events.py | 352 ++++ src/libvt/exc.py | 32 + src/libvt/input.py | 529 ++++++ src/libvt/modes.py | 144 ++ src/libvt/parser.py | 1153 +++++++++++++ src/libvt/pytest_plugin.py | 144 +- src/libvt/screen.py | 927 +++++++++++ src/libvt/status.py | 372 +++++ src/libvt/style.py | 163 ++ src/libvt/terminal.py | 2587 +++++++++++++++++++++++++++++ src/libvt/testing.py | 204 +++ tests/test_aio_and_pytest.py | 141 ++ tests/test_codec_and_cli.py | 58 + tests/test_libvt.py | 48 +- tests/test_parser.py | 141 ++ tests/test_protocols_and_input.py | 209 +++ tests/test_terminal.py | 174 ++ tests/test_ucd_and_grid.py | 209 +++ 27 files changed, 10098 insertions(+), 5 deletions(-) create mode 100644 scripts/generate_ucd.py create mode 100644 src/libvt/__main__.py create mode 100644 src/libvt/_grid.py create mode 100644 src/libvt/_ucd.py create mode 100644 src/libvt/aio.py create mode 100644 src/libvt/codec.py create mode 100644 src/libvt/config.py create mode 100644 src/libvt/events.py create mode 100644 src/libvt/exc.py create mode 100644 src/libvt/input.py create mode 100644 src/libvt/modes.py create mode 100644 src/libvt/parser.py create mode 100644 src/libvt/screen.py create mode 100644 src/libvt/status.py create mode 100644 src/libvt/style.py create mode 100644 src/libvt/terminal.py create mode 100644 src/libvt/testing.py create mode 100644 tests/test_aio_and_pytest.py create mode 100644 tests/test_codec_and_cli.py create mode 100644 tests/test_parser.py create mode 100644 tests/test_protocols_and_input.py create mode 100644 tests/test_terminal.py create mode 100644 tests/test_ucd_and_grid.py diff --git a/conftest.py b/conftest.py index 4f91501..398742a 100644 --- a/conftest.py +++ b/conftest.py @@ -7,9 +7,13 @@ import pytest import libvt +from libvt.testing import assert_screen @pytest.fixture(autouse=True) def _seed_doctest_namespace(doctest_namespace: dict[str, t.Any]) -> None: - """Populate doctest globals with ``libvt``.""" + """Populate doctest globals with common ``libvt`` entry points.""" doctest_namespace["libvt"] = libvt + doctest_namespace["Terminal"] = libvt.Terminal + doctest_namespace["AnsiColor"] = libvt.AnsiColor + doctest_namespace["assert_screen"] = assert_screen diff --git a/scripts/generate_ucd.py b/scripts/generate_ucd.py new file mode 100644 index 0000000..2de3858 --- /dev/null +++ b/scripts/generate_ucd.py @@ -0,0 +1,401 @@ +"""Generate the compact two-stage Unicode 17.0 width & UAX #29 table in libvt._ucd.""" + +from __future__ import annotations + +import base64 +import pathlib +import unicodedata +import zlib + +PROP_NONE = 0 +PROP_CONTROL = 1 +PROP_EXTEND = 2 +PROP_ZWJ = 3 +PROP_REGIONAL_INDICATOR = 4 +PROP_SPACING_MARK = 5 +PROP_EXTENDED_PICTOGRAPHIC = 6 +PROP_INCB_CONSONANT = 7 +PROP_INCB_LINKER = 8 +PROP_VS15 = 9 +PROP_VS16 = 10 +PROP_EMOJI_MODIFIER = 11 + +EXT_PICT_BIT = 0x40 +BIDI_SPOOF_BIT = 0x80 + +# Unicode Indic_Conjunct_Break=Linker (Virama / Halant) codepoints across Indic scripts. +INCB_LINKERS: frozenset[int] = frozenset( + { + 0x094D, # Devanagari + 0x09CD, # Bengali + 0x0A4D, # Gurmukhi + 0x0ACD, # Gujarati + 0x0B4D, # Oriya + 0x0BCD, # Tamil + 0x0C4D, # Telugu + 0x0CCD, # Kannada + 0x0D4D, # Malayalam + 0x0DCA, # Sinhala + 0x1039, # Myanmar + 0x17D2, # Khmer + 0x1A60, # Tai Tham + 0x1B44, # Balinese + 0xA9C0, # Javanese + }, +) + +INCB_CONSONANT_RANGES: tuple[tuple[int, int], ...] = ( + (0x0915, 0x0939), + (0x0958, 0x095F), + (0x0978, 0x097F), + (0x0995, 0x09B9), + (0x09DC, 0x09DF), + (0x09F0, 0x09F1), + (0x0A15, 0x0A39), + (0x0A59, 0x0A5E), + (0x0A95, 0x0AB9), + (0x0B15, 0x0B39), + (0x0B5C, 0x0B5D), + (0x0B95, 0x0BB9), + (0x0C15, 0x0C39), + (0x0C58, 0x0C5A), + (0x0C95, 0x0CB9), + (0x0D15, 0x0D3A), + (0x0D9A, 0x0DC6), +) + +# Official Unicode Extended_Pictographic core blocks for UAX #29 GB11 ZWJ sequences. +EXT_PICT_RANGES: tuple[tuple[int, int], ...] = ( + (0x00A9, 0x00A9), + (0x00AE, 0x00AE), + (0x203C, 0x203C), + (0x2049, 0x2049), + (0x2122, 0x2122), + (0x2139, 0x2139), + (0x2194, 0x2199), + (0x21A9, 0x21AA), + (0x231A, 0x231B), + (0x2328, 0x2328), + (0x23CF, 0x23CF), + (0x23E9, 0x23F3), + (0x23F8, 0x23FA), + (0x24C2, 0x24C2), + (0x25AA, 0x25AB), + (0x25B6, 0x25B6), + (0x25C0, 0x25C0), + (0x25FB, 0x25FE), + (0x2600, 0x27BF), + (0x2934, 0x2935), + (0x2B05, 0x2B07), + (0x2B1B, 0x2B1C), + (0x2B50, 0x2B50), + (0x2B55, 0x2B55), + (0x3030, 0x3030), + (0x303D, 0x303D), + (0x3297, 0x3299), + (0x1F000, 0x1FAFF), +) + +BIDI_SPOOF: frozenset[int] = frozenset( + { + 0x061C, + *range(0x202A, 0x202F), + *range(0x2066, 0x206A), + }, +) + + +def _in_ranges(cp: int, ranges: tuple[tuple[int, int], ...]) -> bool: + return any(lo <= cp <= hi for lo, hi in ranges) + + +def _classify(cp: int) -> int: + if 0xD800 <= cp <= 0xDFFF: + return PROP_CONTROL << 2 + ch = chr(cp) + bidi_bit = BIDI_SPOOF_BIT if cp in BIDI_SPOOF else 0 + if cp < 0x20 or 0x7F <= cp < 0xA0: + return (PROP_CONTROL << 2) | bidi_bit + if 0x20 <= cp <= 0x7E: + return 1 # width=1, prop=NONE + + if cp == 0x200D: + return (PROP_ZWJ << 2) | bidi_bit + if cp == 0xFE0E: + return (PROP_VS15 << 2) | bidi_bit + if cp == 0xFE0F: + return (PROP_VS16 << 2) | bidi_bit + if 0xFE00 <= cp <= 0xFE0D or 0xE0100 <= cp <= 0xE01EF: + return (PROP_EXTEND << 2) | bidi_bit + if 0x1F1E6 <= cp <= 0x1F1FF: + # Single Regional Indicator has base width 1; pair widens to 2 under ?2027. + return 1 | (PROP_REGIONAL_INDICATOR << 2) | bidi_bit + if 0x1F3FB <= cp <= 0x1F3FF: + return 2 | (PROP_EMOJI_MODIFIER << 2) | EXT_PICT_BIT | bidi_bit + if cp in INCB_LINKERS: + return (PROP_INCB_LINKER << 2) | bidi_bit + + cat = unicodedata.category(ch) + if cat in ("Mn", "Me") or unicodedata.combining(ch): + return (PROP_EXTEND << 2) | bidi_bit + if cat == "Mc": + eaw = unicodedata.east_asian_width(ch) + w = 2 if eaw in ("W", "F") else 1 + return w | (PROP_SPACING_MARK << 2) | bidi_bit + if cat == "Cf": + return (PROP_CONTROL << 2) | bidi_bit + + eaw = unicodedata.east_asian_width(ch) + width = 2 if eaw in ("W", "F") else 1 + + if _in_ranges(cp, INCB_CONSONANT_RANGES) and cat == "Lo": + return width | (PROP_INCB_CONSONANT << 2) | bidi_bit + if _in_ranges(cp, EXT_PICT_RANGES) and cat in ("So", "Sk", "Sm", "Po"): + return width | (PROP_EXTENDED_PICTOGRAPHIC << 2) | EXT_PICT_BIT | bidi_bit + + return width | bidi_bit + + +def build_tables() -> tuple[bytes, bytes]: + """Build deduplicated stage-1 (u16 LE) and stage-2 (u8) 256-codepoint tables.""" + block_map: dict[bytes, int] = {} + stage1_indices: list[int] = [] + stage2_blocks: list[bytes] = [] + + for block_idx in range(0x110000 >> 8): + base = block_idx << 8 + block = bytes(_classify(base + offset) for offset in range(256)) + idx = block_map.get(block) + if idx is None: + idx = len(stage2_blocks) + block_map[block] = idx + stage2_blocks.append(block) + stage1_indices.append(idx) + + stage1_bytes = b"".join(idx.to_bytes(2, "little") for idx in stage1_indices) + stage2_bytes = b"".join(stage2_blocks) + return stage1_bytes, stage2_bytes + + +def render_module(stage1: bytes, stage2: bytes) -> str: + """Format ``src/libvt/_ucd.py`` source text.""" + blob = len(stage1).to_bytes(4, "little") + stage1 + stage2 + compressed = base64.b85encode(zlib.compress(blob, level=9)).decode("ascii") + lines = [compressed[i : i + 76] for i in range(0, len(compressed), 76)] + b85_literal = "\n".join(f' "{ln}"' for ln in lines) + + ver = unicodedata.unidata_version + return f'''"""Generated two-stage Unicode {ver} cell-width and UAX #29 table. + +Regenerate with ``uv run python scripts/generate_ucd.py``. +""" + +from __future__ import annotations + +import array +import base64 +import enum +import sys +import zlib + + +class WidthRole(enum.IntEnum): + """Column occupancy role of a terminal grid cell.""" + + NARROW = 0 + WIDE = 1 + SPACER_TAIL = 2 + SPACER_HEAD = 3 + + +class ClusterState(enum.IntEnum): + """Scalar UAX #29 grapheme cluster continuation state.""" + + NONE = 0 + BASE = 1 + RI_ODD = 2 + EXT_PICT = 3 + EXT_PICT_ZWJ = 4 + INCB_CONS = 5 + INCB_LINKER = 6 + + +PROP_NONE = 0 +PROP_CONTROL = 1 +PROP_EXTEND = 2 +PROP_ZWJ = 3 +PROP_REGIONAL_INDICATOR = 4 +PROP_SPACING_MARK = 5 +PROP_EXTENDED_PICTOGRAPHIC = 6 +PROP_INCB_CONSONANT = 7 +PROP_INCB_LINKER = 8 +PROP_VS15 = 9 +PROP_VS16 = 10 +PROP_EMOJI_MODIFIER = 11 + +EXT_PICT_BIT = 0x40 +BIDI_SPOOF_BIT = 0x80 + +UNICODE_VERSION = "{unicodedata.unidata_version}" + +_PACKED_B85 = ( +{b85_literal} +) + + +def _unpack_tables() -> tuple[array.array[int], bytes]: + raw = zlib.decompress(base64.b85decode(_PACKED_B85)) + s1_len = int.from_bytes(raw[:4], "little") + s1 = array.array("H") + s1.frombytes(raw[4 : 4 + s1_len]) + if sys.byteorder != "little": + s1.byteswap() + return s1, raw[4 + s1_len :] + + +_STAGE1, _STAGE2 = _unpack_tables() + + +def ucd_lookup(cp: int) -> int: + """Return packed 8-bit width and UAX #29 property entry for codepoint *cp*.""" + if 0 <= cp <= 0x10FFFF: + return _STAGE2[(_STAGE1[cp >> 8] << 8) | (cp & 0xFF)] + return PROP_CONTROL << 2 + + +def char_width(ch: str) -> int: + """Return default terminal column width (``0``, ``1``, or ``2``) for *ch*.""" + cp = ord(ch) + if 0x20 <= cp <= 0x7E: + return 1 + return ucd_lookup(cp) & 0b11 + + +def step_cluster( + prev_state: ClusterState, + cp: int, + *, + mode_2027: bool, +) -> tuple[bool, ClusterState, int]: + """Evaluate UAX #29 continuation between *prev_state* and codepoint *cp*. + + Returns + ------- + tuple[bool, ClusterState, int] + ``(extends_previous, next_state, width_override)`` where + ``width_override`` is ``-1`` (keep current cluster width), ``1`` + (narrow via ``VS15``), or ``2`` (widen via ``VS16``, emoji modifier, + ZWJ pictographic, or Regional Indicator pair). + """ + entry = ucd_lookup(cp) + prop = (entry >> 2) & 0x0F + + if prev_state != ClusterState.NONE: + if prop == PROP_EXTEND: + return True, prev_state, -1 + if prop == PROP_VS16: + return True, prev_state, (2 if mode_2027 else -1) + if prop == PROP_VS15: + return True, prev_state, (1 if mode_2027 else -1) + if mode_2027: + if prop == PROP_SPACING_MARK: + next_st = ( + prev_state + if prev_state in (ClusterState.INCB_CONS, ClusterState.EXT_PICT) + else ClusterState.BASE + ) + return True, next_st, -1 + if prop == PROP_ZWJ: + next_st = ( + ClusterState.EXT_PICT_ZWJ + if prev_state == ClusterState.EXT_PICT + else ClusterState.BASE + ) + return True, next_st, -1 + if prop == PROP_EMOJI_MODIFIER and prev_state == ClusterState.EXT_PICT: + return True, ClusterState.EXT_PICT, 2 + if prev_state == ClusterState.EXT_PICT_ZWJ and (entry & EXT_PICT_BIT): + return True, ClusterState.EXT_PICT, 2 + if prop == PROP_REGIONAL_INDICATOR and prev_state == ClusterState.RI_ODD: + return True, ClusterState.BASE, 2 + if prop == PROP_INCB_LINKER and prev_state == ClusterState.INCB_CONS: + return True, ClusterState.INCB_LINKER, -1 + if prop == PROP_INCB_CONSONANT and prev_state == ClusterState.INCB_LINKER: + return True, ClusterState.INCB_CONS, -1 + + # Start of a new base cell (or dropped standalone zero-width character). + if prop == PROP_REGIONAL_INDICATOR and mode_2027: + return False, ClusterState.RI_ODD, -1 + if entry & EXT_PICT_BIT: + return False, ClusterState.EXT_PICT, -1 + if prop == PROP_INCB_CONSONANT: + return False, ClusterState.INCB_CONS, -1 + if (entry & 0b11) == 0: + return False, ClusterState.NONE, -1 + return False, ClusterState.BASE, -1 + + +def display_width(text: str, *, mode_2027: bool = True) -> int: + """Return rendered terminal column width of *text*.""" + if text.isascii(): + return sum(1 for ch in text if " " <= ch <= "~") + total = 0 + cur_w = 0 + state = ClusterState.NONE + for ch in text: + cp = ord(ch) + if 0x20 <= cp <= 0x7E: + total += cur_w + cur_w = 1 + state = ClusterState.BASE + continue + extends, state, w_override = step_cluster(state, cp, mode_2027=mode_2027) + if extends: + if w_override != -1: + cur_w = w_override + else: + total += cur_w + cur_w = ucd_lookup(cp) & 0b11 + return total + cur_w + + +def sanitize_terminal_text(text: str) -> str: + """Escape C0, C1, ``DEL``, and BiDi override codepoints for safe display.""" + out: list[str] = [] + for ch in text: + cp = ord(ch) + if 0x20 <= cp <= 0x7E: + out.append(ch) + elif cp < 0x20 or 0x7F <= cp <= 0x9F or (ucd_lookup(cp) & BIDI_SPOOF_BIT): + out.append(f"\\\\x{{cp:02x}}" if cp <= 0xFF else f"\\\\u{{cp:04x}}") + else: + out.append(ch) + return "".join(out) + + +__all__ = [ + "BIDI_SPOOF_BIT", + "UNICODE_VERSION", + "ClusterState", + "WidthRole", + "char_width", + "display_width", + "sanitize_terminal_text", + "step_cluster", + "ucd_lookup", +] +''' + + +def main() -> int: + """Regenerate ``src/libvt/_ucd.py`` from ``unicodedata``.""" + stage1, stage2 = build_tables() + target = ( + pathlib.Path(__file__).resolve().parent.parent / "src" / "libvt" / "_ucd.py" + ) + target.write_text(render_module(stage1, stage2), encoding="utf-8") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/libvt/__init__.py b/src/libvt/__init__.py index 63cbae6..1d3facf 100644 --- a/src/libvt/__init__.py +++ b/src/libvt/__init__.py @@ -18,10 +18,190 @@ __tracker__, __version__, ) +from libvt._ucd import ( + UNICODE_VERSION, + WidthRole, + display_width, + sanitize_terminal_text, +) +from libvt.codec import ExplainedSpan, explain, format_explain +from libvt.config import ( + DEFAULT_LIMITS, + DEFAULT_POLICY, + DEFAULT_PROFILE, + TMUX_PROFILE, + XTERM_PROFILE, + ColorScheme, + Limits, + Policy, + Profile, +) +from libvt.events import ( + Bell, + ClipboardWrite, + ColorSchemeQueried, + EraseCause, + Event, + InBandResize, + KittyCommand, + KittyGraphic, + ProgramStatusChanged, + PromptKind, + PromptMark, + PromptZone, + Rect, + RenderHoldChanged, + ScreenErased, + SixelData, + SixelGraphic, + TitleChanged, + UnhandledSequence, + WorkingDirectoryChanged, +) +from libvt.exc import ( + LibVtError, + ProtocolError, + ScreenAssertionError, + TerminalTimeoutError, + UnsafePasteError, +) +from libvt.input import ( + FocusEvent, + InputEvent, + KeyAction, + KeyEvent, + KeyMod, + KittyKeyboardFlags, + MouseAction, + MouseButton, + MouseEvent, + PasteEvent, + encode_input, + encode_paste, + is_safe_paste, +) +from libvt.modes import DecrpmValue, Mode, ModeState +from libvt.parser import CsiParams, Parser, ParserState, parse_sgr +from libvt.screen import ( + BLANK_CELL, + Cell, + Cursor, + CursorShape, + RegionView, + RowRun, + RowView, + Screen, + ScreenSet, + ScrollRegion, +) +from libvt.status import BlockKind, ProgramStatus, ProgramStatusStore, StatusState +from libvt.style import ( + DEFAULT_STYLE, + AnsiColor, + Color, + Hyperlink, + IndexedColor, + RgbColor, + Style, + UnderlineStyle, +) +from libvt.terminal import ( + FlightRecorder, + Formatter, + OutputFormat, + Snapshot, + StepResult, + StopOn, + Terminal, + render, + strip, +) logging.getLogger(__name__).addHandler(logging.NullHandler()) __all__ = [ + "BLANK_CELL", + "DEFAULT_LIMITS", + "DEFAULT_POLICY", + "DEFAULT_PROFILE", + "DEFAULT_STYLE", + "TMUX_PROFILE", + "UNICODE_VERSION", + "XTERM_PROFILE", + "AnsiColor", + "Bell", + "BlockKind", + "Cell", + "ClipboardWrite", + "Color", + "ColorScheme", + "ColorSchemeQueried", + "CsiParams", + "Cursor", + "CursorShape", + "DecrpmValue", + "EraseCause", + "Event", + "ExplainedSpan", + "FlightRecorder", + "FocusEvent", + "Formatter", + "Hyperlink", + "InBandResize", + "IndexedColor", + "InputEvent", + "KeyAction", + "KeyEvent", + "KeyMod", + "KittyCommand", + "KittyGraphic", + "KittyKeyboardFlags", + "LibVtError", + "Limits", + "Mode", + "ModeState", + "MouseAction", + "MouseButton", + "MouseEvent", + "OutputFormat", + "Parser", + "ParserState", + "PasteEvent", + "Policy", + "Profile", + "ProgramStatus", + "ProgramStatusChanged", + "ProgramStatusStore", + "PromptKind", + "PromptMark", + "PromptZone", + "ProtocolError", + "Rect", + "RegionView", + "RenderHoldChanged", + "RgbColor", + "RowRun", + "RowView", + "Screen", + "ScreenAssertionError", + "ScreenErased", + "ScreenSet", + "ScrollRegion", + "SixelData", + "SixelGraphic", + "Snapshot", + "StatusState", + "StepResult", + "StopOn", + "Style", + "Terminal", + "TerminalTimeoutError", + "TitleChanged", + "UnderlineStyle", + "UnhandledSequence", + "UnsafePasteError", + "WidthRole", + "WorkingDirectoryChanged", "__author__", "__copyright__", "__description__", @@ -34,4 +214,14 @@ "__title__", "__tracker__", "__version__", + "display_width", + "encode_input", + "encode_paste", + "explain", + "format_explain", + "is_safe_paste", + "parse_sgr", + "render", + "sanitize_terminal_text", + "strip", ] diff --git a/src/libvt/__main__.py b/src/libvt/__main__.py new file mode 100644 index 0000000..afbaf3f --- /dev/null +++ b/src/libvt/__main__.py @@ -0,0 +1,54 @@ +"""Command-line entry point for ``python -m libvt`` (explain, render, strip).""" + +from __future__ import annotations + +import argparse +import pathlib +import sys + +from libvt.codec import format_explain +from libvt.terminal import render, strip + + +def _read_input(path: str | None) -> bytes: + if path is None or path == "-": + return sys.stdin.buffer.read() + return pathlib.Path(path).read_bytes() + + +def main(argv: list[str] | None = None) -> int: + """Run ``python -m libvt`` subcommands.""" + parser = argparse.ArgumentParser( + prog="python -m libvt", + description="Inspect, render, or strip VT byte streams.", + ) + sub = parser.add_subparsers(dest="command", required=True) + + p_explain = sub.add_parser("explain", help="Disassemble VT escape sequences") + p_explain.add_argument("file", nargs="?", default="-", help="Input file or '-'") + + p_render = sub.add_parser("render", help="Render VT stream to plain screen text") + p_render.add_argument("file", nargs="?", default="-", help="Input file or '-'") + p_render.add_argument("--rows", type=int, default=24, help="Screen rows") + p_render.add_argument("--cols", type=int, default=80, help="Screen columns") + + p_strip = sub.add_parser("strip", help="Strip VT control sequences from input") + p_strip.add_argument("file", nargs="?", default="-", help="Input file or '-'") + + args = parser.parse_args(argv) + raw = _read_input(args.file) + + if args.command == "explain": + out = format_explain(raw) + elif args.command == "render": + out = render(raw, rows=args.rows, cols=args.cols) + else: + out = strip(raw) + + if out: + sys.stdout.write(out + ("\n" if not out.endswith("\n") else "")) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/libvt/_grid.py b/src/libvt/_grid.py new file mode 100644 index 0000000..310086a --- /dev/null +++ b/src/libvt/_grid.py @@ -0,0 +1,787 @@ +"""Two-tier row storage: lazy 64-bit packed viewport ``_Row`` and RLE ``FrozenRow``. + +Bit layout of each 64-bit unsigned attribute word (``0`` == blank default cell): + +- bits ``0..24`` (25b): foreground color (``0`` default, ``1..16`` ANSI, + ``256..511`` 256-palette index, ``(1 << 24) | 0xRRGGBB`` RGB) +- bits ``25..49`` (25b): background color +- bits ``50..56`` (7b): ``bold``, ``dim``, ``italic``, ``blink``, ``reverse``, + ``hidden``, ``strikethrough`` +- bits ``57..59`` (3b): :class:`~libvt.style.UnderlineStyle` +- bits ``60..61`` (2b): :class:`~libvt._ucd.WidthRole` +- bit ``62`` (1b): ``overline`` +- bit ``63`` (1b): ``HAS_EXT`` gating sparse :class:`_CellExt` +""" + +from __future__ import annotations + +import array +from dataclasses import dataclass + +from libvt._ucd import WidthRole +from libvt.style import ( + DEFAULT_STYLE, + AnsiColor, + Color, + Hyperlink, + IndexedColor, + RgbColor, + Style, + UnderlineStyle, +) + +_COLOR_MASK = (1 << 25) - 1 +_RGB_FLAG = 1 << 24 +_IDX_BASE = 256 + +_BG_SHIFT = 25 +_BOLD_BIT = 1 << 50 +_DIM_BIT = 1 << 51 +_ITALIC_BIT = 1 << 52 +_BLINK_BIT = 1 << 53 +_REVERSE_BIT = 1 << 54 +_HIDDEN_BIT = 1 << 55 +_STRIKE_BIT = 1 << 56 +_UL_SHIFT = 57 +_UL_MASK = 0b111 +_WIDTH_SHIFT = 60 +_WIDTH_MASK = 0b11 +_WIDTH_CLEAR_MASK = ~(_WIDTH_MASK << _WIDTH_SHIFT) & ((1 << 64) - 1) +_OVERLINE_BIT = 1 << 62 +_HAS_EXT_BIT = 1 << 63 + + +@dataclass(frozen=True, slots=True) +class _CellExt: + """Sparse per-cell metadata stored only when ``HAS_EXT`` is set. + + Attributes + ---------- + underline_color : Color + Explicit underline color (``SGR 58``), if any. + hyperlink : Hyperlink | None + Active ``OSC 8`` hyperlink, if any. + protected : bool + ``DECSCA`` character-protection flag respected by ``DECSED``/``DECSEL``. + """ + + underline_color: Color = None + hyperlink: Hyperlink | None = None + protected: bool = False + + +def _pack_color(color: Color) -> int: + if color is None: + return 0 + if isinstance(color, AnsiColor): + return int(color) + 1 + if isinstance(color, IndexedColor): + return _IDX_BASE + color.index + return _RGB_FLAG | (color.r << 16) | (color.g << 8) | color.b + + +def _unpack_color(bits: int) -> Color: + if bits == 0: + return None + if bits & _RGB_FLAG: + rgb = bits & 0xFFFFFF + return RgbColor((rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF) + if bits >= _IDX_BASE: + return IndexedColor(bits - _IDX_BASE) + return AnsiColor(bits - 1) + + +def pack_pen_base(style: Style) -> int: + """Pack *style* into a 64-bit word (leaving ``WidthRole`` and ``HAS_EXT`` clear).""" + if style == DEFAULT_STYLE: + return 0 + word = _pack_color(style.fg) | (_pack_color(style.bg) << _BG_SHIFT) + if style.bold: + word |= _BOLD_BIT + if style.dim: + word |= _DIM_BIT + if style.italic: + word |= _ITALIC_BIT + if style.blink: + word |= _BLINK_BIT + if style.reverse: + word |= _REVERSE_BIT + if style.hidden: + word |= _HIDDEN_BIT + if style.strikethrough: + word |= _STRIKE_BIT + if style.underline != UnderlineStyle.NONE: + word |= (int(style.underline) & _UL_MASK) << _UL_SHIFT + if style.overline: + word |= _OVERLINE_BIT + return word + + +def make_cell_ext( + style: Style, + hyperlink: Hyperlink | None, + *, + protected: bool = False, +) -> _CellExt | None: + """Build sparse :class:`_CellExt` when needed, else return ``None``.""" + if style.underline_color is None and hyperlink is None and not protected: + return None + return _CellExt( + underline_color=style.underline_color, + hyperlink=hyperlink, + protected=protected, + ) + + +def unpack_style(word: int, ext: _CellExt | None) -> Style: + """Unpack a 64-bit cell attribute word and optional :class:`_CellExt`.""" + style_bits = word & _WIDTH_CLEAR_MASK & ~_HAS_EXT_BIT + if style_bits == 0 and (ext is None or ext.underline_color is None): + return DEFAULT_STYLE + fg = _unpack_color(word & _COLOR_MASK) + bg = _unpack_color((word >> _BG_SHIFT) & _COLOR_MASK) + ul_raw = (word >> _UL_SHIFT) & _UL_MASK + ul_color = ext.underline_color if ext is not None else None + return Style( + fg=fg, + bg=bg, + underline_color=ul_color, + bold=bool(word & _BOLD_BIT), + dim=bool(word & _DIM_BIT), + italic=bool(word & _ITALIC_BIT), + underline=UnderlineStyle(ul_raw), + blink=bool(word & _BLINK_BIT), + reverse=bool(word & _REVERSE_BIT), + hidden=bool(word & _HIDDEN_BIT), + strikethrough=bool(word & _STRIKE_BIT), + overline=bool(word & _OVERLINE_BIT), + ) + + +def unpack_width_role(word: int) -> WidthRole: + """Extract :class:`~libvt._ucd.WidthRole` from a 64-bit cell word.""" + raw = (word >> _WIDTH_SHIFT) & _WIDTH_MASK + if raw == 0: + return WidthRole.NARROW + return WidthRole(raw) + + +def raw_width_bits(word: int) -> int: + """Extract raw 2-bit width role integer without constructing an Enum.""" + return (word >> _WIDTH_SHIFT) & _WIDTH_MASK + + +@dataclass(frozen=True, slots=True) +class FrozenRow: + """Run-length-encoded immutable scrollback line. + + Attributes + ---------- + text : str + Right-trimmed rendered row text. + cols : int + Column count when the row was sealed. + runs : tuple[tuple[int, int], ...] + ``(end_col, attr_u64)`` run-length spans; ``()`` when all cells carry + attribute word ``0``. + exts : tuple[tuple[int, _CellExt], ...] + Sorted ``(col, _CellExt)`` sparse metadata pairs. + cells : tuple[str, ...] | None + Per-column cell strings up to ``used`` when the row contains wide + spacers or multi-codepoint clusters; ``None`` when ``text`` maps 1:1 + to narrow columns ``0..len(text) - 1``. + wrapped : bool + ``True`` when the row soft-wrapped onto the next row under ``DECAWM``. + """ + + text: str + cols: int + runs: tuple[tuple[int, int], ...] = () + exts: tuple[tuple[int, _CellExt], ...] = () + cells: tuple[str, ...] | None = None + wrapped: bool = False + + @property + def used(self) -> int: + """Return count of written columns in this sealed row.""" + if self.cells is not None: + return len(self.cells) + run_end = self.runs[-1][0] if self.runs else 0 + return max(len(self.text), run_end) + + def rstrip_text(self) -> str: + """Return right-trimmed row text.""" + return self.text + + def char_at(self, col: int) -> str: + """Return cell string at *col*.""" + if self.cells is not None: + return self.cells[col] if col < len(self.cells) else " " + return self.text[col] if col < len(self.text) else " " + + def attr_at(self, col: int) -> int: + """Return packed 64-bit attribute word at *col*.""" + for end_col, word in self.runs: + if col < end_col: + return word + return 0 + + def ext_at(self, col: int) -> _CellExt | None: + """Return sparse :class:`_CellExt` at *col*, if any.""" + for ext_col, ce in self.exts: + if ext_col == col: + return ce + if ext_col > col: + break + return None + + def thaw(self, target_cols: int | None = None) -> _Row: + """Materialize a mutable :class:`_Row` from this sealed line.""" + width = self.cols if target_cols is None else target_cols + row = _Row(width) + row.wrapped = self.wrapped + limit = min(self.used, width) + if limit == 0 and not self.runs: + return row + for c in range(limit): + row.chars[c] = self.char_at(c) + if self.runs: + attrs = row._ensure_attrs() + start = 0 + for end_col, word in self.runs: + stop = min(end_col, width) + for c in range(start, stop): + attrs[c] = word + if raw_width_bits(word) != 0: + row.has_wide = True + start = stop + if start >= width: + break + if width > 0 and raw_width_bits(attrs[width - 1]) == int(WidthRole.WIDE): + row.chars[width - 1] = " " + attrs[width - 1] &= _WIDTH_CLEAR_MASK + if self.exts: + row.ext = {c: ce for c, ce in self.exts if c < width} + row.used = limit + return row + + +class _Row: + """Mutableviewport row with lazy 64-bit ``array('Q')`` promotion.""" + + __slots__ = ("attrs", "chars", "ext", "has_wide", "uniform_attr", "used", "wrapped") + + def __init__(self, cols: int) -> None: + self.chars: list[str] = [" "] * cols + self.attrs: array.array[int] | None = None + self.uniform_attr: int = 0 + self.has_wide: bool = False + self.ext: dict[int, _CellExt] | None = None + self.used: int = 0 + self.wrapped: bool = False + + def _ensure_attrs(self) -> array.array[int]: + if self.attrs is None: + self.attrs = array.array("Q", [self.uniform_attr]) * len(self.chars) + return self.attrs + + def attr_at(self, col: int) -> int: + """Return 64-bit attribute word at *col*.""" + if self.attrs is None: + return self.uniform_attr + return self.attrs[col] + + def ext_at(self, col: int) -> _CellExt | None: + """Return sparse :class:`_CellExt` at *col*, if any.""" + return self.ext.get(col) if self.ext is not None else None + + def is_protected(self, col: int) -> bool: + """Return ``True`` when cell *col* carries ``DECSCA`` protection.""" + if self.ext is None: + return False + ce = self.ext.get(col) + return bool(ce is not None and ce.protected) + + def reset_blank( + self, + cols: int, + bce_word: int = 0, + bce_ext: _CellExt | None = None, + ) -> None: + """Reset this row in place for zero-allocation scroll recycling.""" + if len(self.chars) != cols: + self.chars = [" "] * cols + else: + self.chars[:] = [" "] * cols + self.attrs = None + self.uniform_attr = bce_word | (_HAS_EXT_BIT if bce_ext is not None else 0) + self.has_wide = False + if bce_ext is not None: + self.ext = dict.fromkeys(range(cols), bce_ext) + self.used = cols + else: + if self.ext is not None: + self.ext.clear() + self.used = cols if bce_word != 0 else 0 + self.wrapped = False + + def _set_raw( + self, + col: int, + ch: str, + pen_word: int, + role: WidthRole, + cell_ext: _CellExt | None, + ) -> None: + word = pen_word | (int(role) << _WIDTH_SHIFT) + if cell_ext is not None: + word |= _HAS_EXT_BIT + if self.ext is None: + self.ext = {col: cell_ext} + else: + self.ext[col] = cell_ext + elif self.ext is not None: + self.ext.pop(col, None) + if role != WidthRole.NARROW: + self.has_wide = True + self.chars[col] = ch + if self.attrs is None: + if word == self.uniform_attr: + return + self._ensure_attrs()[col] = word + else: + self.attrs[col] = word + + def _heal_wide_boundary(self, col: int) -> None: + """Clear both halves when an edit or margin boundary splits a wide glyph.""" + if not self.has_wide or self.attrs is None: + return + cols = len(self.chars) + if col < 0 or col >= cols: + return + role = raw_width_bits(self.attrs[col]) + if role == int(WidthRole.WIDE): + self.chars[col] = " " + self.attrs[col] &= _WIDTH_CLEAR_MASK + if col + 1 < cols: + self.chars[col + 1] = " " + self.attrs[col + 1] &= _WIDTH_CLEAR_MASK + elif role == int(WidthRole.SPACER_TAIL): + self.chars[col] = " " + self.attrs[col] &= _WIDTH_CLEAR_MASK + if col - 1 >= 0: + self.chars[col - 1] = " " + self.attrs[col - 1] &= _WIDTH_CLEAR_MASK + + def write_narrow( + self, + col: int, + ch: str, + pen_word: int, + cell_ext: _CellExt | None, + ) -> None: + """Write a 1-column glyph at *col*, healing any split wide cell.""" + self._heal_wide_boundary(col) + self._set_raw(col, ch, pen_word, WidthRole.NARROW, cell_ext) + self.used = max(self.used, col + 1) + + def write_spacer_head( + self, + col: int, + bce_word: int, + bce_ext: _CellExt | None, + ) -> None: + """Write ``WidthRole.SPACER_HEAD`` padding at right margin before wide wrap.""" + self._heal_wide_boundary(col) + self._set_raw(col, "", bce_word, WidthRole.SPACER_HEAD, bce_ext) + self.used = max(self.used, col + 1) + + def write_ascii_slice( + self, + col: int, + text: str, + pen_word: int, + cell_ext: _CellExt | None, + ) -> None: + """Fast-path bulk write of 1-column printable ASCII characters.""" + n = len(text) + end = col + n + if self.has_wide and self.attrs is not None: + self._heal_wide_boundary(col) + if end - 1 > col: + self._heal_wide_boundary(end - 1) + for idx in range(col, end): + if ( + raw_width_bits(self.attrs[idx]) == int(WidthRole.WIDE) + and idx + 1 >= end + and idx + 1 < len(self.chars) + ): + self.chars[idx + 1] = " " + self.attrs[idx + 1] &= _WIDTH_CLEAR_MASK + + self.chars[col:end] = list(text) + word = pen_word | (_HAS_EXT_BIT if cell_ext is not None else 0) + if self.attrs is None: + if word != self.uniform_attr: + attrs = self._ensure_attrs() + attrs[col:end] = array.array("Q", [word]) * n + else: + self.attrs[col:end] = array.array("Q", [word]) * n + + if cell_ext is not None: + if self.ext is None: + self.ext = {} + for idx in range(col, end): + self.ext[idx] = cell_ext + elif self.ext: + for idx in range(col, end): + self.ext.pop(idx, None) + + self.used = max(self.used, end) + + def write_wide( + self, + col: int, + ch: str, + pen_word: int, + cell_ext: _CellExt | None, + ) -> None: + """Write a 2-column glyph across ``col`` and ``col + 1``.""" + self._heal_wide_boundary(col) + self._heal_wide_boundary(col + 1) + self._set_raw(col, ch, pen_word, WidthRole.WIDE, cell_ext) + self._set_raw(col + 1, "", pen_word, WidthRole.SPACER_TAIL, cell_ext) + self.used = max(self.used, col + 2) + + def append_grapheme( + self, + col: int, + ch: str, + *, + width_override: int, + pen_word: int, + cell_ext: _CellExt | None, + ) -> None: + """Append zero-width or cluster-extending *ch* onto cell *col*.""" + cols = len(self.chars) + if col < 0 or col >= cols: + return + target = col + if ( + self.has_wide + and self.attrs is not None + and raw_width_bits(self.attrs[col]) == int(WidthRole.SPACER_TAIL) + and col > 0 + ): + target = col - 1 + self.chars[target] = self.chars[target] + ch + cur_role = raw_width_bits(self.attrs[target]) if self.attrs is not None else 0 + if ( + width_override == 2 + and cur_role == int(WidthRole.NARROW) + and target + 1 < cols + ): + self._heal_wide_boundary(target + 1) + attrs = self._ensure_attrs() + attrs[target] = (attrs[target] & _WIDTH_CLEAR_MASK) | ( + int(WidthRole.WIDE) << _WIDTH_SHIFT + ) + self.has_wide = True + self._set_raw(target + 1, "", pen_word, WidthRole.SPACER_TAIL, cell_ext) + self.used = max(self.used, target + 2) + elif ( + width_override == 1 + and cur_role == int(WidthRole.WIDE) + and target + 1 < cols + ): + attrs = self._ensure_attrs() + attrs[target] &= _WIDTH_CLEAR_MASK + self._set_raw(target + 1, " ", pen_word, WidthRole.NARROW, cell_ext) + + def clear_range( + self, + start: int, + end: int, + bce_word: int, + bce_ext: _CellExt | None, + *, + selective: bool = False, + ) -> None: + """Erase cells in ``[start, end)`` using background color erase (*bce*).""" + cols = len(self.chars) + lo = max(0, start) + hi = min(cols, end) + if lo >= hi: + return + + if selective and self.ext: + for c in range(lo, hi): + if self.is_protected(c): + continue + self._heal_wide_boundary(c) + self._set_raw(c, " ", bce_word, WidthRole.NARROW, bce_ext) + if bce_word != 0 or bce_ext is not None: + self.used = max(self.used, hi) + elif hi >= cols: + while ( + self.used > lo + and self.chars[self.used - 1] == " " + and self.attr_at(self.used - 1) == 0 + and self.ext_at(self.used - 1) is None + ): + self.used -= 1 + return + + if lo == 0 and hi == cols: + self.reset_blank(cols, bce_word, bce_ext) + return + + if self.has_wide: + self._heal_wide_boundary(lo) + self._heal_wide_boundary(hi - 1) + + n = hi - lo + self.chars[lo:hi] = [" "] * n + word = bce_word | (_HAS_EXT_BIT if bce_ext is not None else 0) + if self.attrs is None: + if word != self.uniform_attr: + attrs = self._ensure_attrs() + attrs[lo:hi] = array.array("Q", [word]) * n + else: + self.attrs[lo:hi] = array.array("Q", [word]) * n + + if bce_ext is not None: + if self.ext is None: + self.ext = {} + for c in range(lo, hi): + self.ext[c] = bce_ext + self.used = max(self.used, hi) + else: + if self.ext: + for c in range(lo, hi): + self.ext.pop(c, None) + if bce_word != 0: + self.used = max(self.used, hi) + elif hi >= cols: + # Clamp used to lo without erasing explicit spaces printed left of lo! + self.used = min(self.used, lo) + + def insert_blanks( + self, + col: int, + count: int, + *, + left: int, + right: int, + bce_word: int, + bce_ext: _CellExt | None = None, + ) -> None: + """Insert *count* blank cells at *col* within ``[left, right]`` (``ICH``).""" + if not (left <= col <= right) or count <= 0: + return + shift = min(count, right - col + 1) + + # Splitting a SPACER_TAIL at col orphans its WIDE head at col - 1. + if ( + self.has_wide + and self.attrs is not None + and raw_width_bits(self.attrs[col]) == int(WidthRole.SPACER_TAIL) + ): + if col > 0: + self.chars[col - 1] = " " + self.attrs[col - 1] &= _WIDTH_CLEAR_MASK + self.chars[col] = " " + self.attrs[col] &= _WIDTH_CLEAR_MASK + + # Discarding a WIDE head at right orphans its SPACER_TAIL at right + 1. + if ( + self.has_wide + and self.attrs is not None + and right + 1 < len(self.chars) + and raw_width_bits(self.attrs[right + 1]) == int(WidthRole.SPACER_TAIL) + ): + self.chars[right + 1] = " " + self.attrs[right + 1] &= _WIDTH_CLEAR_MASK + + attrs = ( + self._ensure_attrs() + if ( + self.attrs is not None + or bce_word != self.uniform_attr + or bce_ext is not None + ) + else None + ) + for dst in range(right, col + shift - 1, -1): + src = dst - shift + self.chars[dst] = self.chars[src] + if attrs is not None: + attrs[dst] = attrs[src] + if self.ext is not None: + if src in self.ext: + self.ext[dst] = self.ext[src] + else: + self.ext.pop(dst, None) + + # 3. If shifting pushed a WIDE head onto right without its tail, clear right! + if ( + self.has_wide + and attrs is not None + and raw_width_bits(attrs[right]) == int(WidthRole.WIDE) + ): + self.chars[right] = " " + attrs[right] &= _WIDTH_CLEAR_MASK + + for c in range(col, col + shift): + self._set_raw(c, " ", bce_word, WidthRole.NARROW, bce_ext) + if bce_word != 0 or bce_ext is not None or self.used > col: + self.used = min(right + 1, max(self.used + shift, col + shift)) + + def delete_cells( + self, + col: int, + count: int, + *, + left: int, + right: int, + bce_word: int, + bce_ext: _CellExt | None = None, + ) -> None: + """Delete *count* cells at *col* within ``[left, right]`` (``DCH``).""" + if not (left <= col <= right) or count <= 0: + return + shift = min(count, right - col + 1) + + if self.has_wide and self.attrs is not None: + # 1. Deleting SPACER_TAIL at col orphans WIDE head at col - 1. + if ( + raw_width_bits(self.attrs[col]) == int(WidthRole.SPACER_TAIL) + and col > 0 + ): + self.chars[col - 1] = " " + self.attrs[col - 1] &= _WIDTH_CLEAR_MASK + # First surviving cell at col + shift lost its WIDE head if SPACER_TAIL. + if col + shift <= right and raw_width_bits(self.attrs[col + shift]) == int( + WidthRole.SPACER_TAIL + ): + self.chars[col + shift] = " " + self.attrs[col + shift] &= _WIDTH_CLEAR_MASK + # Shifting WIDE head at right leftwards splits (right, right + 1). + if right + 1 < len(self.chars) and raw_width_bits( + self.attrs[right + 1] + ) == int(WidthRole.SPACER_TAIL): + self.chars[right] = " " + self.attrs[right] &= _WIDTH_CLEAR_MASK + self.chars[right + 1] = " " + self.attrs[right + 1] &= _WIDTH_CLEAR_MASK + + attrs = ( + self._ensure_attrs() + if ( + self.attrs is not None + or bce_word != self.uniform_attr + or bce_ext is not None + ) + else None + ) + for dst in range(col, right - shift + 1): + src = dst + shift + self.chars[dst] = self.chars[src] + if attrs is not None: + attrs[dst] = attrs[src] + if self.ext is not None: + if src in self.ext: + self.ext[dst] = self.ext[src] + else: + self.ext.pop(dst, None) + + for c in range(right - shift + 1, right + 1): + self._set_raw(c, " ", bce_word, WidthRole.NARROW, bce_ext) + if bce_word != 0 or bce_ext is not None: + self.used = max(self.used, right + 1) + elif self.used > col: + self.used = max(col, self.used - shift) + + def resize(self, cols: int) -> None: + """Resize row in place to *cols* columns (non-reflow path).""" + cur = len(self.chars) + if cols == cur: + return + if cols < cur: + if ( + cols > 0 + and self.has_wide + and self.attrs is not None + and raw_width_bits(self.attrs[cols - 1]) == int(WidthRole.WIDE) + ): + self.chars[cols - 1] = " " + self.attrs[cols - 1] &= _WIDTH_CLEAR_MASK + del self.chars[cols:] + if self.attrs is not None: + del self.attrs[cols:] + self.used = min(self.used, cols) + if self.ext: + for k in [k for k in self.ext if k >= cols]: + del self.ext[k] + else: + pad = cols - cur + self.chars.extend([" "] * pad) + if self.attrs is not None: + self.attrs.extend([0] * pad) + elif self.uniform_attr != 0: + attrs = array.array("Q", [self.uniform_attr]) * cur + attrs.extend([0] * pad) + self.attrs = attrs + + def clone(self) -> _Row: + """Return an independent copy of this row.""" + dup = _Row.__new__(_Row) + dup.chars = self.chars.copy() + dup.attrs = array.array("Q", self.attrs) if self.attrs is not None else None + dup.uniform_attr = self.uniform_attr + dup.has_wide = self.has_wide + dup.ext = self.ext.copy() if self.ext else None + dup.used = self.used + dup.wrapped = self.wrapped + return dup + + def freeze(self) -> FrozenRow: + """Seal this row into a compact run-length-encoded :class:`FrozenRow`.""" + cols = len(self.chars) + used = self.used + text = "".join(self.chars[:used]) + cells: tuple[str, ...] | None = None + if len(text) != used: + cells = tuple(self.chars[:used]) + + runs: tuple[tuple[int, int], ...] + if self.attrs is None: + runs = () if self.uniform_attr == 0 else ((cols, self.uniform_attr),) + else: + run_list: list[tuple[int, int]] = [] + cur_word = self.attrs[0] if cols > 0 else 0 + for c in range(1, cols): + w = self.attrs[c] + if w != cur_word: + run_list.append((c, cur_word)) + cur_word = w + if cols > 0 and (cur_word != 0 or run_list): + run_list.append((cols, cur_word)) + runs = tuple(run_list) + + exts = tuple(sorted(self.ext.items())) if self.ext else () + return FrozenRow( + text=text, + cols=cols, + runs=runs, + exts=exts, + cells=cells, + wrapped=self.wrapped, + ) + + def rstrip_text(self) -> str: + """Return row text up to ``used`` written columns.""" + return "".join(self.chars[: self.used]) + + +type RowLike = _Row | FrozenRow diff --git a/src/libvt/_ucd.py b/src/libvt/_ucd.py new file mode 100644 index 0000000..11ec4bd --- /dev/null +++ b/src/libvt/_ucd.py @@ -0,0 +1,227 @@ +"""Generated two-stage Unicode 17.0.0 cell-width and UAX #29 table. + +Regenerate with ``uv run python scripts/generate_ucd.py``. +""" + +from __future__ import annotations + +import array +import base64 +import enum +import sys +import zlib + + +class WidthRole(enum.IntEnum): + """Column occupancy role of a terminal grid cell.""" + + NARROW = 0 + WIDE = 1 + SPACER_TAIL = 2 + SPACER_HEAD = 3 + + +class ClusterState(enum.IntEnum): + """Scalar UAX #29 grapheme cluster continuation state.""" + + NONE = 0 + BASE = 1 + RI_ODD = 2 + EXT_PICT = 3 + EXT_PICT_ZWJ = 4 + INCB_CONS = 5 + INCB_LINKER = 6 + + +PROP_NONE = 0 +PROP_CONTROL = 1 +PROP_EXTEND = 2 +PROP_ZWJ = 3 +PROP_REGIONAL_INDICATOR = 4 +PROP_SPACING_MARK = 5 +PROP_EXTENDED_PICTOGRAPHIC = 6 +PROP_INCB_CONSONANT = 7 +PROP_INCB_LINKER = 8 +PROP_VS15 = 9 +PROP_VS16 = 10 +PROP_EMOJI_MODIFIER = 11 + +EXT_PICT_BIT = 0x40 +BIDI_SPOOF_BIT = 0x80 + +UNICODE_VERSION = "17.0.0" + +_PACKED_B85 = ( + "c-rk8hoa;pa9E?Fp5;{RtLu5{*?aH3_ZsZIpMJ!BxP+1rLJ}aPY{JajeVc?Zg@G9=oB{@j;SSD&4" + "9yMJ>0;)Z-kp*4>!Xt?Dv6vZiQ2D8=" + "QvQ;SRVH&cI!($Ge%-_pr~sa395A$D-z@zN@F?bxFsHJ$4e?J9J!!z(KJO|" + "Ii3-BVm1TVuY@G86pufrSgCcFi2!#mDY-woi@4c}|rc^^KIzdj7s^hfY<1l~SjIeiMBS)P3E^!^v" + "@^Cjd!Yj?lWet*qm{f7Pj7QTb;+5aEl$6DH-;Ai*+eudxQclZPTgumc#_{Xq@gj>b4Ne3G*f0Qs`" + "!h{JECQO(xVZww76DCZUFk!;g;=k};(n7+72@`G*vmQX>Lgq|AFH+|yL0rHSL(+I#5hO+U8zf>V{" + ")RO`R`Tdv1kM|Yrc`2v6cb!a4mOtcF*r}vjzXoG1@20!r7y4isD;^M3$MWyC+n+3q>R-wvblqpemdATlc>BG|X0N_0hKgb)f_`gf=p(;" + "IpEnAH-Kz$ol3()cAiuBv_lEujeJ+1Vzm{c#KB-#)39SEnT-CoW{Rhb3$pq4Vm8n?zgOHqvuz*Nt" + "=1a&hS7Z&?rVDSe-8saj-x#2W*H?z5X5#=a6VYC$BhF9EuO2%>s{=XHvOSyFZgPa0O%OO9@eJ)v8A<3V" + "FljBc*|&gKnFp=1TvCLu#kbXj@+g-QEH0i3;Tjz?$NiLUvMa|P7yLiTJh&GdZ6-Jf@DTo?F_!VQmvm_w_vs%w6tr>gJQ)^AgrWV_Z>Cs|^4vrZQE+Lv74%x" + "Y#Vz0XlZZ36I?EXm)s|m+4x}E31r5}7l)_4Tyk;&" + "%yXTJ{Ma*Me;hh6ahDz)u0Irv#clVc6o!=sQsW(AckQ~n9k~V4m1~L5BzqP8s7;F&xFh;c`L0E0M" + "Ql+`c&xV5UbHC#4g(gu^u7D8^^Ks}pb{bM+_Yg~T^n@|1shnTC@SJ" + "G(_{*kQ3{Oj8@$FTjDbxNeNj9HDNisVo=l^Y|_kvq9XP?<&w#wWTC5P}&j" + ")8|E6rQT;Rg)}zfsB{h{Dm|5@ipnG3DpJbdX>C@%T4=U!{JO*C4RL|Z{QO+1n+vw_+ai" + "xg{1a%4IgRZPW@!S)jp59@W&qK8 tuple[array.array[int], bytes]: + raw = zlib.decompress(base64.b85decode(_PACKED_B85)) + s1_len = int.from_bytes(raw[:4], "little") + s1 = array.array("H") + s1.frombytes(raw[4 : 4 + s1_len]) + if sys.byteorder != "little": + s1.byteswap() + return s1, raw[4 + s1_len :] + + +_STAGE1, _STAGE2 = _unpack_tables() + + +def ucd_lookup(cp: int) -> int: + """Return packed 8-bit width and UAX #29 property entry for codepoint *cp*.""" + if 0 <= cp <= 0x10FFFF: + return _STAGE2[(_STAGE1[cp >> 8] << 8) | (cp & 0xFF)] + return PROP_CONTROL << 2 + + +def char_width(ch: str) -> int: + """Return default terminal column width (``0``, ``1``, or ``2``) for *ch*.""" + cp = ord(ch) + if 0x20 <= cp <= 0x7E: + return 1 + return ucd_lookup(cp) & 0b11 + + +def step_cluster( + prev_state: ClusterState, + cp: int, + *, + mode_2027: bool, +) -> tuple[bool, ClusterState, int]: + """Evaluate UAX #29 continuation between *prev_state* and codepoint *cp*. + + Returns + ------- + tuple[bool, ClusterState, int] + ``(extends_previous, next_state, width_override)`` where + ``width_override`` is ``-1`` (keep current cluster width), ``1`` + (narrow via ``VS15``), or ``2`` (widen via ``VS16``, emoji modifier, + ZWJ pictographic, or Regional Indicator pair). + """ + entry = ucd_lookup(cp) + prop = (entry >> 2) & 0x0F + + if prev_state != ClusterState.NONE: + if prop == PROP_EXTEND: + return True, prev_state, -1 + if prop == PROP_VS16: + return True, prev_state, (2 if mode_2027 else -1) + if prop == PROP_VS15: + return True, prev_state, (1 if mode_2027 else -1) + if mode_2027: + if prop == PROP_SPACING_MARK: + next_st = ( + prev_state + if prev_state in (ClusterState.INCB_CONS, ClusterState.EXT_PICT) + else ClusterState.BASE + ) + return True, next_st, -1 + if prop == PROP_ZWJ: + next_st = ( + ClusterState.EXT_PICT_ZWJ + if prev_state == ClusterState.EXT_PICT + else ClusterState.BASE + ) + return True, next_st, -1 + if prop == PROP_EMOJI_MODIFIER and prev_state == ClusterState.EXT_PICT: + return True, ClusterState.EXT_PICT, 2 + if prev_state == ClusterState.EXT_PICT_ZWJ and (entry & EXT_PICT_BIT): + return True, ClusterState.EXT_PICT, 2 + if prop == PROP_REGIONAL_INDICATOR and prev_state == ClusterState.RI_ODD: + return True, ClusterState.BASE, 2 + if prop == PROP_INCB_LINKER and prev_state == ClusterState.INCB_CONS: + return True, ClusterState.INCB_LINKER, -1 + if prop == PROP_INCB_CONSONANT and prev_state == ClusterState.INCB_LINKER: + return True, ClusterState.INCB_CONS, -1 + + # Start of a new base cell (or dropped standalone zero-width character). + if prop == PROP_REGIONAL_INDICATOR and mode_2027: + return False, ClusterState.RI_ODD, -1 + if entry & EXT_PICT_BIT: + return False, ClusterState.EXT_PICT, -1 + if prop == PROP_INCB_CONSONANT: + return False, ClusterState.INCB_CONS, -1 + if (entry & 0b11) == 0: + return False, ClusterState.NONE, -1 + return False, ClusterState.BASE, -1 + + +def display_width(text: str, *, mode_2027: bool = True) -> int: + """Return rendered terminal column width of *text*.""" + if text.isascii(): + return sum(1 for ch in text if " " <= ch <= "~") + total = 0 + cur_w = 0 + state = ClusterState.NONE + for ch in text: + cp = ord(ch) + if 0x20 <= cp <= 0x7E: + total += cur_w + cur_w = 1 + state = ClusterState.BASE + continue + extends, state, w_override = step_cluster(state, cp, mode_2027=mode_2027) + if extends: + if w_override != -1: + cur_w = w_override + else: + total += cur_w + cur_w = ucd_lookup(cp) & 0b11 + return total + cur_w + + +def sanitize_terminal_text(text: str) -> str: + """Escape C0, C1, ``DEL``, and BiDi override codepoints for safe display.""" + out: list[str] = [] + for ch in text: + cp = ord(ch) + if 0x20 <= cp <= 0x7E: + out.append(ch) + elif cp < 0x20 or 0x7F <= cp <= 0x9F or (ucd_lookup(cp) & BIDI_SPOOF_BIT): + out.append(f"\\x{cp:02x}" if cp <= 0xFF else f"\\u{cp:04x}") + else: + out.append(ch) + return "".join(out) + + +__all__ = [ + "BIDI_SPOOF_BIT", + "UNICODE_VERSION", + "ClusterState", + "WidthRole", + "char_width", + "display_width", + "sanitize_terminal_text", + "step_cluster", + "ucd_lookup", +] diff --git a/src/libvt/aio.py b/src/libvt/aio.py new file mode 100644 index 0000000..78fc298 --- /dev/null +++ b/src/libvt/aio.py @@ -0,0 +1,445 @@ +"""Transport-only ``asyncio`` stream and POSIX PTY adapters over :class:`Terminal`.""" + +from __future__ import annotations + +import asyncio +import collections.abc +import contextlib +import os +import struct +import sys +import time +import typing as t + +from libvt.config import ( + DEFAULT_LIMITS, + DEFAULT_POLICY, + DEFAULT_PROFILE, + Limits, + Policy, + Profile, +) +from libvt.exc import TerminalTimeoutError +from libvt.input import InputEvent, KeyEvent, PasteEvent +from libvt.terminal import FlightRecorder, Snapshot, Terminal + + +class ReplyWriter(t.Protocol): + """Structural writer protocol satisfied by :class:`asyncio.StreamWriter`.""" + + def write(self, data: bytes, /) -> object: + """Buffer outbound *data* bytes.""" + + async def drain(self) -> None: + """Flush buffered outbound bytes.""" + + def close(self) -> object: + """Initiate writer close.""" + + async def wait_closed(self) -> None: + """Wait until writer close completes.""" + + +class AsyncTerminalStream: + """Drive a sans-I/O :class:`~libvt.terminal.Terminal` from ``asyncio`` streams. + + Coalesces frame wakeups across DEC mode ``?2026`` synchronized-output + batches (bounded by *sync_timeout* using generation-safe expiry) and + automatically flushes :meth:`~libvt.terminal.Terminal.drain_replies` when a + ``StreamWriter`` is attached. + """ + + def __init__( + self, + reader: asyncio.StreamReader, + writer: ReplyWriter | None = None, + *, + terminal: Terminal | None = None, + rows: int = 24, + cols: int = 80, + chunk_size: int = 4_096, + sync_timeout: float = 1.0, + ) -> None: + self.reader = reader + self.writer = writer + self.terminal = ( + terminal if terminal is not None else Terminal(rows=rows, cols=cols) + ) + self.chunk_size = chunk_size + self.sync_timeout = sync_timeout + self._frame_event = asyncio.Event() + self._eof = False + self._sync_started_at: float | None = None + self._sync_gen_tracked: int | None = None + self._task: asyncio.Task[None] | None = None + + @property + def eof(self) -> bool: + """Return ``True`` once ``reader`` reaches end-of-stream.""" + return self._eof + + def _update_sync_timer(self, now: float) -> None: + if self.terminal.synchronized: + cur_gen = self.terminal.sync_generation + if self._sync_gen_tracked != cur_gen or self._sync_started_at is None: + self._sync_gen_tracked = cur_gen + self._sync_started_at = now + elif ( + now - self._sync_started_at >= self.sync_timeout + and self.terminal.expire_synchronized_output(cur_gen) + ): + self._sync_started_at = None + self._sync_gen_tracked = None + self._frame_event.set() + else: + self._sync_started_at = None + self._sync_gen_tracked = None + self._frame_event.set() + + async def pump_once(self) -> bool: + """Read and feed one chunk; return ``False`` on EOF.""" + chunk = await self.reader.read(self.chunk_size) + if not chunk: + self._eof = True + self._frame_event.set() + return False + self.terminal.feed(chunk) + replies = self.terminal.drain_replies() + if replies and self.writer is not None: + self.writer.write(replies) + await self.writer.drain() + self._update_sync_timer(time.monotonic()) + return True + + async def _pump_loop(self) -> None: + while await self.pump_once(): + pass + + def start(self) -> asyncio.Task[None]: + """Start background stream pumping on the running event loop.""" + if self._task is None or self._task.done(): + self._task = asyncio.create_task(self._pump_loop()) + return self._task + + async def aclose(self) -> None: + """Cancel background pump task and close the writer if present.""" + if self._task is not None: + self._task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await self._task + self._task = None + if self.writer is not None: + self.writer.close() + with contextlib.suppress(OSError): + await self.writer.wait_closed() + + async def __aenter__(self) -> t.Self: + """Start background pumping when entering an ``async with`` block.""" + self.start() + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: object, + ) -> None: + """Stop background pumping and close writer when leaving ``async with``.""" + await self.aclose() + + async def wait_for( + self, + predicate: collections.abc.Callable[[Snapshot], bool] | str, + *, + timeout: float = 2.0, + ) -> Snapshot: + """Wait until *predicate* matches the committed :class:`Snapshot`.""" + check = ( + (lambda snap: predicate in snap.text) + if isinstance(predicate, str) + else predicate + ) + deadline = time.monotonic() + timeout + while True: + now = time.monotonic() + if self.terminal.synchronized: + self._update_sync_timer(now) + snap = self.terminal.snapshot() if self._eof else self.terminal.committed + if check(snap): + return snap + if self._eof: + msg = ( + f"stream reached EOF before predicate matched; " + f"screen text={snap.text!r}" + ) + raise TerminalTimeoutError(msg) + remaining = deadline - now + if remaining <= 0: + live = self.terminal.snapshot() + if check(live): + return live + msg = ( + f"timed out after {timeout:.2f}s waiting for terminal state; " + f"screen text={live.text!r}" + ) + raise TerminalTimeoutError(msg) + self._frame_event.clear() + wait_slice = ( + min(remaining, self.sync_timeout) + if self.terminal.synchronized + else remaining + ) + if self._task is None: + try: + await asyncio.wait_for(self.pump_once(), timeout=wait_slice) + except TimeoutError as exc: + if self.terminal.synchronized: + self._update_sync_timer(time.monotonic()) + continue + msg = f"timed out after {timeout:.2f}s waiting for stream bytes" + raise TerminalTimeoutError(msg) from exc + else: + with contextlib.suppress(TimeoutError): + await asyncio.wait_for( + self._frame_event.wait(), + timeout=wait_slice, + ) + if self.terminal.synchronized: + self._update_sync_timer(time.monotonic()) + + +class PtySession: + """Async POSIX pseudo-terminal subprocess session backed by :class:`Terminal`.""" + + def __init__( + self, + *, + master_fd: int, + process: asyncio.subprocess.Process, + terminal: Terminal, + sync_timeout: float = 1.0, + ) -> None: + self._master_fd = master_fd + self.process = process + self.terminal = terminal + self.sync_timeout = sync_timeout + self._frame_event = asyncio.Event() + self._eof = False + self._closed = False + self._sync_started_at: float | None = None + self._sync_gen_tracked: int | None = None + self._loop: asyncio.AbstractEventLoop | None = None + + @property + def eof(self) -> bool: + """Return ``True`` once the PTY master reaches EOF.""" + return self._eof + + def _on_readable(self) -> None: + if self._closed: + return + try: + chunk = os.read(self._master_fd, 16_384) + except OSError: + chunk = b"" + if not chunk: + self._eof = True + if self._loop is not None: + self._loop.remove_reader(self._master_fd) + self._frame_event.set() + return + self.terminal.feed(chunk) + replies = self.terminal.drain_replies() + if replies: + with contextlib.suppress(OSError): + os.write(self._master_fd, replies) + now = time.monotonic() + if self.terminal.synchronized: + cur_gen = self.terminal.sync_generation + if self._sync_gen_tracked != cur_gen or self._sync_started_at is None: + self._sync_gen_tracked = cur_gen + self._sync_started_at = now + else: + self._sync_started_at = None + self._sync_gen_tracked = None + self._frame_event.set() + + def send(self, data: bytes | str, /) -> None: + """Write raw *data* bytes (or UTF-8 string) to the PTY master.""" + raw = data.encode("utf-8") if isinstance(data, str) else data + os.write(self._master_fd, raw) + + def send_event(self, event: InputEvent, /) -> None: + """Encode *event* via :meth:`Terminal.encode` and write to the PTY.""" + encoded = self.terminal.encode(event) + if encoded: + os.write(self._master_fd, encoded) + + def send_key(self, chord: str, /) -> None: + """Parse *chord* (e.g. ``"ctrl+c"``, ``"enter"``) and send to the PTY.""" + self.send_event(KeyEvent.parse(chord)) + + def paste(self, text: str, /, *, sanitize: bool = False) -> None: + """Encode *text* as a :class:`PasteEvent` and write to the PTY.""" + self.send_event(PasteEvent(text=text, sanitize=sanitize)) + + def resize(self, *, rows: int, cols: int, reflow: bool = True) -> None: + """Update kernel ``TIOCSWINSZ`` and resize :attr:`terminal`.""" + import fcntl + import termios + + winsz = struct.pack("HHHH", rows, cols, 0, 0) + fcntl.ioctl(self._master_fd, termios.TIOCSWINSZ, winsz) + self.terminal.resize(rows=rows, cols=cols, reflow=reflow) + + async def wait_for( + self, + predicate: collections.abc.Callable[[Snapshot], bool] | str, + *, + timeout: float = 2.0, + ) -> Snapshot: + """Wait until *predicate* matches the committed :class:`Snapshot`.""" + check = ( + (lambda snap: predicate in snap.text) + if isinstance(predicate, str) + else predicate + ) + deadline = time.monotonic() + timeout + while True: + now = time.monotonic() + if ( + self.terminal.synchronized + and self._sync_started_at is not None + and now - self._sync_started_at >= self.sync_timeout + ): + self.terminal.expire_synchronized_output(self._sync_gen_tracked) + self._sync_started_at = None + self._sync_gen_tracked = None + snap = self.terminal.snapshot() if self._eof else self.terminal.committed + if check(snap): + return snap + if self._eof: + msg = ( + f"PTY reached EOF before predicate matched; " + f"screen text={snap.text!r}" + ) + raise TerminalTimeoutError(msg) + remaining = deadline - now + if remaining <= 0: + live = self.terminal.snapshot() + if check(live): + return live + msg = ( + f"timed out after {timeout:.2f}s waiting for PTY state; " + f"screen text={live.text!r}" + ) + raise TerminalTimeoutError(msg) + self._frame_event.clear() + wait_slice = ( + min(remaining, self.sync_timeout) + if self.terminal.synchronized + else remaining + ) + with contextlib.suppress(TimeoutError): + await asyncio.wait_for(self._frame_event.wait(), timeout=wait_slice) + + async def aclose(self) -> int: + """Stop reading, close PTY master fd, and terminate/reap child process.""" + if not self._closed: + self._closed = True + if self._loop is not None: + with contextlib.suppress(Exception): + self._loop.remove_reader(self._master_fd) + with contextlib.suppress(OSError): + os.close(self._master_fd) + if self.process.returncode is None: + self.process.terminate() + try: + await asyncio.wait_for(self.process.wait(), timeout=1.0) + except TimeoutError: + self.process.kill() + await self.process.wait() + self.terminal.notify_process_exit() + return self.process.returncode or 0 + + +@contextlib.asynccontextmanager +async def open_pty( + argv: collections.abc.Sequence[str], + *, + rows: int = 24, + cols: int = 80, + scrollback: int = 2_000, + env: collections.abc.Mapping[str, str] | None = None, + cwd: str | os.PathLike[str] | None = None, + profile: Profile = DEFAULT_PROFILE, + policy: Policy = DEFAULT_POLICY, + limits: Limits = DEFAULT_LIMITS, + sync_timeout: float = 1.0, +) -> collections.abc.AsyncGenerator[PtySession]: + """Spawn *argv* on a POSIX pseudo-terminal driven by :class:`Terminal`.""" + if sys.platform == "win32": + msg = "open_pty requires POSIX pty.openpty()" + raise NotImplementedError(msg) + + import fcntl + import pty + import termios + + master_fd, slave_fd = pty.openpty() + try: + fcntl.ioctl( + slave_fd, + termios.TIOCSWINSZ, + struct.pack("HHHH", rows, cols, 0, 0), + ) + os.set_blocking(master_fd, False) + child_env = dict(os.environ if env is None else env) + child_env.setdefault("TERM", "xterm-256color") + proc = await asyncio.create_subprocess_exec( + *argv, + stdin=slave_fd, + stdout=slave_fd, + stderr=slave_fd, + cwd=cwd, + env=child_env, + start_new_session=True, + close_fds=True, + ) + except BaseException: + os.close(master_fd) + raise + finally: + os.close(slave_fd) + + recorder = FlightRecorder(max_bytes=limits.max_recorder_bytes) + terminal = Terminal( + rows=rows, + cols=cols, + scrollback=scrollback, + profile=profile, + policy=policy, + limits=limits, + recorder=recorder, + ) + session = PtySession( + master_fd=master_fd, + process=proc, + terminal=terminal, + sync_timeout=sync_timeout, + ) + loop = asyncio.get_running_loop() + session._loop = loop + loop.add_reader(master_fd, session._on_readable) + try: + yield session + finally: + await session.aclose() + + +__all__ = [ + "AsyncTerminalStream", + "PtySession", + "ReplyWriter", + "open_pty", +] diff --git a/src/libvt/codec.py b/src/libvt/codec.py new file mode 100644 index 0000000..3bdc76a --- /dev/null +++ b/src/libvt/codec.py @@ -0,0 +1,232 @@ +"""Cold-path VT byte-stream disassembler for ``libvt.explain()`` and failure dumps.""" + +from __future__ import annotations + +import collections.abc +from dataclasses import dataclass + +from libvt._ucd import sanitize_terminal_text +from libvt.modes import DEC_PRIVATE_MASK, Mode +from libvt.parser import ( + ApcDispatch, + CsiDispatch, + DcsDispatch, + EscDispatch, + Execute, + OscDispatch, + Parser, + Print, +) + + +@dataclass(frozen=True, slots=True) +class ExplainedSpan: + """Human-readable disassembly of one parsed VT token. + + Attributes + ---------- + kind : str + Token family (``"PRINT"``, ``"C0"``, ``"ESC"``, ``"CSI"``, ``"OSC"``, + ``"DCS"``, or ``"APC"``). + mnemonic : str + Standard ECMA-48 / DEC / modern VT mnemonic (e.g. ``"CUP"``, ``"SGR"``, + ``"DECSET"``, ``"OSC 7501"``). + summary : str + Sanitized parameter and meaning summary. + """ + + kind: str + mnemonic: str + summary: str + + +_C0_NAMES: dict[int, tuple[str, str]] = { + 0x07: ("BEL", "bell"), + 0x08: ("BS", "backspace"), + 0x09: ("HT", "horizontal tab"), + 0x0A: ("LF", "line feed"), + 0x0B: ("VT", "vertical tab"), + 0x0C: ("FF", "form feed"), + 0x0D: ("CR", "carriage return"), + 0x0E: ("SO", "shift out -> G1"), + 0x0F: ("SI", "shift in -> G0"), +} + +_CSI_NAMES: dict[str, str] = { + "@": "ICH", + "A": "CUU", + "B": "CUD", + "C": "CUF", + "D": "CUB", + "E": "CNL", + "F": "CPL", + "G": "CHA", + "H": "CUP", + "I": "CHT", + "J": "ED", + "K": "EL", + "L": "IL", + "M": "DL", + "P": "DCH", + "S": "SU", + "T": "SD", + "X": "ECH", + "Z": "CBT", + "`": "HPA", + "b": "REP", + "c": "DA1", + "d": "VPA", + "f": "HVP", + "g": "TBC", + "h": "SM", + "l": "RM", + "m": "SGR", + "n": "DSR", + "q": "XTVERSION/DECSCUSR", + "r": "DECSTBM", + "s": "DECSLRM/SCOSC", + "t": "XTWINOPS", + "u": "SCORC/KITTY_KBD", +} + +_OSC_NAMES: dict[int, str] = { + 0: "OSC 0 (icon+title)", + 1: "OSC 1 (icon)", + 2: "OSC 2 (title)", + 4: "OSC 4 (palette)", + 7: "OSC 7 (cwd)", + 8: "OSC 8 (hyperlink)", + 9: "OSC 9 (notification/progress)", + 10: "OSC 10 (fg color)", + 11: "OSC 11 (bg color)", + 12: "OSC 12 (cursor color)", + 22: "OSC 22 (pointer shape)", + 52: "OSC 52 (clipboard)", + 66: "OSC 66 (text sizing)", + 99: "OSC 99 (kitty notification)", + 133: "OSC 133 (semantic prompt)", + 3008: "OSC 3008 (context)", + 5522: "OSC 5522 (mime clipboard)", + 7501: "OSC 7501 (program status)", +} + + +def _describe_mode(code: int, *, private: bool) -> str: + raw = (DEC_PRIVATE_MASK | code) if private else code + prefix = "?" if private else "" + try: + name = Mode(raw).name + except ValueError: + return f"{prefix}{code}" + return f"{prefix}{code} ({name})" + + +def _explain_csi(act: CsiDispatch) -> ExplainedSpan: + pfx = chr(act.prefix) if act.prefix else "" + inter = act.intermediates.decode("ascii", errors="replace") + fin = chr(act.final) + vals = ";".join(str(v) for v in act.params.values) + + if act.prefix == ord("?") and not inter and fin in ("h", "l"): + mnem = "DECSET" if fin == "h" else "DECRST" + modes = ", ".join(_describe_mode(v, private=True) for v in act.params.values) + state_word = "set" if fin == "h" else "reset" + return ExplainedSpan("CSI", mnem, f"{modes} = {state_word}") + + if inter == "$" and fin == "p": + code = act.params.raw_or_default(0, 0) + return ExplainedSpan( + "CSI", + "DECRQM", + _describe_mode(code, private=act.prefix == ord("?")), + ) + + if fin == "u" and pfx in (">", "<", "=", "?"): + return ExplainedSpan("CSI", "KITTY_KBD", f"{pfx}{vals}u") + + if pfx == ">" and fin == "q" and not inter: + return ExplainedSpan("CSI", "XTVERSION", ">q") + + if inter == '"' and fin == "q": + return ExplainedSpan("CSI", "DECSCA", f'{vals}"q') + + if pfx == "?" and fin in ("J", "K"): + mnem = "DECSED" if fin == "J" else "DECSEL" + return ExplainedSpan("CSI", mnem, f"?{vals}{fin}") + + mnem = _CSI_NAMES.get(fin, f"CSI {fin}") + return ExplainedSpan("CSI", mnem, f"{pfx}{vals}{inter}{fin}") + + +def explain(data: collections.abc.Buffer | str) -> tuple[ExplainedSpan, ...]: + """Disassemble *data* into sanitized :class:`ExplainedSpan` records.""" + raw = data.encode("utf-8") if isinstance(data, str) else data + parser = Parser() + actions = parser.feed(raw) + spans: list[ExplainedSpan] = [] + + for act in actions: + if isinstance(act, Print): + spans.append( + ExplainedSpan("PRINT", "TEXT", repr(sanitize_terminal_text(act.text))), + ) + elif isinstance(act, Execute): + mnem, desc = _C0_NAMES.get(act.byte, (f"0x{act.byte:02X}", "control")) + spans.append(ExplainedSpan("C0", mnem, f"{desc} (0x{act.byte:02x})")) + elif isinstance(act, EscDispatch): + inter = act.intermediates.decode("ascii", errors="replace") + fin = chr(act.final) + if inter in ("(", ")", "*", "+"): + slot = {"(": "G0", ")": "G1", "*": "G2", "+": "G3"}[inter] + spans.append(ExplainedSpan("ESC", "SCS", f"{slot} -> {fin!r}")) + else: + spans.append(ExplainedSpan("ESC", f"ESC {inter}{fin}", f"{inter}{fin}")) + elif isinstance(act, CsiDispatch): + spans.append(_explain_csi(act)) + elif isinstance(act, OscDispatch): + mnem = _OSC_NAMES.get(act.code, f"OSC {act.code}") + body = sanitize_terminal_text(act.data.decode("utf-8", errors="replace")) + if len(body) > 96: + body = body[:96] + "..." + spans.append(ExplainedSpan("OSC", mnem, body)) + elif isinstance(act, DcsDispatch): + inter = act.intermediates.decode("ascii", errors="replace") + fin = chr(act.final) + if not act.prefix and not inter and fin == "q": + mnem = "SIXEL" + elif inter == "$": + mnem = "DECRQSS" + elif inter == "+": + mnem = "XTGETTCAP" + else: + mnem = f"DCS {inter}{fin}" + preview = sanitize_terminal_text( + act.data[:64].decode("utf-8", errors="replace"), + ) + spans.append( + ExplainedSpan("DCS", mnem, f"len={len(act.data)} {preview!r}"), + ) + elif isinstance(act, ApcDispatch): + mnem = "KITTY_GFX" if act.data.startswith(b"G") else "APC" + preview = sanitize_terminal_text( + act.data[:64].decode("utf-8", errors="replace"), + ) + spans.append( + ExplainedSpan("APC", mnem, f"len={len(act.data)} {preview!r}"), + ) + + return tuple(spans) + + +def format_explain(data: collections.abc.Buffer | str) -> str: + """Format :func:`explain` spans as aligned one-line records.""" + return "\n".join( + f"{sp.kind:<5} {sp.mnemonic:<28} {sp.summary}" for sp in explain(data) + ) + + +__all__ = [ + "ExplainedSpan", + "explain", + "format_explain", +] diff --git a/src/libvt/config.py b/src/libvt/config.py new file mode 100644 index 0000000..daf6fa0 --- /dev/null +++ b/src/libvt/config.py @@ -0,0 +1,174 @@ +"""Terminal identity profiles, security policies, and resource ceilings.""" + +from __future__ import annotations + +import enum +from dataclasses import dataclass + + +class ColorScheme(enum.IntEnum): + """``CSI ? 997 ; Ps n`` color-scheme values (``DEC ?2031`` / ``DSR ?996n``).""" + + DARK = 1 + LIGHT = 2 + + +@dataclass(frozen=True, slots=True) +class Profile: + """Terminal identity responses and compatibility switches. + + Attributes + ---------- + name : str + Human-readable profile identifier. + da1 : bytes + Primary Device Attributes (``CSI c``) response bytes. + da2 : bytes + Secondary Device Attributes (``CSI > c``) response bytes. + xtversion : str + Version banner emitted in ``DCS > | ST`` (``CSI > q``). + osc_7501_capabilities : str + Payload body returned for ``OSC 7501 ; ?`` queries when enabled + (for example + ``"?:states=idle,working,done,blocked,error:kinds=permission,question,auth"`` + or ``"?"`` for bare ``tmux`` compatibility). + color_scheme : ColorScheme + Default scheme reported for ``CSI ? 996 n`` color-scheme queries. + fg_rgb : tuple[int, int, int] + Default foreground 8-bit RGB reported for ``OSC 10 ; ?``. + bg_rgb : tuple[int, int, int] + Default background 8-bit RGB reported for ``OSC 11 ; ?``. + pending_wrap_phantom_col : bool + When ``True`` (``TMUX_PROFILE``), ``pending_wrap`` treats the cursor as + occupying phantom column ``cols`` on ``CUB`` / ``BS`` and allows ``BS`` + at column ``0`` to step onto the end of a soft-wrapped predecessor row, + matching ``tmux``'s ``screen-write.c``. When ``False`` (default), + ``CUB`` / ``BS`` follow ``xterm`` / ``Ghostty`` rules. + """ + + name: str = "xterm" + da1: bytes = b"\x1b[?62;22c" + da2: bytes = b"\x1b[>1;10;0c" + xtversion: str = "libvt 0.1" + osc_7501_capabilities: str = ( + "?:states=idle,working,done,blocked,error:kinds=permission,question,auth" + ) + color_scheme: ColorScheme = ColorScheme.DARK + fg_rgb: tuple[int, int, int] = (0xE5, 0xE5, 0xE5) + bg_rgb: tuple[int, int, int] = (0x1E, 0x1E, 0x1E) + pending_wrap_phantom_col: bool = False + + +@dataclass(frozen=True, slots=True) +class Policy: + """Default-deny host security and strictness policy. + + Attributes + ---------- + allow_title_report : bool + Permit ``CSI 21 t`` window-title report replies (default ``False``). + allow_checksum_report : bool + Permit ``DECRQCRA`` rectangular checksum replies (default ``False``). + allow_clipboard_read : bool + Permit ``OSC 52 ; ... ; ?`` clipboard read replies (default ``False``). + allow_clipboard_write : bool + Emit :class:`~libvt.events.ClipboardWrite` events on ``OSC 52`` writes + (default ``True``; no host clipboard is ever mutated by ``libvt``). + allow_color_queries : bool + Permit ``OSC 10 ; ?``, ``OSC 11 ; ?``, and ``CSI ? 996 n`` palette and + color-scheme replies (default ``True``). + allow_program_status_query : bool + Force ``OSC 7501 ; ?`` capability replies even when neither ``on_event`` + nor ``record_events`` is enabled (default ``False``, matching + ``libghostty-vt``). + allow_unsafe_uris : bool + Allow schemes outside ``http://``, ``https://``, and ``mailto:`` in + HTML ```` output (default ``False``). + unwrap_tmux_passthrough : bool + Unwrap ``DCS tmux; ESC ESC ... ST`` passthrough envelopes and feed the + inner byte stream (default ``True``). + strict : bool + Raise :exc:`~libvt.exc.ProtocolError` on unrecognized escape sequences + instead of ignoring or recording :class:`~libvt.events.UnhandledSequence` + (default ``False``). + """ + + allow_title_report: bool = False + allow_checksum_report: bool = False + allow_clipboard_read: bool = False + allow_clipboard_write: bool = True + allow_color_queries: bool = True + allow_program_status_query: bool = False + allow_unsafe_uris: bool = False + unwrap_tmux_passthrough: bool = True + strict: bool = False + + +@dataclass(frozen=True, slots=True) +class Limits: + """Resource ceilings protecting memory and CPU against hostile byte streams. + + Attributes + ---------- + max_grapheme_codepoints : int + Maximum Unicode codepoints stored in a single grid cell (default ``32``). + max_csi_params : int + Maximum parameter slots retained in a ``CSI`` or ``DCS`` header. + max_osc_bytes : int + Maximum payload bytes buffered for an ``OSC`` sequence. + max_dcs_bytes : int + Maximum payload bytes buffered for a ``DCS`` sequence. + max_apc_bytes : int + Maximum payload bytes buffered for an ``APC`` sequence. + max_reply_bytes : int + Maximum unread bytes queued in :meth:`~libvt.terminal.Terminal.drain_replies`. + max_rep_count : int + Maximum repeat count executed by ``REP`` (``CSI Ps b``). + max_prompt_zones : int + Maximum ``OSC 133`` prompt zones retained on a terminal. + max_status_records : int + Maximum concurrent ``OSC 7501`` task records retained in the store. + max_events : int + Maximum unread :data:`~libvt.events.Event` items retained when + ``record_events=True``. + 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`. + """ + + max_grapheme_codepoints: int = 32 + max_csi_params: int = 32 + max_osc_bytes: int = 131_072 + max_dcs_bytes: int = 4_194_304 + max_apc_bytes: int = 4_194_304 + max_reply_bytes: int = 65_536 + max_rep_count: int = 4_096 + max_prompt_zones: int = 1_024 + max_status_records: int = 64 + max_events: int = 4_096 + max_keyboard_stack: int = 8 + max_recorder_bytes: int = 4_096 + + +XTERM_PROFILE = Profile() +DEFAULT_PROFILE = XTERM_PROFILE +TMUX_PROFILE = Profile( + name="tmux", + osc_7501_capabilities="?", + pending_wrap_phantom_col=True, +) +DEFAULT_POLICY = Policy() +DEFAULT_LIMITS = Limits() + +__all__ = [ + "DEFAULT_LIMITS", + "DEFAULT_POLICY", + "DEFAULT_PROFILE", + "TMUX_PROFILE", + "XTERM_PROFILE", + "ColorScheme", + "Limits", + "Policy", + "Profile", +] diff --git a/src/libvt/events.py b/src/libvt/events.py new file mode 100644 index 0000000..a34aec8 --- /dev/null +++ b/src/libvt/events.py @@ -0,0 +1,352 @@ +"""Closed algebraic Event union and structured terminal notification records.""" + +from __future__ import annotations + +import enum +import typing as t +from dataclasses import dataclass + +if t.TYPE_CHECKING: + from libvt.config import ColorScheme + from libvt.status import ProgramStatus + + +class PromptKind(enum.StrEnum): + """``OSC 133`` FinalTerm / semantic-shell prompt zone markers.""" + + PROMPT_START = "A" + COMMAND_START = "B" + COMMAND_EXECUTED = "C" + COMMAND_FINISHED = "D" + + +@dataclass(frozen=True, slots=True) +class PromptZone: + """Semantic shell prompt boundary emitted via ``OSC 133``. + + Attributes + ---------- + kind : PromptKind + Marker kind (``A``, ``B``, ``C``, or ``D``). + row : int + Zero-based viewport row (negative once scrolled into ``history``). + col : int + Zero-based column index when the marker arrived. + exit_code : int | None + Parsed exit status on ``D`` markers when supplied, else ``None``. + abs_row : int + Monotonic row index from the top of primary scroll history so scrolling + never invalidates stored coordinates. + """ + + kind: PromptKind + row: int + col: int + exit_code: int | None = None + abs_row: int = 0 + + +class EraseCause(enum.StrEnum): + """Reason a screen rectangle was cleared or scrolled.""" + + ED = "ed" + EL = "el" + ECH = "ech" + DECSED = "decsed" + DECSEL = "decsel" + SCROLL = "scroll" + RESET = "reset" + + +@dataclass(frozen=True, slots=True) +class Rect: + """Zero-based rectangular cell region. + + Attributes + ---------- + row : int + Top row index (``0``-based). + col : int + Left column index (``0``-based). + rows : int + Height in rows. + cols : int + Width in columns. + """ + + row: int + col: int + rows: int + cols: int + + +@dataclass(frozen=True, slots=True) +class SixelData: + """Zero-dependency ``DCS ... q`` SIXEL payload record. + + Attributes + ---------- + row : int + Zero-based cursor row at SIXEL entry. + col : int + Zero-based cursor column at SIXEL entry. + params : tuple[int, ...] + Parsed ``DCS`` numeric header parameters. + payload : bytes + Raw SIXEL data bytes up to ``ST``. + """ + + row: int + col: int + params: tuple[int, ...] + payload: bytes + + +@dataclass(frozen=True, slots=True) +class KittyCommand: + """Zero-dependency ``APC G`` Kitty graphics protocol record. + + Attributes + ---------- + row : int + Zero-based cursor row when the command arrived. + col : int + Zero-based cursor column when the command arrived. + control : dict[str, str] + Key-value control header pairs before ``;``. + payload : bytes + Encoded payload bytes following ``;``. + """ + + row: int + col: int + control: dict[str, str] + payload: bytes + + +@dataclass(frozen=True, slots=True) +class Bell: + """Emitted when ``BEL`` (``0x07``) executes in ``GROUND``.""" + + +@dataclass(frozen=True, slots=True) +class TitleChanged: + """Emitted when ``OSC 0`` or ``OSC 2`` updates the window title. + + Attributes + ---------- + title : str + Updated window title. + """ + + title: str + + +@dataclass(frozen=True, slots=True) +class WorkingDirectoryChanged: + """Emitted when ``OSC 7`` or ``OSC 9;9`` updates the working directory. + + Attributes + ---------- + uri : str + Reported ``file://`` URI or directory path. + path : str + Decoded path component extracted from ``uri``. + """ + + uri: str + path: str + + +@dataclass(frozen=True, slots=True) +class ClipboardWrite: + """Emitted when ``OSC 52`` writes base64-decoded text to a selection target. + + Attributes + ---------- + selection : str + Clipboard selection targets (e.g. ``"c"`` or ``"p"``). + text : str + Decoded UTF-8 text written by the application. + """ + + selection: str + text: str + + +@dataclass(frozen=True, slots=True) +class PromptMark: + """Emitted when ``OSC 133`` records a semantic prompt zone. + + Attributes + ---------- + zone : PromptZone + Recorded prompt zone descriptor. + """ + + zone: PromptZone + + +@dataclass(frozen=True, slots=True) +class ProgramStatusChanged: + """Emitted when ``OSC 7501`` or ``OSC 9;4`` mutates task status. + + Attributes + ---------- + status : ProgramStatus | None + Updated task record, or ``None`` when all records were cleared. + task_id : str + Task identifier affected by the update (``""`` for root). + """ + + status: ProgramStatus | None + task_id: str = "" + + +@dataclass(frozen=True, slots=True) +class RenderHoldChanged: + """Emitted when DEC mode ``?2026`` synchronized output starts or ends. + + Attributes + ---------- + active : bool + ``True`` on ``?2026h`` start; ``False`` on ``?2026l`` commit or expiry. + sync_generation : int + Monotonic synchronized-update batch counter. + expired : bool + ``True`` when ended by + :meth:`~libvt.terminal.Terminal.expire_synchronized_output`. + """ + + active: bool + sync_generation: int + expired: bool = False + + +@dataclass(frozen=True, slots=True) +class ColorSchemeQueried: + """Emitted when ``CSI ? 996 n`` queries the host color scheme. + + Attributes + ---------- + scheme : ColorScheme + Scheme reported back to the application. + """ + + scheme: ColorScheme + + +@dataclass(frozen=True, slots=True) +class InBandResize: + """Emitted when ``resize()`` queues a ``?2048`` in-band resize report. + + Attributes + ---------- + rows : int + New terminal height in rows. + cols : int + New terminal width in columns. + """ + + rows: int + cols: int + + +@dataclass(frozen=True, slots=True) +class SixelGraphic: + """Emitted when a ``DCS ... q`` SIXEL graphic sequence completes. + + Attributes + ---------- + data : SixelData + Captured SIXEL header and payload. + """ + + data: SixelData + + +@dataclass(frozen=True, slots=True) +class KittyGraphic: + """Emitted when an ``APC G`` Kitty graphics sequence completes. + + Attributes + ---------- + command : KittyCommand + Captured Kitty control dictionary and payload. + """ + + command: KittyCommand + + +@dataclass(frozen=True, slots=True) +class ScreenErased: + """Emitted when cells clear or scroll on the active screen. + + Attributes + ---------- + rect : Rect + Zero-based rectangle affected. + cause : EraseCause + Operation that cleared or scrolled the region. + active_is_alt : bool + ``True`` when the erase occurred on the ``?1049`` alternate screen. + """ + + rect: Rect + cause: EraseCause + active_is_alt: bool + + +@dataclass(frozen=True, slots=True) +class UnhandledSequence: + """Recorded when an unrecognized control sequence arrives and ``strict=False``. + + Attributes + ---------- + kind : str + Sequence family (``"esc"``, ``"csi"``, ``"osc"``, ``"dcs"``, or ``"apc"``). + summary : str + Sanitized compact representation of the unrecognized sequence. + """ + + kind: str + summary: str + + +type Event = ( + Bell + | TitleChanged + | WorkingDirectoryChanged + | ClipboardWrite + | PromptMark + | ProgramStatusChanged + | RenderHoldChanged + | ColorSchemeQueried + | InBandResize + | SixelGraphic + | KittyGraphic + | ScreenErased + | UnhandledSequence +) + +__all__ = [ + "Bell", + "ClipboardWrite", + "ColorSchemeQueried", + "EraseCause", + "Event", + "InBandResize", + "KittyCommand", + "KittyGraphic", + "ProgramStatusChanged", + "PromptKind", + "PromptZone", + "Rect", + "RenderHoldChanged", + "ScreenErased", + "SixelData", + "SixelGraphic", + "TitleChanged", + "UnhandledSequence", + "WorkingDirectoryChanged", +] diff --git a/src/libvt/exc.py b/src/libvt/exc.py new file mode 100644 index 0000000..e841ea9 --- /dev/null +++ b/src/libvt/exc.py @@ -0,0 +1,32 @@ +"""Exceptions raised by libvt.""" + +from __future__ import annotations + + +class LibVtError(Exception): + """Base exception for all libvt errors.""" + + +class ProtocolError(LibVtError): + """Raised when ``Policy.strict`` rejects a malformed or unsupported sequence.""" + + +class UnsafePasteError(LibVtError): + """Raised when pasted text contains control or bracket-escape bytes.""" + + +class TerminalTimeoutError(LibVtError, TimeoutError): + """Raised when an async terminal stream wait exceeds its deadline.""" + + +class ScreenAssertionError(LibVtError, AssertionError): + """Raised when :func:`~libvt.testing.assert_screen` detects a screen mismatch.""" + + +__all__ = [ + "LibVtError", + "ProtocolError", + "ScreenAssertionError", + "TerminalTimeoutError", + "UnsafePasteError", +] diff --git a/src/libvt/input.py b/src/libvt/input.py new file mode 100644 index 0000000..387c38a --- /dev/null +++ b/src/libvt/input.py @@ -0,0 +1,529 @@ +"""Mode-aware input event types, Kitty keyboard flag stacks, and paste guards.""" + +from __future__ import annotations + +import enum +from dataclasses import dataclass + +from libvt.exc import UnsafePasteError +from libvt.modes import Mode, ModeState + + +class KeyMod(enum.IntFlag): + """Keyboard and mouse modifier bitmask matching Kitty ``CSI u`` bits.""" + + NONE = 0 + SHIFT = 1 + ALT = 2 + CTRL = 4 + SUPER = 8 + HYPER = 16 + META = 32 + + +class KeyAction(enum.IntEnum): + """Key press lifecycle event type for Kitty ``CSI u``.""" + + PRESS = 1 + REPEAT = 2 + RELEASE = 3 + + +class KittyKeyboardFlags(enum.IntFlag): + """Progressive-enhancement flags for the Kitty Keyboard Protocol (``CSI u``).""" + + NONE = 0 + DISAMBIGUATE = 1 + REPORT_EVENT_TYPES = 2 + REPORT_ALTERNATE_KEYS = 4 + REPORT_ALL_KEYS = 8 + REPORT_ASSOCIATED_TEXT = 16 + + +class KittyKeyboardStack: + """Bounded per-screen stack of :class:`KittyKeyboardFlags`.""" + + __slots__ = ("_max_depth", "_stack") + + def __init__(self, *, max_depth: int = 8) -> None: + self._max_depth = max_depth + self._stack: list[int] = [0] + + @property + def flags(self) -> KittyKeyboardFlags: + """Return currently active :class:`KittyKeyboardFlags`.""" + return KittyKeyboardFlags(self._stack[-1] if self._stack else 0) + + def push(self, flags: int) -> None: + """Push *flags* onto the stack (``CSI > flags u``), evicting oldest on full.""" + masked = flags & 0x1F + if len(self._stack) >= self._max_depth: + self._stack.pop(0) + self._stack.append(masked) + + def pop(self, count: int = 1) -> None: + """Pop *count* entries (``CSI < count u``), keeping ``0`` when emptied.""" + n = max(1, count) + if n >= len(self._stack): + self._stack = [0] + else: + del self._stack[-n:] + + def set_flags(self, flags: int, mode: int = 1) -> None: + """Update top-of-stack flags via ``CSI = flags ; mode u``.""" + masked = flags & 0x1F + cur = self._stack[-1] if self._stack else 0 + if mode == 1: + self._stack[-1] = masked + elif mode == 2: + self._stack[-1] = cur | masked + elif mode == 3: + self._stack[-1] = cur & ~masked + + def reset(self) -> None: + """Reset keyboard flags to legacy mode ``0``.""" + self._stack = [0] + + +_MOD_NAMES: dict[str, KeyMod] = { + "shift": KeyMod.SHIFT, + "alt": KeyMod.ALT, + "opt": KeyMod.ALT, + "option": KeyMod.ALT, + "ctrl": KeyMod.CTRL, + "control": KeyMod.CTRL, + "super": KeyMod.SUPER, + "cmd": KeyMod.SUPER, + "win": KeyMod.SUPER, + "hyper": KeyMod.HYPER, + "meta": KeyMod.META, +} + + +@dataclass(frozen=True, slots=True) +class KeyEvent: + """Structured keyboard event for outbound PTY encoding. + + Attributes + ---------- + key : str + Single Unicode character (e.g. ``"a"``, ``"A"``) or canonical key name + (``"enter"``, ``"tab"``, ``"escape"``, ``"backspace"``, ``"up"``, + ``"down"``, ``"right"``, ``"left"``, ``"home"``, ``"end"``, + ``"page_up"``, ``"page_down"``, ``"insert"``, ``"delete"``, + ``"f1"``..``"f12"``). + modifiers : KeyMod + Active modifier bitmask. + action : KeyAction + Key action (``PRESS``, ``REPEAT``, or ``RELEASE``). + text : str + Optional associated text for Kitty flag ``REPORT_ASSOCIATED_TEXT``. + """ + + key: str + modifiers: KeyMod = KeyMod.NONE + action: KeyAction = KeyAction.PRESS + text: str = "" + + @classmethod + def parse(cls, chord: str, *, action: KeyAction = KeyAction.PRESS) -> KeyEvent: + """Parse a human-readable chord such as ``"ctrl+shift+p"`` or ``"up"``.""" + if chord == "+": + return cls(key="+", action=action) + parts = chord.split("+") + mods = KeyMod.NONE + for raw_mod in parts[:-1]: + m = _MOD_NAMES.get(raw_mod.strip().lower()) + if m is None: + msg = f"unknown key modifier {raw_mod!r} in chord {chord!r}" + raise ValueError(msg) + mods |= m + raw_key = parts[-1] + key = raw_key if len(raw_key) == 1 else raw_key.strip().lower() + return cls(key=key, modifiers=mods, action=action) + + +class MouseButton(enum.IntEnum): + """Mouse buttons and scroll wheel directions.""" + + LEFT = 0 + MIDDLE = 1 + RIGHT = 2 + NONE = 3 + WHEEL_UP = 64 + WHEEL_DOWN = 65 + + +class MouseAction(enum.StrEnum): + """Mouse pointer action.""" + + PRESS = "press" + RELEASE = "release" + MOVE = "move" + + +@dataclass(frozen=True, slots=True) +class MouseEvent: + """Zero-based ``(row, col)`` mouse event for outbound SGR / X10 encoding. + + Attributes + ---------- + button : MouseButton + Mouse button or scroll wheel. + action : MouseAction + Pointer action (``press``, ``release``, or ``move``). + row : int + Zero-based terminal row. + col : int + Zero-based terminal column. + modifiers : KeyMod + Active keyboard modifiers during the mouse event. + pixel_x : int + Horizontal pixel coordinate for ``?1016`` SGR-Pixel mode. + pixel_y : int + Vertical pixel coordinate for ``?1016`` SGR-Pixel mode. + """ + + button: MouseButton + action: MouseAction + row: int + col: int + modifiers: KeyMod = KeyMod.NONE + pixel_x: int = 0 + pixel_y: int = 0 + + +@dataclass(frozen=True, slots=True) +class FocusEvent: + """Terminal window focus-in / focus-out event (``?1004``). + + Attributes + ---------- + focused : bool + ``True`` on focus gain (``ESC [ I``); ``False`` on focus loss (``ESC [ O``). + """ + + focused: bool + + +@dataclass(frozen=True, slots=True) +class PasteEvent: + r"""Clipboard paste payload encoded with ``?2004`` bracketing and safety checks. + + Attributes + ---------- + text : str + Text to paste into the terminal. + sanitize : bool + When ``False`` (default), raise :exc:`~libvt.exc.UnsafePasteError` on + control or escape characters. When ``True``, strip control/escape + codepoints in a single character-level pass. + allow_unbracketed_newlines : bool + Permit ``\r`` and ``\n`` when ``?2004`` bracketed paste is disabled. + """ + + text: str + sanitize: bool = False + allow_unbracketed_newlines: bool = False + + +type InputEvent = KeyEvent | MouseEvent | FocusEvent | PasteEvent + +_ARROW_CSI: dict[str, str] = { + "up": "A", + "down": "B", + "right": "C", + "left": "D", + "home": "H", + "end": "F", +} + +_TILDE_CSI: dict[str, int] = { + "insert": 2, + "delete": 3, + "page_up": 5, + "page_down": 6, + "f5": 15, + "f6": 17, + "f7": 18, + "f8": 19, + "f9": 20, + "f10": 21, + "f11": 23, + "f12": 24, +} + +_SS3_FKEYS: dict[str, str] = { + "f1": "P", + "f2": "Q", + "f3": "R", + "f4": "S", +} + +_KITTY_SPECIAL_CP: dict[str, int] = { + "escape": 27, + "esc": 27, + "enter": 13, + "return": 13, + "tab": 9, + "backspace": 127, +} + + +def is_safe_paste(text: str, *, bracketed: bool = True) -> bool: + """Return ``True`` when *text* contains no escape or injection control bytes.""" + for ch in text: + cp = ord(ch) + if cp == 0x1B or cp == 0x7F or 0x80 <= cp <= 0x9F or cp == 0: + return False + if cp < 0x20: + if ch == "\t": + continue + if bracketed and ch in ("\n", "\r"): + continue + return False + return True + + +def encode_paste( + text: str, + *, + bracketed: bool, + sanitize: bool = False, + allow_unbracketed_newlines: bool = False, +) -> bytes: + """Encode *text* for pasting, failing closed on escape/control injection.""" + if sanitize: + cleaned: list[str] = [] + for ch in text: + cp = ord(ch) + if cp == 0x1B or cp == 0x7F or 0x80 <= cp <= 0x9F or cp == 0: + continue + if cp < 0x20: + if ch == "\t" or ( + (bracketed or allow_unbracketed_newlines) and ch in ("\n", "\r") + ): + cleaned.append(ch) + continue + cleaned.append(ch) + payload = "".join(cleaned).encode("utf-8") + else: + for ch in text: + cp = ord(ch) + if cp == 0x1B or cp == 0x7F or 0x80 <= cp <= 0x9F or cp == 0: + msg = f"paste contains unsafe control/escape codepoint U+{cp:04X}" + raise UnsafePasteError(msg) + if cp < 0x20: + if ch == "\t": + continue + if (bracketed or allow_unbracketed_newlines) and ch in ("\n", "\r"): + continue + msg = ( + f"paste contains newline/control U+{cp:04X} while bracketed " + f"paste (?2004) is {'enabled' if bracketed else 'disabled'}" + ) + raise UnsafePasteError(msg) + payload = text.encode("utf-8") + + if bracketed: + return b"\x1b[200~" + payload + b"\x1b[201~" + return payload + + +def _encode_key( + event: KeyEvent, + *, + modes: ModeState, + kitty_flags: KittyKeyboardFlags, +) -> bytes: + report_events = bool(kitty_flags & KittyKeyboardFlags.REPORT_EVENT_TYPES) + if event.action == KeyAction.RELEASE and not report_events: + return b"" + + mod_param = int(event.modifiers) + 1 + ev_suffix = ( + f":{int(event.action)}" + if report_events and event.action != KeyAction.PRESS + else "" + ) + + k = event.key + k_low = k if len(k) == 1 else k.lower() + + # Functional arrows / Home / End + if k_low in _ARROW_CSI: + final = _ARROW_CSI[k_low] + if mod_param == 1 and not ev_suffix: + if modes.is_set(Mode.DECCKM): + return f"\x1bO{final}".encode("ascii") + return f"\x1b[{final}".encode("ascii") + return f"\x1b[1;{mod_param}{ev_suffix}{final}".encode("ascii") + + # SS3 F1-F4 + if k_low in _SS3_FKEYS: + final = _SS3_FKEYS[k_low] + if mod_param == 1 and not ev_suffix: + return f"\x1bO{final}".encode("ascii") + return f"\x1b[1;{mod_param}{ev_suffix}{final}".encode("ascii") + + # Tilde functional keys + if k_low in _TILDE_CSI: + num = _TILDE_CSI[k_low] + if mod_param == 1 and not ev_suffix: + return f"\x1b[{num}~".encode("ascii") + return f"\x1b[{num};{mod_param}{ev_suffix}~".encode("ascii") + + disambig = bool( + kitty_flags + & (KittyKeyboardFlags.DISAMBIGUATE | KittyKeyboardFlags.REPORT_ALL_KEYS), + ) + report_all = bool(kitty_flags & KittyKeyboardFlags.REPORT_ALL_KEYS) + + # Named C0 keys (escape, enter, tab, backspace) + if k_low in _KITTY_SPECIAL_CP: + cp = _KITTY_SPECIAL_CP[k_low] + if report_all or ( + disambig + and ( + k_low in ("escape", "esc") + or event.modifiers != KeyMod.NONE + or ev_suffix + ) + ): + if mod_param == 1 and not ev_suffix: + return f"\x1b[{cp}u".encode("ascii") + return f"\x1b[{cp};{mod_param}{ev_suffix}u".encode("ascii") + if k_low == "tab" and (event.modifiers & KeyMod.SHIFT): + return b"\x1b[Z" + raw = bytes([cp]) + return (b"\x1b" + raw) if (event.modifiers & KeyMod.ALT) else raw + + if len(k) != 1: + msg = f"unsupported key identifier {k!r}" + raise ValueError(msg) + + cp = ord(k) + if report_all or ( + disambig + and ((event.modifiers & ~KeyMod.SHIFT) != KeyMod.NONE or bool(ev_suffix)) + ): + base_cp = ord(k.lower()) if "A" <= k <= "Z" else cp + mods = event.modifiers | (KeyMod.SHIFT if "A" <= k <= "Z" else KeyMod.NONE) + mp = int(mods) + 1 + if mp == 1 and not ev_suffix: + return f"\x1b[{base_cp}u".encode("ascii") + return f"\x1b[{base_cp};{mp}{ev_suffix}u".encode("ascii") + + # Legacy xterm key encoding + out_char = k + if event.modifiers & KeyMod.CTRL: + low_cp = ord(k.lower()) + if 0x61 <= low_cp <= 0x7A: + raw = bytes([low_cp - 0x60]) + elif k in (" ", "@"): + raw = b"\x00" + elif k == "[": + raw = b"\x1b" + elif k == "\\": + raw = b"\x1c" + elif k == "]": + raw = b"\x1d" + elif k == "^": + raw = b"\x1e" + elif k in ("_", "/"): + raw = b"\x1f" + else: + raw = out_char.encode("utf-8") + else: + raw = out_char.encode("utf-8") + + if event.modifiers & KeyMod.ALT: + return b"\x1b" + raw + return raw + + +def _encode_mouse(event: MouseEvent, *, modes: ModeState) -> bytes: + any_event = modes.is_set(Mode.MOUSE_ANY_EVENT) + btn_event = modes.is_set(Mode.MOUSE_BUTTON_EVENT) + vt200 = modes.is_set(Mode.MOUSE_VT200) + x10 = modes.is_set(Mode.MOUSE_X10) + + if not (any_event or btn_event or vt200 or x10): + return b"" + if ( + event.action == MouseAction.MOVE + and not any_event + and not (btn_event and event.button != MouseButton.NONE) + ): + return b"" + if ( + event.action == MouseAction.RELEASE + and x10 + and not (vt200 or btn_event or any_event) + ): + return b"" + + code = int(event.button) + if event.action == MouseAction.MOVE: + code |= 32 + if event.modifiers & KeyMod.SHIFT: + code |= 4 + if event.modifiers & KeyMod.ALT: + code |= 8 + if event.modifiers & KeyMod.CTRL: + code |= 16 + + if modes.is_set(Mode.MOUSE_SGR_PIXELS): + final = "m" if event.action == MouseAction.RELEASE else "M" + return f"\x1b[<{code};{event.pixel_x};{event.pixel_y}{final}".encode("ascii") + + if modes.is_set(Mode.MOUSE_SGR): + final = "m" if event.action == MouseAction.RELEASE else "M" + return f"\x1b[<{code};{event.col + 1};{event.row + 1}{final}".encode("ascii") + + # Classic X10 / VT200 byte-encoded coordinates (clamped to 223). + wire_btn = 3 if event.action == MouseAction.RELEASE else code + cx = min(255, 32 + max(0, event.col) + 1) + cy = min(255, 32 + max(0, event.row) + 1) + return bytes([0x1B, ord("["), ord("M"), min(255, 32 + wire_btn), cx, cy]) + + +def encode_input( + event: InputEvent, + *, + modes: ModeState, + kitty_flags: KittyKeyboardFlags = KittyKeyboardFlags.NONE, +) -> bytes: + """Encode *event* into outbound PTY bytes respecting active terminal *modes*.""" + if isinstance(event, KeyEvent): + return _encode_key(event, modes=modes, kitty_flags=kitty_flags) + if isinstance(event, MouseEvent): + return _encode_mouse(event, modes=modes) + if isinstance(event, FocusEvent): + if not modes.is_set(Mode.FOCUS_EVENT): + return b"" + return b"\x1b[I" if event.focused else b"\x1b[O" + return encode_paste( + event.text, + bracketed=modes.is_set(Mode.BRACKETED_PASTE), + sanitize=event.sanitize, + allow_unbracketed_newlines=event.allow_unbracketed_newlines, + ) + + +__all__ = [ + "FocusEvent", + "InputEvent", + "KeyAction", + "KeyEvent", + "KeyMod", + "KittyKeyboardFlags", + "KittyKeyboardStack", + "MouseAction", + "MouseButton", + "MouseEvent", + "PasteEvent", + "encode_input", + "encode_paste", + "is_safe_paste", +] diff --git a/src/libvt/modes.py b/src/libvt/modes.py new file mode 100644 index 0000000..b9d5bda --- /dev/null +++ b/src/libvt/modes.py @@ -0,0 +1,144 @@ +"""ANSI standard and DEC private terminal mode definitions.""" + +from __future__ import annotations + +import enum + +DEC_PRIVATE_MASK = 0x8000 + + +class Mode(enum.IntEnum): + """ANSI standard modes and DEC private modes (``0x8000 | code``).""" + + IRM = 4 + LNM = 20 + + DECCKM = DEC_PRIVATE_MASK | 1 + DECOM = DEC_PRIVATE_MASK | 6 + DECAWM = DEC_PRIVATE_MASK | 7 + MOUSE_X10 = DEC_PRIVATE_MASK | 9 + DECTCEM = DEC_PRIVATE_MASK | 25 + REVERSE_WRAP = DEC_PRIVATE_MASK | 45 + ALT_SCREEN_47 = DEC_PRIVATE_MASK | 47 + DECLRMM = DEC_PRIVATE_MASK | 69 + MOUSE_VT200 = DEC_PRIVATE_MASK | 1000 + MOUSE_BUTTON_EVENT = DEC_PRIVATE_MASK | 1002 + MOUSE_ANY_EVENT = DEC_PRIVATE_MASK | 1003 + FOCUS_EVENT = DEC_PRIVATE_MASK | 1004 + MOUSE_SGR = DEC_PRIVATE_MASK | 1006 + MOUSE_SGR_PIXELS = DEC_PRIVATE_MASK | 1016 + ALT_SCREEN_1047 = DEC_PRIVATE_MASK | 1047 + DECSC_1048 = DEC_PRIVATE_MASK | 1048 + ALT_SCREEN = DEC_PRIVATE_MASK | 1049 + BRACKETED_PASTE = DEC_PRIVATE_MASK | 2004 + SYNCHRONIZED_OUTPUT = DEC_PRIVATE_MASK | 2026 + GRAPHEME_CLUSTERING = DEC_PRIVATE_MASK | 2027 + COLOR_SCHEME_UPDATES = DEC_PRIVATE_MASK | 2031 + IN_BAND_RESIZE = DEC_PRIVATE_MASK | 2048 + + +ALT_SCREEN_MODES: frozenset[Mode] = frozenset( + { + Mode.ALT_SCREEN_47, + Mode.ALT_SCREEN_1047, + Mode.ALT_SCREEN, + }, +) + + +class DecrpmValue(enum.IntEnum): + """``DECRPM`` status codes returned in ``CSI ? Ps ; Pm $ y`` replies.""" + + NOT_RECOGNIZED = 0 + SET = 1 + RESET = 2 + PERMANENTLY_SET = 3 + PERMANENTLY_RESET = 4 + + +TRANSIENT_SNAPSHOT_MODES: frozenset[Mode] = frozenset( + { + Mode.SYNCHRONIZED_OUTPUT, + }, +) + +_DEFAULT_ENABLED_MODES: frozenset[Mode] = frozenset( + { + Mode.DECAWM, + Mode.DECTCEM, + Mode.GRAPHEME_CLUSTERING, + }, +) + +_RECOGNIZED_MODES: frozenset[int] = frozenset(int(m) for m in Mode) + + +class ModeState: + """Mutable set of active ANSI and DEC private modes.""" + + __slots__ = ("_enabled",) + + def __init__(self, enabled: set[Mode] | None = None) -> None: + self._enabled: set[Mode] = ( + set(_DEFAULT_ENABLED_MODES) if enabled is None else set(enabled) + ) + + def is_set(self, mode: Mode) -> bool: + """Return ``True`` when *mode* is enabled.""" + return mode in self._enabled + + def set_mode(self, mode: Mode, *, enabled: bool) -> None: + """Enable or disable *mode*.""" + if enabled: + self._enabled.add(mode) + else: + self._enabled.discard(mode) + + def sync_alt_screen( + self, + *, + active_is_alt: bool, + entered_via: Mode = Mode.ALT_SCREEN, + ) -> None: + """Reconcile ``?47`` / ``?1047`` / ``?1049`` flags to *active_is_alt*. + + Exiting alternate screen via any of ``?47l``, ``?1047l``, or ``?1049l`` + clears all three flags so ``DECRQM`` never reports a stale set bit. + """ + self._enabled.difference_update(ALT_SCREEN_MODES) + if active_is_alt: + self._enabled.add(entered_via) + + def decrpm( + self, + code: int, + *, + private: bool, + active_is_alt: bool | None = None, + ) -> DecrpmValue: + """Return the ``DECRPM`` status value for raw mode number *code*.""" + raw = (DEC_PRIVATE_MASK | code) if private else code + if raw not in _RECOGNIZED_MODES: + return DecrpmValue.NOT_RECOGNIZED + mode = Mode(raw) + if mode in ALT_SCREEN_MODES and active_is_alt is False: + return DecrpmValue.RESET + return DecrpmValue.SET if mode in self._enabled else DecrpmValue.RESET + + def enabled_modes(self) -> frozenset[Mode]: + """Return an immutable snapshot of currently enabled modes.""" + return frozenset(self._enabled) + + def clone(self) -> ModeState: + """Return an independent copy of this mode state.""" + return ModeState(self._enabled) + + +__all__ = [ + "ALT_SCREEN_MODES", + "DEC_PRIVATE_MASK", + "TRANSIENT_SNAPSHOT_MODES", + "DecrpmValue", + "Mode", + "ModeState", +] diff --git a/src/libvt/parser.py b/src/libvt/parser.py new file mode 100644 index 0000000..b474bb7 --- /dev/null +++ b/src/libvt/parser.py @@ -0,0 +1,1153 @@ +"""Clean-room 14-state VT500 streaming byte parser and SGR parameter decoder. + +State transitions follow Paul Flo Williams' public DEC ANSI parser state +diagram (ECMA-48 / DEC STD 070) with UTF-8 multi-byte decoding, 7-bit C1 +isolation, and bounded parameter and string buffers. +""" + +from __future__ import annotations + +import codecs +import collections.abc +import enum +import re +import typing as t +from dataclasses import dataclass + +from libvt.config import DEFAULT_LIMITS, Limits +from libvt.style import ( + DEFAULT_STYLE, + AnsiColor, + Color, + IndexedColor, + RgbColor, + Style, + UnderlineStyle, +) + +MAX_INTERMEDIATES = 4 +_PARAM_CLAMP = 65_535 +_MEMO_LIMIT = 256 +_CTRL_RE = re.compile(rb"[\x00-\x1f\x7f]") +_CSI_FAST_RE = re.compile(rb"([\x3c-\x3f]?)([0-9;:]{0,256})([\x40-\x7e])") + + +class ParserState(enum.IntEnum): + """States of the DEC ANSI / VT500 byte state machine.""" + + GROUND = 0 + ESCAPE = 1 + ESCAPE_INTERMEDIATE = 2 + CSI_ENTRY = 3 + CSI_PARAM = 4 + CSI_INTERMEDIATE = 5 + CSI_IGNORE = 6 + DCS_ENTRY = 7 + DCS_PARAM = 8 + DCS_INTERMEDIATE = 9 + DCS_PASSTHROUGH = 10 + DCS_IGNORE = 11 + OSC_STRING = 12 + SOS_PM_APC_STRING = 13 + + +@dataclass(frozen=True, slots=True) +class CsiParams: + """Parsed CSI parameter list preserving ``;`` vs ``:`` subparameter boundaries. + + Attributes + ---------- + values : tuple[int, ...] + Clamped integer parameter values (``0`` for omitted slots). + colon_mask : int + Bitmask where bit ``i`` is ``1`` when ``values[i]`` was preceded by + ``:`` (an ITU T.416 subparameter of the nearest preceding ``;`` slot). + omitted_mask : int + Bitmask where bit ``i`` is ``1`` when slot ``i`` contained no digits. + """ + + values: tuple[int, ...] = () + colon_mask: int = 0 + omitted_mask: int = 0 + + def get(self, index: int, default: int = 1) -> int: + """Return parameter *index*, substituting *default* when omitted or ``0``.""" + if index >= len(self.values): + return default + val = self.values[index] + return default if val == 0 else val + + def raw_or_default(self, index: int, default: int = 0) -> int: + """Return parameter *index*, substituting *default* only when omitted.""" + if index >= len(self.values): + return default + if (self.omitted_mask >> index) & 1: + return default + return self.values[index] + + def is_subparam(self, index: int) -> bool: + """Return ``True`` when parameter *index* was introduced by ``:``.""" + return bool((self.colon_mask >> index) & 1) + + def groups(self) -> list[tuple[int, ...]]: + """Group ``values`` into semicolon-delimited parameter tuples.""" + if not self.values: + return [] + result: list[list[int]] = [[self.values[0]]] + for idx in range(1, len(self.values)): + if (self.colon_mask >> idx) & 1: + result[-1].append(self.values[idx]) + else: + result.append([self.values[idx]]) + return [tuple(g) for g in result] + + +EMPTY_PARAMS = CsiParams() + + +@dataclass(frozen=True, slots=True) +class Print: + """Decoded printable text emitted in ``GROUND`` state. + + Attributes + ---------- + text : str + Decoded Unicode string (one or more characters). + """ + + text: str + + +@dataclass(frozen=True, slots=True) +class Execute: + """C0 control byte executed immediately. + + Attributes + ---------- + byte : int + Control code value (e.g. ``0x0A`` for ``LF``). + """ + + byte: int + + +@dataclass(frozen=True, slots=True) +class EscDispatch: + """Completed two- or multi-byte ``ESC`` sequence. + + Attributes + ---------- + intermediates : bytes + Intermediate bytes in ``0x20..0x2F``. + final : int + Final byte in ``0x30..0x7E``. + """ + + intermediates: bytes + final: int + + +@dataclass(frozen=True, slots=True) +class CsiDispatch: + """Completed ``CSI`` control sequence. + + Attributes + ---------- + prefix : int + Private marker byte in ``0x3C..0x3F`` (``<``, ``=``, ``>``, ``?``) or + ``0`` when absent. + params : CsiParams + Parsed numeric parameters and colon/omission bitmasks. + intermediates : bytes + Intermediate bytes in ``0x20..0x2F``. + final : int + Final byte in ``0x40..0x7E``. + """ + + prefix: int + params: CsiParams + intermediates: bytes + final: int + + +@dataclass(frozen=True, slots=True) +class OscDispatch: + r"""Completed Operating System Command (``OSC``). + + Attributes + ---------- + code : int + Numeric ``OSC`` command identifier (``-1`` when absent or non-numeric). + data : bytes + Raw payload bytes following the first ``;`` (or the full body when no + ``;`` is present). + terminator : bytes + Wire terminator that closed the command (``b"\x07"`` or ``b"\x1b\\"``). + """ + + code: int + data: bytes + terminator: bytes = b"\x1b\\" + + +@dataclass(frozen=True, slots=True) +class DcsDispatch: + """Completed Device Control String (``DCS``), including ``SIXEL``. + + Attributes + ---------- + prefix : int + Private marker byte in ``0x3C..0x3F`` or ``0``. + params : CsiParams + Header parameters preceding the payload. + intermediates : bytes + Header intermediate bytes in ``0x20..0x2F``. + final : int + Header final byte in ``0x40..0x7E``. + data : bytes + Raw passthrough payload bytes up to ``ST``. + """ + + prefix: int + params: CsiParams + intermediates: bytes + final: int + data: bytes + + +@dataclass(frozen=True, slots=True) +class ApcDispatch: + """Completed Application Program Command (``APC``), e.g. Kitty graphics. + + Attributes + ---------- + data : bytes + Raw ``APC`` payload bytes up to ``ST``. + """ + + data: bytes + + +type Action = ( + Print + | Execute + | EscDispatch + | CsiDispatch + | OscDispatch + | DcsDispatch + | ApcDispatch +) + + +class ActionSink(t.Protocol): + """Zero-allocation callback target for :meth:`Parser.feed_to`.""" + + def on_print(self, text: str) -> None: + """Receive printable Unicode text.""" + + def on_execute(self, byte: int) -> None: + """Receive a C0 control byte.""" + + def on_esc(self, intermediates: bytes, final: int) -> None: + """Receive an ``ESC`` sequence.""" + + def on_csi( + self, + prefix: int, + params: CsiParams, + intermediates: bytes, + final: int, + ) -> None: + """Receive a ``CSI`` sequence.""" + + def on_osc(self, code: int, data: bytes, terminator: bytes) -> None: + """Receive an ``OSC`` sequence and its closing terminator.""" + + def on_dcs( + self, + prefix: int, + params: CsiParams, + intermediates: bytes, + final: int, + data: bytes, + ) -> None: + """Receive a ``DCS`` sequence.""" + + def on_apc(self, data: bytes) -> None: + """Receive an ``APC`` sequence.""" + + +class _ListSink: + __slots__ = ("actions",) + + def __init__(self) -> None: + self.actions: list[Action] = [] + + def on_print(self, text: str) -> None: + self.actions.append(Print(text)) + + def on_execute(self, byte: int) -> None: + self.actions.append(Execute(byte)) + + def on_esc(self, intermediates: bytes, final: int) -> None: + self.actions.append(EscDispatch(intermediates, final)) + + def on_csi( + self, + prefix: int, + params: CsiParams, + intermediates: bytes, + final: int, + ) -> None: + self.actions.append(CsiDispatch(prefix, params, intermediates, final)) + + def on_osc(self, code: int, data: bytes, terminator: bytes) -> None: + self.actions.append(OscDispatch(code, data, terminator)) + + def on_dcs( + self, + prefix: int, + params: CsiParams, + intermediates: bytes, + final: int, + data: bytes, + ) -> None: + self.actions.append( + DcsDispatch(prefix, params, intermediates, final, data), + ) + + def on_apc(self, data: bytes) -> None: + self.actions.append(ApcDispatch(data)) + + +def _parse_csi_param_bytes(raw: bytes, *, max_params: int) -> CsiParams: + if not raw: + return EMPTY_PARAMS + vals: list[int] = [] + colon_mask = 0 + omitted_mask = 0 + cur = 0 + has_digit = False + is_colon = False + for b in raw: + if 0x30 <= b <= 0x39: + cur = min(_PARAM_CLAMP, cur * 10 + (b - 0x30)) + has_digit = True + elif b in (0x3B, 0x3A): + idx = len(vals) + if idx < max_params: + vals.append(cur) + if is_colon: + colon_mask |= 1 << idx + if not has_digit: + omitted_mask |= 1 << idx + cur = 0 + has_digit = False + is_colon = b == 0x3A + idx = len(vals) + if idx < max_params: + vals.append(cur) + if is_colon: + colon_mask |= 1 << idx + if not has_digit: + omitted_mask |= 1 << idx + return CsiParams(tuple(vals), colon_mask, omitted_mask) + + +def _decode_extended_color( + sub: tuple[int, ...], + flat_groups: list[tuple[int, ...]], + group_idx: int, +) -> tuple[Color, int]: + """Decode ``38`` / ``48`` / ``58`` color group into ``(color, consumed)``.""" + if len(sub) >= 2: + mode = sub[1] + if mode == 5 and len(sub) >= 3: + cidx = sub[2] + if 0 <= cidx <= 255: + return IndexedColor(cidx), 1 + return None, 1 + if mode == 2: + if len(sub) >= 6: + r, g, b = sub[3], sub[4], sub[5] + elif len(sub) == 5: + r, g, b = sub[2], sub[3], sub[4] + else: + return None, 1 + if 0 <= r <= 255 and 0 <= g <= 255 and 0 <= b <= 255: + return RgbColor(r, g, b), 1 + return None, 1 + return None, 1 + + if group_idx + 1 >= len(flat_groups): + return None, 1 + mode = flat_groups[group_idx + 1][0] + if mode == 5 and group_idx + 2 < len(flat_groups): + cidx = flat_groups[group_idx + 2][0] + if 0 <= cidx <= 255: + return IndexedColor(cidx), 3 + return None, 3 + if mode == 2 and group_idx + 4 < len(flat_groups): + r = flat_groups[group_idx + 2][0] + g = flat_groups[group_idx + 3][0] + b = flat_groups[group_idx + 4][0] + if 0 <= r <= 255 and 0 <= g <= 255 and 0 <= b <= 255: + return RgbColor(r, g, b), 5 + return None, 5 + return None, 2 + + +_UL_MAP: dict[int, UnderlineStyle] = { + 0: UnderlineStyle.NONE, + 1: UnderlineStyle.SINGLE, + 2: UnderlineStyle.DOUBLE, + 3: UnderlineStyle.CURLY, + 4: UnderlineStyle.DOTTED, + 5: UnderlineStyle.DASHED, +} + + +def parse_sgr( + params: CsiParams, + current: Style = DEFAULT_STYLE, + *, + memo: dict[tuple[Style, CsiParams], Style] | None = None, +) -> Style: + """Apply ``CSI ... m`` parameters to *current* and return a new :class:`Style`.""" + if not params.values or ( + len(params.values) == 1 and params.values[0] == 0 and params.colon_mask == 0 + ): + return DEFAULT_STYLE + + if memo is not None: + cached = memo.get((current, params)) + if cached is not None: + return cached + + fg = current.fg + bg = current.bg + ul_color = current.underline_color + bold = current.bold + dim = current.dim + italic = current.italic + underline = current.underline + blink = current.blink + reverse = current.reverse + hidden = current.hidden + strike = current.strikethrough + overline = current.overline + + groups = params.groups() + idx = 0 + total = len(groups) + while idx < total: + grp = groups[idx] + code = grp[0] + if code == 0 and len(grp) == 1: + fg = None + bg = None + ul_color = None + bold = False + dim = False + italic = False + underline = UnderlineStyle.NONE + blink = False + reverse = False + hidden = False + strike = False + overline = False + elif code == 1: + bold = True + elif code == 2: + dim = True + elif code == 3: + italic = True + elif code == 4: + sub_ul = grp[1] if len(grp) >= 2 else 1 + underline = _UL_MAP.get(sub_ul, UnderlineStyle.SINGLE) + elif code in (5, 6): + blink = True + elif code == 7: + reverse = True + elif code == 8: + hidden = True + elif code == 9: + strike = True + elif code == 21: + underline = UnderlineStyle.DOUBLE + elif code == 22: + bold = False + dim = False + elif code == 23: + italic = False + elif code == 24: + underline = UnderlineStyle.NONE + elif code == 25: + blink = False + elif code == 27: + reverse = False + elif code == 28: + hidden = False + elif code == 29: + strike = False + elif 30 <= code <= 37: + fg = AnsiColor(code - 30) + elif code == 38: + parsed_fg, step = _decode_extended_color(grp, groups, idx) + if parsed_fg is not None: + fg = parsed_fg + idx += step + continue + elif code == 39: + fg = None + elif 40 <= code <= 47: + bg = AnsiColor(code - 40) + elif code == 48: + parsed_bg, step = _decode_extended_color(grp, groups, idx) + if parsed_bg is not None: + bg = parsed_bg + idx += step + continue + elif code == 49: + bg = None + elif code == 53: + overline = True + elif code == 55: + overline = False + elif code == 58: + parsed_ul, step = _decode_extended_color(grp, groups, idx) + if parsed_ul is not None: + ul_color = parsed_ul + idx += step + continue + elif code == 59: + ul_color = None + elif 90 <= code <= 97: + fg = AnsiColor(code - 90 + 8) + elif 100 <= code <= 107: + bg = AnsiColor(code - 100 + 8) + idx += 1 + + result = Style( + fg=fg, + bg=bg, + underline_color=ul_color, + bold=bold, + dim=dim, + italic=italic, + underline=underline, + blink=blink, + reverse=reverse, + hidden=hidden, + strikethrough=strike, + overline=overline, + ) + if memo is not None: + if len(memo) >= _MEMO_LIMIT: + del memo[next(iter(memo))] + memo[(current, params)] = result + return result + + +class Parser: + """Streaming 14-state VT500 / ANSI escape-sequence byte parser.""" + + __slots__ = ( + "_c1_controls", + "_csi_colon_mask", + "_csi_cur", + "_csi_has_digit", + "_csi_is_colon", + "_csi_memo", + "_csi_omitted_mask", + "_csi_prefix", + "_csi_vals", + "_dcs_final", + "_dcs_intermediates", + "_dcs_params", + "_intermediates", + "_limits", + "_return_from_esc_st", + "_state", + "_str_buf", + "_str_kind", + "_str_overflow", + "_utf8", + "_utf8_pending", + ) + + def __init__( + self, + *, + c1_controls: bool = False, + limits: Limits = DEFAULT_LIMITS, + ) -> None: + self._c1_controls = c1_controls + self._limits = limits + self._state: ParserState = ParserState.GROUND + self._utf8 = codecs.getincrementaldecoder("utf-8")("replace") + self._utf8_pending: bool = False + self._intermediates = bytearray() + self._csi_prefix: int = 0 + self._csi_vals: list[int] = [] + self._csi_colon_mask: int = 0 + self._csi_omitted_mask: int = 0 + self._csi_cur: int = 0 + self._csi_has_digit: bool = False + self._csi_is_colon: bool = False + self._dcs_params: CsiParams = EMPTY_PARAMS + self._dcs_intermediates: bytes = b"" + self._dcs_final: int = 0 + self._str_buf = bytearray() + self._str_overflow: bool = False + self._str_kind: int = 0 + self._return_from_esc_st: ParserState | None = None + self._csi_memo: dict[bytes, CsiParams] = {} + + @property + def state(self) -> ParserState: + """Return the current :class:`ParserState`.""" + return self._state + + @property + def utf8_pending(self) -> bool: + """Return ``True`` when an incomplete multi-byte UTF-8 sequence is buffered.""" + return self._utf8_pending + + def reset(self) -> None: + """Reset parser state and clear buffered partial sequences.""" + self._state = ParserState.GROUND + self._utf8.reset() + self._utf8_pending = False + self._intermediates.clear() + self._reset_csi() + self._str_buf.clear() + self._str_overflow = False + self._str_kind = 0 + self._return_from_esc_st = None + + def _reset_csi(self) -> None: + self._csi_prefix = 0 + self._csi_vals.clear() + self._csi_colon_mask = 0 + self._csi_omitted_mask = 0 + self._csi_cur = 0 + self._csi_has_digit = False + self._csi_is_colon = False + self._intermediates.clear() + + def _push_param(self, *, next_is_colon: bool) -> None: + idx = len(self._csi_vals) + if idx < self._limits.max_csi_params: + self._csi_vals.append(self._csi_cur) + if self._csi_is_colon: + self._csi_colon_mask |= 1 << idx + if not self._csi_has_digit: + self._csi_omitted_mask |= 1 << idx + self._csi_cur = 0 + self._csi_has_digit = False + self._csi_is_colon = next_is_colon + + def _finalize_params(self) -> CsiParams: + if not self._csi_vals and not self._csi_has_digit and not self._csi_is_colon: + return EMPTY_PARAMS + self._push_param(next_is_colon=False) + return CsiParams( + values=tuple(self._csi_vals), + colon_mask=self._csi_colon_mask, + omitted_mask=self._csi_omitted_mask, + ) + + def _flush_incomplete_utf8(self, sink: ActionSink) -> None: + if self._utf8_pending: + flushed = self._utf8.decode(b"", final=True) + self._utf8.reset() + self._utf8_pending = False + if flushed: + sink.on_print(flushed) + + def _decode_utf8_bytes(self, raw: bytes | memoryview, sink: ActionSink) -> None: + chunk = bytes(raw) if isinstance(raw, memoryview) else raw + decoded = self._utf8.decode(chunk, final=False) + self._utf8_pending = bool(self._utf8.getstate()[0]) + if decoded: + sink.on_print(decoded) + + def _dispatch_osc(self, sink: ActionSink, terminator: bytes) -> None: + if self._str_overflow: + self._str_buf.clear() + self._str_overflow = False + return + raw = bytes(self._str_buf) + self._str_buf.clear() + semi = raw.find(b";") + if semi == -1: + code = int(raw) if raw.isdigit() else -1 + sink.on_osc(code, b"", terminator) + else: + head = raw[:semi] + code = int(head) if head.isdigit() else -1 + sink.on_osc(code, raw[semi + 1 :], terminator) + + def _dispatch_dcs(self, sink: ActionSink) -> None: + if not self._str_overflow: + sink.on_dcs( + self._csi_prefix, + self._dcs_params, + self._dcs_intermediates, + self._dcs_final, + bytes(self._str_buf), + ) + self._str_buf.clear() + self._str_overflow = False + self._dcs_intermediates = b"" + self._reset_csi() + + def _dispatch_apc(self, sink: ActionSink) -> None: + if self._str_kind == 0x5F and not self._str_overflow: + sink.on_apc(bytes(self._str_buf)) + self._str_buf.clear() + self._str_overflow = False + self._str_kind = 0 + + def _cached_csi_params(self, pbytes: bytes) -> CsiParams: + if not pbytes: + return EMPTY_PARAMS + cached = self._csi_memo.get(pbytes) + if cached is not None: + return cached + parsed = _parse_csi_param_bytes( + pbytes, + max_params=self._limits.max_csi_params, + ) + if len(self._csi_memo) >= _MEMO_LIMIT: + del self._csi_memo[next(iter(self._csi_memo))] + self._csi_memo[pbytes] = parsed + return parsed + + def feed(self, data: collections.abc.Buffer) -> list[Action]: + """Feed *data* and return all completed :data:`Action` items.""" + sink = _ListSink() + self.feed_to(data, sink) + return sink.actions + + def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None: + """Feed *data* directly into *sink* without allocating action wrappers.""" + mv = memoryview(data).cast("B") + n = len(mv) + pos = 0 + c1 = self._c1_controls + max_osc = self._limits.max_osc_bytes + max_dcs = self._limits.max_dcs_bytes + max_apc = self._limits.max_apc_bytes + + while pos < n: + state = self._state + + if state == ParserState.GROUND: + if c1: + if not self._utf8_pending and 0x80 <= mv[pos] <= 0x9F: + b_c1 = mv[pos] + pos += 1 + if b_c1 == 0x9B: + self._reset_csi() + self._state = ParserState.CSI_ENTRY + elif b_c1 == 0x9D: + self._str_buf.clear() + self._str_overflow = False + self._state = ParserState.OSC_STRING + elif b_c1 == 0x90: + self._reset_csi() + self._str_buf.clear() + self._str_overflow = False + self._state = ParserState.DCS_ENTRY + elif b_c1 in (0x98, 0x9E, 0x9F): + self._str_buf.clear() + self._str_overflow = False + self._str_kind = b_c1 - 0x40 + self._state = ParserState.SOS_PM_APC_STRING + elif b_c1 != 0x9C: + sink.on_esc(b"", b_c1 - 0x40) + continue + end = pos + while end < n and 0x20 <= mv[end] <= 0x7E: + end += 1 + if end > pos and not self._utf8_pending: + sink.on_print(bytes(mv[pos:end]).decode("ascii")) + pos = end + if pos >= n: + break + continue + if mv[pos] >= 0x80: + self._decode_utf8_bytes(mv[pos : pos + 1], sink) + pos += 1 + continue + else: + match = _CTRL_RE.search(mv, pos) + end = match.start() if match is not None else n + if end > pos: + span = mv[pos:end] + if not self._utf8_pending: + raw_span = bytes(span) + if raw_span.isascii(): + sink.on_print(raw_span.decode("ascii")) + pos = end + if pos >= n: + break + else: + self._decode_utf8_bytes(raw_span, sink) + pos = end + if pos >= n: + break + else: + self._decode_utf8_bytes(span, sink) + pos = end + if pos >= n: + break + + b = mv[pos] + pos += 1 + if b == 0x1B: + self._flush_incomplete_utf8(sink) + if pos < n and mv[pos] == 0x5B: # '[' -> CSI fast path + csi_m = _CSI_FAST_RE.match(mv, pos + 1) + if csi_m is not None: + pfx_b, p_mv, fin_b = csi_m.groups() + pfx = pfx_b[0] if pfx_b else 0 + params = self._cached_csi_params(bytes(p_mv)) + sink.on_csi(pfx, params, b"", fin_b[0]) + pos = csi_m.end() + continue + self._intermediates.clear() + self._return_from_esc_st = None + self._state = ParserState.ESCAPE + elif b == 0x7F: + pass + else: + # Flush incomplete UTF-8 BEFORE executing any C0 control! + self._flush_incomplete_utf8(sink) + sink.on_execute(b) + continue + + # String states: bulk-scan up to ESC / BEL / CAN / SUB (or 0x9C if c1). + if state == ParserState.OSC_STRING: + start = pos + while pos < n: + b_scan = mv[pos] + if b_scan in (0x07, 0x18, 0x1A, 0x1B) or (c1 and b_scan == 0x9C): + break + pos += 1 + if pos > start and not self._str_overflow: + chunk_len = pos - start + if len(self._str_buf) + chunk_len <= max_osc: + self._str_buf.extend(mv[start:pos]) + else: + self._str_buf.clear() + self._str_overflow = True + if pos >= n: + break + b = mv[pos] + pos += 1 + if b == 0x07: + self._dispatch_osc(sink, b"\x07") + self._state = ParserState.GROUND + elif c1 and b == 0x9C: + self._dispatch_osc(sink, b"\x9c") + self._state = ParserState.GROUND + elif b == 0x1B: + self._return_from_esc_st = ParserState.OSC_STRING + self._intermediates.clear() + self._state = ParserState.ESCAPE + else: # CAN (0x18) or SUB (0x1A) + self._str_buf.clear() + self._str_overflow = False + self._state = ParserState.GROUND + continue + + if state == ParserState.DCS_PASSTHROUGH: + start = pos + while pos < n: + b_scan = mv[pos] + if b_scan in (0x18, 0x1A, 0x1B, 0x7F) or (c1 and b_scan == 0x9C): + break + pos += 1 + if pos > start and not self._str_overflow: + chunk_len = pos - start + if len(self._str_buf) + chunk_len <= max_dcs: + self._str_buf.extend(mv[start:pos]) + else: + self._str_buf.clear() + self._str_overflow = True + if pos >= n: + break + b = mv[pos] + pos += 1 + if b == 0x7F: + continue + if c1 and b == 0x9C: + self._dispatch_dcs(sink) + self._state = ParserState.GROUND + elif b == 0x1B: + self._return_from_esc_st = ParserState.DCS_PASSTHROUGH + self._intermediates.clear() + self._state = ParserState.ESCAPE + else: + self._str_buf.clear() + self._str_overflow = False + self._reset_csi() + self._state = ParserState.GROUND + continue + + if state == ParserState.SOS_PM_APC_STRING: + start = pos + while pos < n: + b_scan = mv[pos] + if b_scan in (0x18, 0x1A, 0x1B) or (c1 and b_scan == 0x9C): + break + pos += 1 + if pos > start and self._str_kind == 0x5F and not self._str_overflow: + chunk_len = pos - start + if len(self._str_buf) + chunk_len <= max_apc: + self._str_buf.extend(mv[start:pos]) + else: + self._str_buf.clear() + self._str_overflow = True + if pos >= n: + break + b = mv[pos] + pos += 1 + if c1 and b == 0x9C: + self._dispatch_apc(sink) + self._state = ParserState.GROUND + elif b == 0x1B: + self._return_from_esc_st = ParserState.SOS_PM_APC_STRING + self._intermediates.clear() + self._state = ParserState.ESCAPE + else: + self._str_buf.clear() + self._str_overflow = False + self._str_kind = 0 + self._state = ParserState.GROUND + continue + + b = mv[pos] + pos += 1 + + if b == 0x1B: + if ( + state == ParserState.ESCAPE + and self._return_from_esc_st == ParserState.DCS_PASSTHROUGH + and self._dcs_final == 0x74 + and self._csi_prefix == 0 + and not self._dcs_intermediates + and self._str_buf.startswith(b"mux;") + ): + if not self._str_overflow: + if len(self._str_buf) + 1 <= max_dcs: + self._str_buf.append(0x1B) + else: + self._str_buf.clear() + self._str_overflow = True + self._return_from_esc_st = None + self._state = ParserState.DCS_PASSTHROUGH + continue + # Double-ESC inside a non-passthrough string aborts it cleanly. + if self._return_from_esc_st is not None: + self._str_buf.clear() + self._str_overflow = False + self._str_kind = 0 + self._dcs_intermediates = b"" + self._return_from_esc_st = None + self._intermediates.clear() + self._state = ParserState.ESCAPE + continue + + if b in (0x18, 0x1A): + self._str_buf.clear() + self._str_overflow = False + self._str_kind = 0 + self._return_from_esc_st = None + self._reset_csi() + self._state = ParserState.GROUND + continue + + if state == ParserState.DCS_IGNORE: + if c1 and b == 0x9C: + self._reset_csi() + self._state = ParserState.GROUND + continue + + if b < 0x20: + sink.on_execute(b) + continue + if b == 0x7F: + continue + + if state == ParserState.ESCAPE: + prev_str = self._return_from_esc_st + self._return_from_esc_st = None + if prev_str is not None and b == 0x5C: # 'ESC \' -> 7-bit ST + if prev_str == ParserState.OSC_STRING: + self._dispatch_osc(sink, b"\x1b\\") + elif prev_str == ParserState.DCS_PASSTHROUGH: + self._dispatch_dcs(sink) + elif prev_str == ParserState.SOS_PM_APC_STRING: + self._dispatch_apc(sink) + self._state = ParserState.GROUND + continue + if prev_str is not None: + self._str_buf.clear() + self._str_overflow = False + self._str_kind = 0 + + if 0x20 <= b <= 0x2F: + self._intermediates.append(b) + self._state = ParserState.ESCAPE_INTERMEDIATE + elif b == 0x5B: # '[' -> CSI + self._reset_csi() + self._state = ParserState.CSI_ENTRY + elif b == 0x5D: # ']' -> OSC + self._str_buf.clear() + self._str_overflow = False + self._state = ParserState.OSC_STRING + elif b == 0x50: # 'P' -> DCS + self._reset_csi() + self._str_buf.clear() + self._str_overflow = False + self._state = ParserState.DCS_ENTRY + elif b in (0x58, 0x5E, 0x5F): # SOS, PM, APC + self._str_buf.clear() + self._str_overflow = False + self._str_kind = b + self._state = ParserState.SOS_PM_APC_STRING + elif 0x30 <= b <= 0x7E: + sink.on_esc(b"", b) + self._state = ParserState.GROUND + else: + self._state = ParserState.GROUND + + elif state == ParserState.ESCAPE_INTERMEDIATE: + if 0x20 <= b <= 0x2F: + if len(self._intermediates) < MAX_INTERMEDIATES: + self._intermediates.append(b) + elif 0x30 <= b <= 0x7E: + sink.on_esc(bytes(self._intermediates), b) + self._intermediates.clear() + self._state = ParserState.GROUND + else: + self._state = ParserState.GROUND + + elif state in (ParserState.CSI_ENTRY, ParserState.CSI_PARAM): + if state == ParserState.CSI_ENTRY and 0x3C <= b <= 0x3F: + self._csi_prefix = b + self._state = ParserState.CSI_PARAM + elif 0x30 <= b <= 0x39: + self._csi_cur = min( + _PARAM_CLAMP, + self._csi_cur * 10 + (b - 0x30), + ) + self._csi_has_digit = True + self._state = ParserState.CSI_PARAM + elif b == 0x3B: + self._push_param(next_is_colon=False) + self._state = ParserState.CSI_PARAM + elif b == 0x3A: + self._push_param(next_is_colon=True) + self._state = ParserState.CSI_PARAM + elif 0x20 <= b <= 0x2F: + self._intermediates.append(b) + self._state = ParserState.CSI_INTERMEDIATE + elif 0x40 <= b <= 0x7E: + params = self._finalize_params() + sink.on_csi( + self._csi_prefix, + params, + bytes(self._intermediates), + b, + ) + self._state = ParserState.GROUND + else: + self._state = ParserState.CSI_IGNORE + + elif state == ParserState.CSI_INTERMEDIATE: + if 0x20 <= b <= 0x2F: + if len(self._intermediates) < MAX_INTERMEDIATES: + self._intermediates.append(b) + elif 0x40 <= b <= 0x7E: + params = self._finalize_params() + sink.on_csi( + self._csi_prefix, + params, + bytes(self._intermediates), + b, + ) + self._state = ParserState.GROUND + else: + self._state = ParserState.CSI_IGNORE + + elif state == ParserState.CSI_IGNORE: + if 0x40 <= b <= 0x7E: + self._reset_csi() + self._state = ParserState.GROUND + + elif state in (ParserState.DCS_ENTRY, ParserState.DCS_PARAM): + if state == ParserState.DCS_ENTRY and 0x3C <= b <= 0x3F: + self._csi_prefix = b + self._state = ParserState.DCS_PARAM + elif 0x30 <= b <= 0x39: + self._csi_cur = min( + _PARAM_CLAMP, + self._csi_cur * 10 + (b - 0x30), + ) + self._csi_has_digit = True + self._state = ParserState.DCS_PARAM + elif b == 0x3B: + self._push_param(next_is_colon=False) + self._state = ParserState.DCS_PARAM + elif b == 0x3A: + self._push_param(next_is_colon=True) + self._state = ParserState.DCS_PARAM + elif 0x20 <= b <= 0x2F: + self._intermediates.append(b) + self._state = ParserState.DCS_INTERMEDIATE + elif 0x40 <= b <= 0x7E: + self._dcs_params = self._finalize_params() + self._dcs_intermediates = bytes(self._intermediates) + self._dcs_final = b + self._str_buf.clear() + self._str_overflow = False + self._state = ParserState.DCS_PASSTHROUGH + else: + self._state = ParserState.DCS_IGNORE + + elif state == ParserState.DCS_INTERMEDIATE: + if 0x20 <= b <= 0x2F: + if len(self._intermediates) < MAX_INTERMEDIATES: + self._intermediates.append(b) + elif 0x40 <= b <= 0x7E: + self._dcs_params = self._finalize_params() + self._dcs_intermediates = bytes(self._intermediates) + self._dcs_final = b + self._str_buf.clear() + self._str_overflow = False + self._state = ParserState.DCS_PASSTHROUGH + else: + self._state = ParserState.DCS_IGNORE + + +__all__ = [ + "EMPTY_PARAMS", + "Action", + "ActionSink", + "ApcDispatch", + "CsiDispatch", + "CsiParams", + "DcsDispatch", + "EscDispatch", + "Execute", + "OscDispatch", + "Parser", + "ParserState", + "Print", + "parse_sgr", +] diff --git a/src/libvt/pytest_plugin.py b/src/libvt/pytest_plugin.py index 1936d84..8886b5f 100644 --- a/src/libvt/pytest_plugin.py +++ b/src/libvt/pytest_plugin.py @@ -1,5 +1,145 @@ -"""Pytest plugin entry point for libvt.""" +"""Import-light ``pytest11`` plugin providing ``vt_*`` fixtures.""" from __future__ import annotations -__all__: list[str] = [] +import sys +import typing as t + +import pytest + +if t.TYPE_CHECKING: + import collections.abc + import os + + from libvt.aio import PtySession + from libvt.config import Limits, Policy, Profile + from libvt.events import Event + from libvt.parser import Parser + from libvt.terminal import FlightRecorder, Terminal + + +class TerminalFactory(t.Protocol): + """Typed callable protocol returned by the :func:`vt_factory` fixture.""" + + def __call__( + self, + *, + rows: int = 24, + cols: int = 80, + scrollback: int = 2_000, + profile: Profile = ..., + policy: Policy = ..., + limits: Limits = ..., + on_event: collections.abc.Callable[[Event], None] | None = None, + record_events: bool = False, + recorder: FlightRecorder | None = None, + ) -> Terminal: + """Create a configured :class:`~libvt.terminal.Terminal` instance.""" + + +class PtyFactory(t.Protocol): + """Typed async context-manager factory returned by :func:`vt_pty`.""" + + def __call__( + self, + argv: collections.abc.Sequence[str], + *, + rows: int = 24, + cols: int = 80, + env: collections.abc.Mapping[str, str] | None = None, + cwd: str | os.PathLike[str] | None = None, + ) -> contextlib.AbstractAsyncContextManager[PtySession]: + """Open a POSIX PTY subprocess session.""" + + +if t.TYPE_CHECKING: + import contextlib + + +@pytest.fixture +def vt_recorder() -> FlightRecorder: + """Return a fresh 4 KiB :class:`~libvt.terminal.FlightRecorder`.""" + from libvt.terminal import FlightRecorder + + return FlightRecorder() + + +@pytest.fixture +def vt_terminal(vt_recorder: FlightRecorder) -> Terminal: + """Return a fresh ``24x80`` :class:`~libvt.terminal.Terminal` with recorder.""" + from libvt.terminal import Terminal + + return Terminal(rows=24, cols=80, recorder=vt_recorder) + + +@pytest.fixture +def vt_factory() -> TerminalFactory: + """Return a typed factory creating :class:`~libvt.terminal.Terminal` instances.""" + from libvt.config import DEFAULT_LIMITS, DEFAULT_POLICY, DEFAULT_PROFILE + from libvt.terminal import Terminal + + def _make( + *, + rows: int = 24, + cols: int = 80, + scrollback: int = 2_000, + profile: Profile = DEFAULT_PROFILE, + policy: Policy = DEFAULT_POLICY, + limits: Limits = DEFAULT_LIMITS, + on_event: collections.abc.Callable[[Event], None] | None = None, + record_events: bool = False, + recorder: FlightRecorder | None = None, + ) -> Terminal: + return Terminal( + rows=rows, + cols=cols, + scrollback=scrollback, + profile=profile, + policy=policy, + limits=limits, + on_event=on_event, + record_events=record_events, + recorder=recorder, + ) + + return _make + + +@pytest.fixture +def vt_parser() -> Parser: + """Return a fresh streaming :class:`~libvt.parser.Parser`.""" + from libvt.parser import Parser + + return Parser() + + +@pytest.fixture +def vt_pty() -> PtyFactory: + """Return a POSIX :func:`~libvt.aio.open_pty` factory (skips on Windows).""" + if sys.platform == "win32": + pytest.skip("vt_pty requires POSIX pty.openpty()") + + from libvt.aio import open_pty + + def _spawn( + argv: collections.abc.Sequence[str], + *, + rows: int = 24, + cols: int = 80, + env: collections.abc.Mapping[str, str] | None = None, + cwd: str | os.PathLike[str] | None = None, + ) -> contextlib.AbstractAsyncContextManager[PtySession]: + return open_pty(argv, rows=rows, cols=cols, env=env, cwd=cwd) + + return _spawn + + +__all__ = [ + "PtyFactory", + "TerminalFactory", + "vt_factory", + "vt_parser", + "vt_pty", + "vt_recorder", + "vt_terminal", +] diff --git a/src/libvt/screen.py b/src/libvt/screen.py new file mode 100644 index 0000000..6c5b6d6 --- /dev/null +++ b/src/libvt/screen.py @@ -0,0 +1,927 @@ +"""Zero-based screen buffer, lazy cell/row/region views, reflow, and dual screens.""" + +from __future__ import annotations + +import collections +import collections.abc +import enum +import typing as t +from dataclasses import dataclass + +from libvt._grid import ( + _WIDTH_CLEAR_MASK, + FrozenRow, + RowLike, + _CellExt, + _Row, + raw_width_bits, + unpack_style, + unpack_width_role, +) +from libvt._ucd import WidthRole +from libvt.input import KittyKeyboardStack +from libvt.style import DEFAULT_STYLE, Hyperlink, Style + + +class CursorShape(enum.StrEnum): + """Cursor glyph shape configured via ``DECSCUSR`` (``CSI Ps SP q``).""" + + BLOCK = "block" + UNDERLINE = "underline" + BAR = "bar" + + +@dataclass(frozen=True, slots=True) +class Cursor: + """Zero-based cursor state on a :class:`Screen`. + + Attributes + ---------- + row : int + Zero-based row index in ``0..rows - 1``. + col : int + Zero-based column index in ``0..cols - 1``. + visible : bool + Whether the cursor is visible (``DECTCEM`` ``?25``). + shape : CursorShape + Visual cursor shape. + blinking : bool + Whether cursor blinking is active. + pending_wrap : bool + ``True`` when a glyph filled ``cols - 1`` under ``DECAWM`` and the + next printable character will wrap to the next line. + """ + + row: int = 0 + col: int = 0 + visible: bool = True + shape: CursorShape = CursorShape.BLOCK + blinking: bool = True + pending_wrap: bool = False + + +@dataclass(frozen=True, slots=True) +class ScrollRegion: + """Inclusive zero-based scroll margin bounds (``DECSTBM`` / ``DECSLRM``). + + Attributes + ---------- + top : int + Top margin row index (inclusive, ``0``-based). + bottom : int + Bottom margin row index (inclusive, ``0``-based). + left : int + Left margin column index (inclusive, ``0``-based). + right : int + Right margin column index (inclusive, ``0``-based). + """ + + top: int + bottom: int + left: int + right: int + + +@dataclass(frozen=True, slots=True) +class Cell: + """Immutable view of a single terminal grid cell. + + Attributes + ---------- + text : str + Grapheme cluster string (``" "`` for narrow blanks, ``""`` for + :attr:`WidthRole.SPACER_TAIL` and :attr:`WidthRole.SPACER_HEAD`). + style : Style + Unpacked SGR rendition attributes. + width_role : WidthRole + Column occupancy role (narrow, wide lead, or spacer). + hyperlink : Hyperlink | None + Active ``OSC 8`` hyperlink, when present. + protected : bool + ``DECSCA`` protection attribute respected by ``DECSED`` / ``DECSEL``. + """ + + text: str = " " + style: Style = DEFAULT_STYLE + width_role: WidthRole = WidthRole.NARROW + hyperlink: Hyperlink | None = None + protected: bool = False + + @property + def width(self) -> int: + """Return column width (``2`` wide, ``0`` spacer, ``1`` narrow).""" + if self.width_role == WidthRole.WIDE: + return 2 + if self.width_role in (WidthRole.SPACER_TAIL, WidthRole.SPACER_HEAD): + return 0 + return 1 + + @property + def is_blank(self) -> bool: + """Return ``True`` when the cell holds an unstyled narrow space.""" + return ( + self.text == " " + and self.style == DEFAULT_STYLE + and self.width_role == WidthRole.NARROW + and self.hyperlink is None + ) + + +BLANK_CELL = Cell() + + +@dataclass(frozen=True, slots=True) +class RowRun: + """Contiguous run of identically styled cells within a :class:`RowView`. + + Attributes + ---------- + start_col : int + Inclusive zero-based start column. + end_col : int + Exclusive zero-based end column. + text : str + Rendered text across ``start_col..end_col`` (omitting spacer empty strings). + style : Style + Shared :class:`~libvt.style.Style` across the run. + hyperlink : Hyperlink | None + Shared ``OSC 8`` hyperlink across the run, if any. + """ + + start_col: int + end_col: int + text: str + style: Style = DEFAULT_STYLE + hyperlink: Hyperlink | None = None + + +def _materialize_cell(row: RowLike, col: int) -> Cell: + ch = row.chars[col] if isinstance(row, _Row) else row.char_at(col) + word = row.attr_at(col) + if word == 0 and ch == " ": + return BLANK_CELL + ext = row.ext_at(col) + style = unpack_style(word, ext) + role = unpack_width_role(word) + hyperlink = ext.hyperlink if ext is not None else None + protected = bool(ext is not None and ext.protected) + return Cell( + text=ch, + style=style, + width_role=role, + hyperlink=hyperlink, + protected=protected, + ) + + +def _normalize_index(idx: int, length: int, *, axis: str) -> int: + norm = idx + length if idx < 0 else idx + if norm < 0 or norm >= length: + msg = f"{axis} index {idx} out of range for size {length}" + raise IndexError(msg) + return norm + + +def _slice_indices(s: slice, length: int) -> range: + start, stop, step = s.indices(length) + if step != 1: + msg = "grid slices only support step=1" + raise ValueError(msg) + return range(start, stop) + + +class RowView(collections.abc.Sequence[Cell]): + """Read-only sequence view over one live viewport or scrollback row.""" + + __slots__ = ("_col_range", "_row") + + def __init__(self, row: RowLike, col_range: range | None = None) -> None: + self._row = row + total_cols = len(row.chars) if isinstance(row, _Row) else row.cols + self._col_range = range(total_cols) if col_range is None else col_range + + @property + def wrapped(self) -> bool: + """Return ``True`` when this row soft-wrapped onto the next line.""" + return self._row.wrapped + + @property + def text(self) -> str: + """Return right-trimmed rendered text for this row slice.""" + total_cols = ( + len(self._row.chars) if isinstance(self._row, _Row) else self._row.cols + ) + if self._col_range.start == 0 and self._col_range.stop == total_cols: + return self._row.rstrip_text() + limit = min(self._col_range.stop, self._row.used) + if limit <= self._col_range.start: + return "" + if isinstance(self._row, _Row): + raw = "".join(self._row.chars[self._col_range.start : limit]) + else: + raw = "".join( + self._row.char_at(c) for c in range(self._col_range.start, limit) + ) + return raw.rstrip(" ") + + @property + def runs(self) -> tuple[RowRun, ...]: + """Return coalesced ``(style, hyperlink)`` spans up to ``used`` columns.""" + limit = min(self._col_range.stop, self._row.used) + start_c = self._col_range.start + if limit <= start_c: + return () + out: list[RowRun] = [] + run_start = start_c + first_ext = self._row.ext_at(start_c) + cur_style = unpack_style(self._row.attr_at(start_c), first_ext) + cur_link = first_ext.hyperlink if first_ext is not None else None + buf: list[str] = [] + + for c in range(start_c, limit): + word = self._row.attr_at(c) + role_bits = raw_width_bits(word) + if role_bits in (int(WidthRole.SPACER_TAIL), int(WidthRole.SPACER_HEAD)): + continue + ext = self._row.ext_at(c) + st = unpack_style(word, ext) + lnk = ext.hyperlink if ext is not None else None + ch = ( + self._row.chars[c] + if isinstance(self._row, _Row) + else self._row.char_at(c) + ) + if st != cur_style or lnk != cur_link: + out.append( + RowRun( + start_col=run_start, + end_col=c, + text="".join(buf), + style=cur_style, + hyperlink=cur_link, + ), + ) + run_start = c + cur_style = st + cur_link = lnk + buf = [ch] + else: + buf.append(ch) + + out.append( + RowRun( + start_col=run_start, + end_col=limit, + text="".join(buf), + style=cur_style, + hyperlink=cur_link, + ), + ) + return tuple(out) + + def __len__(self) -> int: + """Return column count in this view.""" + return len(self._col_range) + + @t.overload + def __getitem__(self, index: int) -> Cell: ... + + @t.overload + def __getitem__(self, index: slice) -> RowView: ... + + def __getitem__(self, index: int | slice) -> Cell | RowView: + """Index one :class:`Cell` or slice a sub-range :class:`RowView`.""" + if isinstance(index, slice): + sub = _slice_indices(index, len(self._col_range)) + base = self._col_range.start + return RowView(self._row, range(base + sub.start, base + sub.stop)) + norm = _normalize_index(index, len(self._col_range), axis="col") + return _materialize_cell(self._row, self._col_range.start + norm) + + +class RegionView(collections.abc.Sequence[RowView]): + """Read-only 2D rectangular slice view over ``(rows, cols)``.""" + + __slots__ = ("_col_range", "_rows") + + def __init__( + self, rows: collections.abc.Sequence[RowLike], col_range: range + ) -> None: + self._rows = tuple(rows) + self._col_range = col_range + + @property + def rows(self) -> int: + """Return height of this region in rows.""" + return len(self._rows) + + @property + def cols(self) -> int: + """Return width of this region in columns.""" + return len(self._col_range) + + @property + def lines(self) -> tuple[str, ...]: + """Return right-trimmed text for each row in the region.""" + return tuple(RowView(r, self._col_range).text for r in self._rows) + + @property + def text(self) -> str: + """Return newline-joined text with trailing empty rows omitted.""" + lines = list(self.lines) + while lines and lines[-1] == "": + lines.pop() + return "\n".join(lines) + + def __len__(self) -> int: + """Return number of rows in this region.""" + return len(self._rows) + + @t.overload + def __getitem__(self, key: int) -> RowView: ... + + @t.overload + def __getitem__(self, key: slice) -> RegionView: ... + + @t.overload + def __getitem__(self, key: tuple[int, int]) -> Cell: ... + + def __getitem__( + self, + key: int | slice | tuple[int, int], + ) -> RowView | RegionView | Cell: + """Index a row, sub-region, or ``(row, col)`` cell within this region.""" + if isinstance(key, tuple): + r_idx, c_idx = key + nr = _normalize_index(r_idx, len(self._rows), axis="row") + nc = _normalize_index(c_idx, len(self._col_range), axis="col") + return _materialize_cell(self._rows[nr], self._col_range.start + nc) + if isinstance(key, slice): + sub = _slice_indices(key, len(self._rows)) + return RegionView(self._rows[sub.start : sub.stop], self._col_range) + nr = _normalize_index(key, len(self._rows), axis="row") + return RowView(self._rows[nr], self._col_range) + + +def format_rows_text(rows: collections.abc.Sequence[RowLike]) -> str: + """Format *rows* as newline-joined text omitting trailing blank lines.""" + lines = [r.rstrip_text() for r in rows] + while lines and lines[-1] == "": + lines.pop() + return "\n".join(lines) + + +def slice_grid( + rows: collections.abc.Sequence[RowLike], + cols: int, + key: int | slice | tuple[slice | int, slice | int], +) -> RowView | Cell | RegionView: + """Implement ``grid[r]``, ``grid[r, c]``, and ``grid[r1:r2, c1:c2]``.""" + height = len(rows) + if isinstance(key, int): + nr = _normalize_index(key, height, axis="row") + return RowView(rows[nr]) + if isinstance(key, slice): + r_range = _slice_indices(key, height) + return RegionView(rows[r_range.start : r_range.stop], range(cols)) + + r_key, c_key = key + if isinstance(r_key, int) and isinstance(c_key, int): + nr = _normalize_index(r_key, height, axis="row") + nc = _normalize_index(c_key, cols, axis="col") + return _materialize_cell(rows[nr], nc) + if isinstance(r_key, int) and isinstance(c_key, slice): + nr = _normalize_index(r_key, height, axis="row") + c_range = _slice_indices(c_key, cols) + return RegionView((rows[nr],), c_range) + if isinstance(r_key, slice) and isinstance(c_key, int): + r_range = _slice_indices(r_key, height) + nc = _normalize_index(c_key, cols, axis="col") + return RegionView(rows[r_range.start : r_range.stop], range(nc, nc + 1)) + if isinstance(r_key, slice) and isinstance(c_key, slice): + r_range = _slice_indices(r_key, height) + c_range = _slice_indices(c_key, cols) + return RegionView(rows[r_range.start : r_range.stop], c_range) + msg = f"unsupported grid index {key!r}" + raise TypeError(msg) + + +class Screen: + """Mutable 2D character grid with ``FrozenRow`` RLE scrollback and reflow.""" + + __slots__ = ( + "_cols", + "_cur_blinking", + "_cur_col", + "_cur_row", + "_cur_shape", + "_cur_visible", + "_history", + "_pending_wrap", + "_rows", + "_scrolled_total", + "_tabstops", + "_tabstops_sorted", + "keyboard_stack", + "scroll_region", + ) + + def __init__( + self, + *, + rows: int = 24, + cols: int = 80, + scrollback: int = 2_000, + keyboard_stack_depth: int = 8, + ) -> None: + if rows < 1 or cols < 1: + msg = f"rows and cols must be >= 1, got ({rows}, {cols})" + raise ValueError(msg) + self._cols = cols + self._rows: list[_Row] = [_Row(cols) for _ in range(rows)] + self._history: collections.deque[FrozenRow] = collections.deque( + maxlen=max(0, scrollback), + ) + self._scrolled_total: int = 0 + self._cur_row: int = 0 + self._cur_col: int = 0 + self._cur_visible: bool = True + self._cur_shape: CursorShape = CursorShape.BLOCK + self._cur_blinking: bool = True + self._pending_wrap: bool = False + self.scroll_region = ScrollRegion( + top=0, + bottom=rows - 1, + left=0, + right=cols - 1, + ) + self._tabstops: set[int] = set(range(8, cols, 8)) + self._tabstops_sorted: list[int] = sorted(self._tabstops) + self.keyboard_stack = KittyKeyboardStack(max_depth=keyboard_stack_depth) + + @property + def rows(self) -> int: + """Return visible screen height in rows.""" + return len(self._rows) + + @property + def cols(self) -> int: + """Return screen width in columns.""" + return self._cols + + @property + def scrolled_total(self) -> int: + """Return cumulative primary rows scrolled off the top margin.""" + return self._scrolled_total + + @property + def cursor(self) -> Cursor: + """Return current zero-based :class:`Cursor`.""" + return Cursor( + row=self._cur_row, + col=self._cur_col, + visible=self._cur_visible, + shape=self._cur_shape, + blinking=self._cur_blinking, + pending_wrap=self._pending_wrap, + ) + + @cursor.setter + def cursor(self, value: Cursor) -> None: + self._cur_row = value.row + self._cur_col = value.col + self._cur_visible = value.visible + self._cur_shape = value.shape + self._cur_blinking = value.blinking + self._pending_wrap = value.pending_wrap + + @property + def history(self) -> tuple[RowView, ...]: + """Return immutable :class:`RowView` sequence over sealed scrollback rows.""" + return tuple(RowView(fr) for fr in self._history) + + @property + def tabstops(self) -> tuple[int, ...]: + """Return sorted horizontal tabstop columns.""" + return tuple(self._tabstops_sorted) + + def add_tabstop(self, col: int) -> None: + """Set a horizontal tabstop at *col* (``HTS``).""" + if 0 <= col < self._cols and col not in self._tabstops: + self._tabstops.add(col) + self._tabstops_sorted = sorted(self._tabstops) + + def clear_tabstop(self, col: int) -> None: + """Remove the horizontal tabstop at *col* (``TBC 0``).""" + if col in self._tabstops: + self._tabstops.discard(col) + self._tabstops_sorted = sorted(self._tabstops) + + def clear_all_tabstops(self) -> None: + """Remove all horizontal tabstops (``TBC 3``).""" + self._tabstops.clear() + self._tabstops_sorted.clear() + + def clear_history(self) -> None: + """Clear all sealed scrollback rows (``ED 3``).""" + self._history.clear() + + @property + def lines(self) -> tuple[str, ...]: + """Return right-trimmed text for every visible row.""" + return tuple(r.rstrip_text() for r in self._rows) + + @property + def text(self) -> str: + """Return visible screen text with trailing blank rows omitted.""" + return format_rows_text(self._rows) + + @t.overload + def __getitem__(self, key: int) -> RowView: ... + + @t.overload + def __getitem__(self, key: tuple[int, int]) -> Cell: ... + + @t.overload + def __getitem__( + self, + key: slice | tuple[slice | int, slice | int], + ) -> RegionView: ... + + def __getitem__( + self, + key: int | slice | tuple[slice | int, slice | int], + ) -> RowView | Cell | RegionView: + """Index a row, single ``(row, col)`` cell, or 2D region view.""" + return slice_grid(self._rows, self._cols, key) + + def scroll_up( + self, + count: int = 1, + *, + top: int | None = None, + bottom: int | None = None, + left: int = 0, + right: int | None = None, + save_history: bool = True, + bce_word: int = 0, + bce_ext: _CellExt | None = None, + ) -> None: + """Scroll region ``[top..bottom, left..right]`` upward by *count* lines.""" + t_row = self.scroll_region.top if top is None else top + b_row = self.scroll_region.bottom if bottom is None else bottom + r_col = (self._cols - 1) if right is None else right + if count <= 0 or t_row > b_row: + return + shift = min(count, b_row - t_row + 1) + full_width = left == 0 and r_col == self._cols - 1 + + if full_width: + can_save = ( + save_history + and t_row == 0 + and self._history.maxlen is not None + and self._history.maxlen > 0 + ) + evicted = self._rows[t_row : t_row + shift] + if can_save: + for row_ev in evicted: + self._history.append(row_ev.freeze()) + if t_row == 0: + self._scrolled_total += shift + del self._rows[t_row : t_row + shift] + for row_ev in evicted: + row_ev.reset_blank(self._cols, bce_word, bce_ext) + self._rows[b_row - shift + 1 : b_row - shift + 1] = evicted + return + + for dst_r in range(t_row, b_row - shift + 1): + src_row = self._rows[dst_r + shift] + dst_row = self._rows[dst_r] + dst_row._heal_wide_boundary(left) + dst_row._heal_wide_boundary(r_col) + src_row._heal_wide_boundary(left) + src_row._heal_wide_boundary(r_col) + for c in range(left, r_col + 1): + word = src_row.attr_at(c) + role = unpack_width_role(word) + base = word & _WIDTH_CLEAR_MASK + dst_row._set_raw(c, src_row.chars[c], base, role, src_row.ext_at(c)) + dst_row.used = max(dst_row.used, min(src_row.used, r_col + 1)) + + for clr_r in range(b_row - shift + 1, b_row + 1): + self._rows[clr_r].clear_range(left, r_col + 1, bce_word, bce_ext) + + def scroll_down( + self, + count: int = 1, + *, + top: int | None = None, + bottom: int | None = None, + left: int = 0, + right: int | None = None, + bce_word: int = 0, + bce_ext: _CellExt | None = None, + ) -> None: + """Scroll region ``[top..bottom, left..right]`` downward by *count* lines.""" + t_row = self.scroll_region.top if top is None else top + b_row = self.scroll_region.bottom if bottom is None else bottom + r_col = (self._cols - 1) if right is None else right + if count <= 0 or t_row > b_row: + return + shift = min(count, b_row - t_row + 1) + full_width = left == 0 and r_col == self._cols - 1 + + if full_width: + recycled = self._rows[b_row - shift + 1 : b_row + 1] + del self._rows[b_row - shift + 1 : b_row + 1] + for row_ev in recycled: + row_ev.reset_blank(self._cols, bce_word, bce_ext) + self._rows[t_row:t_row] = recycled + return + + for dst_r in range(b_row, t_row + shift - 1, -1): + src_row = self._rows[dst_r - shift] + dst_row = self._rows[dst_r] + dst_row._heal_wide_boundary(left) + dst_row._heal_wide_boundary(r_col) + src_row._heal_wide_boundary(left) + src_row._heal_wide_boundary(r_col) + for c in range(left, r_col + 1): + word = src_row.attr_at(c) + role = unpack_width_role(word) + base = word & _WIDTH_CLEAR_MASK + dst_row._set_raw(c, src_row.chars[c], base, role, src_row.ext_at(c)) + dst_row.used = max(dst_row.used, min(src_row.used, r_col + 1)) + + for clr_r in range(t_row, t_row + shift): + self._rows[clr_r].clear_range(left, r_col + 1, bce_word, bce_ext) + + def push_scrollback_and_clear( + self, + bce_word: int = 0, + bce_ext: _CellExt | None = None, + ) -> None: + """Push active lines up to last non-blank row into history (``CSI 22 J``).""" + last_used = -1 + for idx in range(len(self._rows) - 1, -1, -1): + if self._rows[idx].used > 0 or idx == self._cur_row: + last_used = idx + break + if ( + last_used >= 0 + and self._history.maxlen is not None + and self._history.maxlen > 0 + ): + for idx in range(last_used + 1): + self._history.append(self._rows[idx].freeze()) + self._scrolled_total += last_used + 1 + for r in self._rows: + r.reset_blank(self._cols, bce_word, bce_ext) + + def _reflow_primary(self, *, rows: int, cols: int) -> None: + hist_thawed = [fr.thaw() for fr in self._history] + hist_len = len(hist_thawed) + + # Trim trailing unwritten blank rows strictly below the cursor. + last_active = self._cur_row + for r_idx in range(len(self._rows) - 1, self._cur_row, -1): + if self._rows[r_idx].used > 0 or self._rows[r_idx].wrapped: + last_active = r_idx + break + + combined = hist_thawed + self._rows[: last_active + 1] + cur_abs_idx = hist_len + self._cur_row + cur_col = self._cur_col + + new_all: list[_Row] = [] + new_cur_abs = 0 + new_cur_col = 0 + cursor_placed = False + + idx = 0 + total = len(combined) + while idx < total: + group_start = idx + while idx + 1 < total and combined[idx].wrapped: + idx += 1 + group_end = idx + idx += 1 + + # Extract logical cells across [group_start .. group_end]. + cells: list[tuple[str, int, int, _CellExt | None, bool]] = [] + for r_i in range(group_start, group_end + 1): + src = combined[r_i] + is_last = r_i == group_end + limit = len(src.chars) if not is_last else src.used + if r_i == cur_abs_idx: + limit = max(limit, cur_col + 1) + for c_i in range(limit): + word = src.attr_at(c_i) + rb = raw_width_bits(word) + is_cur = r_i == cur_abs_idx and c_i == cur_col + if rb == int(WidthRole.SPACER_HEAD): + if is_cur: + cells.append((" ", 0, 1, None, True)) + continue + if rb == int(WidthRole.SPACER_TAIL): + if is_cur and cells: + prev_ch, prev_w, prev_cw, prev_ext, _ = cells[-1] + cells[-1] = (prev_ch, prev_w, prev_cw, prev_ext, True) + continue + cw = 2 if rb == int(WidthRole.WIDE) else 1 + base_word = word & _WIDTH_CLEAR_MASK + cells.append( + (src.chars[c_i], base_word, cw, src.ext_at(c_i), is_cur) + ) + + if not cells: + empty_row = _Row(cols) + if group_start <= cur_abs_idx <= group_end and not cursor_placed: + new_cur_abs = len(new_all) + new_cur_col = 0 + cursor_placed = True + new_all.append(empty_row) + continue + + cur_out = _Row(cols) + new_all.append(cur_out) + out_col = 0 + for ch, base_w, cw, ce, is_cur in cells: + eff_cw = cw + eff_ch = ch + if eff_cw == 2 and cols == 1: + eff_ch = "\ufffd" + eff_cw = 1 + + if out_col + eff_cw > cols: + if out_col < cols: + cur_out.write_spacer_head(out_col, 0, None) + cur_out.wrapped = True + cur_out = _Row(cols) + new_all.append(cur_out) + out_col = 0 + + if is_cur and not cursor_placed: + new_cur_abs = len(new_all) - 1 + new_cur_col = out_col + cursor_placed = True + + if eff_cw == 2: + cur_out.write_wide(out_col, eff_ch, base_w, ce) + out_col += 2 + else: + cur_out.write_narrow(out_col, eff_ch, base_w, ce) + out_col += 1 + + # Re-trim trailing space added only to track cursor position. + while ( + cur_out.used > 0 + and cur_out.chars[cur_out.used - 1] == " " + and cur_out.attr_at(cur_out.used - 1) == 0 + and cur_out.ext_at(cur_out.used - 1) is None + ): + cur_out.used -= 1 + + if not new_all: + new_all.append(_Row(cols)) + + hist_cut = max(0, len(new_all) - rows) + hist_cut = min(hist_cut, new_cur_abs) + + self._history.clear() + if self._history.maxlen is not None and self._history.maxlen > 0: + for r_h in new_all[:hist_cut]: + self._history.append(r_h.freeze()) + + viewport = new_all[hist_cut : hist_cut + rows] + while len(viewport) < rows: + viewport.append(_Row(cols)) + self._rows = viewport + self._cols = cols + self._cur_row = max(0, min(rows - 1, new_cur_abs - hist_cut)) + self._cur_col = max(0, min(cols - 1, new_cur_col)) + self._pending_wrap = False + + def resize(self, *, rows: int, cols: int, reflow: bool = True) -> None: + """Resize screen to ``(rows, cols)``, optionally reflowing soft wraps.""" + if rows < 1 or cols < 1: + msg = f"rows and cols must be >= 1, got ({rows}, {cols})" + raise ValueError(msg) + + old_cols = self._cols + if reflow and cols != old_cols: + self._reflow_primary(rows=rows, cols=cols) + else: + if cols != old_cols: + for r in self._rows: + r.resize(cols) + self._cols = cols + + cur_rows = len(self._rows) + if rows < cur_rows: + drop_needed = cur_rows - rows + # Keep cursor visible by scrolling excess top rows into history first. + top_excess = max(0, self._cur_row - (rows - 1)) + top_drop = min(drop_needed, top_excess) + if top_drop > 0: + if self._history.maxlen is not None and self._history.maxlen > 0: + for r_ev in self._rows[:top_drop]: + self._history.append(r_ev.freeze()) + self._scrolled_total += top_drop + del self._rows[:top_drop] + self._cur_row -= top_drop + if len(self._rows) > rows: + del self._rows[rows:] + elif rows > cur_rows: + self._rows.extend(_Row(cols) for _ in range(rows - cur_rows)) + + self._cur_row = min(self._cur_row, rows - 1) + self._cur_col = min(self._cur_col, cols - 1) + self._pending_wrap = False + + self.scroll_region = ScrollRegion( + top=0, + bottom=rows - 1, + left=0, + right=cols - 1, + ) + if cols > old_cols: + first_new = ((old_cols // 8) + 1) * 8 + self._tabstops.update(range(first_new, cols, 8)) + else: + self._tabstops = {t for t in self._tabstops if t < cols} + self._tabstops_sorted = sorted(self._tabstops) + + def reset(self) -> None: + """Clear all visible rows, margins, cursor, keyboard stack, and tabstops.""" + rows = len(self._rows) + for r in self._rows: + r.reset_blank(self._cols) + self._cur_row = 0 + self._cur_col = 0 + self._cur_visible = True + self._cur_shape = CursorShape.BLOCK + self._cur_blinking = True + self._pending_wrap = False + self.scroll_region = ScrollRegion( + top=0, + bottom=rows - 1, + left=0, + right=self._cols - 1, + ) + self._tabstops = set(range(8, self._cols, 8)) + self._tabstops_sorted = sorted(self._tabstops) + self.keyboard_stack.reset() + + +class ScreenSet: + """Dual primary and alternate (``?1049``) screen pair.""" + + __slots__ = ("active_is_alt", "alternate", "primary") + + def __init__( + self, + *, + rows: int = 24, + cols: int = 80, + scrollback: int = 2_000, + keyboard_stack_depth: int = 8, + ) -> None: + self.primary = Screen( + rows=rows, + cols=cols, + scrollback=scrollback, + keyboard_stack_depth=keyboard_stack_depth, + ) + self.alternate = Screen( + rows=rows, + cols=cols, + scrollback=0, + keyboard_stack_depth=keyboard_stack_depth, + ) + self.active_is_alt: bool = False + + @property + def active(self) -> Screen: + """Return the currently active :class:`Screen`.""" + return self.alternate if self.active_is_alt else self.primary + + def resize(self, *, rows: int, cols: int, reflow: bool = True) -> None: + """Resize both screens (reflowing primary when *reflow* is ``True``).""" + self.primary.resize(rows=rows, cols=cols, reflow=reflow) + self.alternate.resize(rows=rows, cols=cols, reflow=False) + + +__all__ = [ + "BLANK_CELL", + "Cell", + "Cursor", + "CursorShape", + "RegionView", + "RowRun", + "RowView", + "Screen", + "ScreenSet", + "ScrollRegion", +] diff --git a/src/libvt/status.py b/src/libvt/status.py new file mode 100644 index 0000000..24da82b --- /dev/null +++ b/src/libvt/status.py @@ -0,0 +1,372 @@ +"""Rex / tmux / Ghostty ``OSC 7501`` Program Status protocol parser and store.""" + +from __future__ import annotations + +import base64 +import binascii +import enum +import re +from dataclasses import dataclass + +_APP_RE = re.compile(r"^[A-Za-z0-9_.+-]{1,32}$") +_KEY_RE = re.compile(r"^[a-z]{1,16}$") +_SEG_RE = re.compile(r"^[A-Za-z0-9_.-]+$") + +MAX_WIRE_BYTES = 4_096 +MAX_ID_BYTES = 128 +MAX_ID_DEPTH = 8 +MAX_TITLE_B64_BYTES = 256 +MAX_TITLE_BYTES = 192 +MAX_MSG_B64_BYTES = 2_732 +MAX_MSG_BYTES = 2_048 + +_BIDI_CODEPOINTS: frozenset[int] = frozenset( + { + 0x061C, + *range(0x202A, 0x202F), + *range(0x2066, 0x206A), + }, +) + + +class StatusState(enum.StrEnum): + """Foreground task lifecycle states defined by ``OSC 7501``.""" + + IDLE = "idle" + WORKING = "working" + DONE = "done" + BLOCKED = "blocked" + ERROR = "error" + CLEAR = "clear" + + +class BlockKind(enum.StrEnum): + """Reason categories when :attr:`StatusState.BLOCKED` requests user action.""" + + PERMISSION = "permission" + QUESTION = "question" + AUTH = "auth" + + +_URGENCY_RANK: dict[StatusState, int] = { + StatusState.BLOCKED: 5, + StatusState.ERROR: 4, + StatusState.WORKING: 3, + StatusState.DONE: 2, + StatusState.IDLE: 1, +} + + +@dataclass(frozen=True, slots=True) +class ProgramStatus: + """Validated ``OSC 7501`` (or ``OSC 9;4`` fallback) task status record. + + Attributes + ---------- + state : StatusState + Lifecycle state (``idle``, ``working``, ``done``, ``blocked``, or + ``error``). + id : str + Hierarchical ``/``-delimited task identifier, or ``""`` for the root + foreground task. + kind : BlockKind | None + User-input category when ``state == StatusState.BLOCKED``. + progress : int | None + Completion percentage in ``0..100``, when reported. + app : str | None + Explicit ``app=`` identifier supplied on this record. + effective_app : str | None + ``app`` when present, otherwise inherited from the nearest ancestor + task prefix in :class:`ProgramStatusStore`. + title : str | None + Decoded UTF-8 task title (``<= 192`` UTF-8 bytes). + msg : str | None + Decoded UTF-8 detail message (``<= 2048`` UTF-8 bytes). + """ + + state: StatusState + id: str = "" + kind: BlockKind | None = None + progress: int | None = None + app: str | None = None + effective_app: str | None = None + title: str | None = None + msg: str | None = None + + @property + def value(self) -> str: + """Return ``state.value`` string shorthand.""" + return self.state.value + + +def _validate_id(raw_id: str) -> str | None: + if not raw_id: + return "" + if len(raw_id.encode("utf-8")) > MAX_ID_BYTES: + return None + if raw_id.startswith("/") or raw_id.endswith("/"): + return None + parts = raw_id.split("/") + if len(parts) > MAX_ID_DEPTH: + return None + if not all(_SEG_RE.match(seg) for seg in parts): + return None + return raw_id + + +def _decode_b64_text( + raw: str, + *, + max_b64: int, + max_decoded: int, + allow_tab_newline: bool, +) -> str | None: + if len(raw) > max_b64: + return None + padded = raw + ("=" * ((4 - len(raw) % 4) % 4)) + try: + decoded_bytes = base64.b64decode(padded, validate=True) + except (binascii.Error, ValueError): + return None + if len(decoded_bytes) > max_decoded: + return None + try: + text = decoded_bytes.decode("utf-8", errors="strict") + except UnicodeDecodeError: + return None + for ch in text: + cp = ord(ch) + if cp in _BIDI_CODEPOINTS or 0x7F <= cp <= 0x9F: + return None + if cp < 0x20: + if allow_tab_newline and ch in ("\t", "\n"): + continue + return None + return text + + +class ProgramStatusStore: + """Bounded store managing hierarchical ``OSC 7501`` and ``OSC 9;4`` status.""" + + __slots__ = ("_max_records", "_native_7501_seen", "_records") + + def __init__(self, *, max_records: int = 64) -> None: + self._max_records = max_records + self._records: dict[str, ProgramStatus] = {} + self._native_7501_seen = False + + @property + def records(self) -> dict[str, ProgramStatus]: + """Return a shallow copy of active task records keyed by ``id``.""" + return dict(self._records) + + @property + def most_urgent(self) -> ProgramStatus | None: + """Return the highest-urgency active record (preferring root on ties).""" + if not self._records: + return None + return max( + self._records.values(), + key=lambda r: (_URGENCY_RANK.get(r.state, 0), r.id == ""), + ) + + def _resolve_effective_app( + self, task_id: str, explicit_app: str | None + ) -> str | None: + if explicit_app is not None: + return explicit_app + if not task_id: + return None + parts = task_id.split("/") + for depth in range(len(parts) - 1, 0, -1): + ancestor = "/".join(parts[:depth]) + rec = self._records.get(ancestor) + if rec is not None and rec.effective_app is not None: + return rec.effective_app + root = self._records.get("") + return root.effective_app if root is not None else None + + def apply_osc_7501(self, payload: bytes) -> tuple[bool, ProgramStatus | None]: + """Apply a non-query ``OSC 7501`` byte payload. + + Returns + ------- + tuple[bool, ProgramStatus | None] + ``(changed, updated_or_most_urgent)`` indicating whether store + state changed and the resulting record (or ``None`` after clear). + """ + if not payload or len(payload) > MAX_WIRE_BYTES: + return False, self.most_urgent + try: + text = payload.decode("ascii", errors="strict") + except UnicodeDecodeError: + return False, self.most_urgent + + fields: dict[str, str] = {} + for token in text.split(":"): + if not token: + continue + eq = token.find("=") + if eq <= 0: + return False, self.most_urgent + key = token[:eq] + val = token[eq + 1 :] + if not _KEY_RE.match(key): + return False, self.most_urgent + fields[key] = val + + raw_state = fields.get("state") + if raw_state is None: + return False, self.most_urgent + try: + state = StatusState(raw_state) + except ValueError: + return False, self.most_urgent + + task_id = _validate_id(fields.get("id", "")) + if task_id is None: + return False, self.most_urgent + + self._native_7501_seen = True + + if state == StatusState.CLEAR: + if task_id == "": + if not self._records: + return False, None + self._records.clear() + return True, None + prefix = f"{task_id}/" + to_remove = [ + k for k in self._records if k == task_id or k.startswith(prefix) + ] + if not to_remove: + return False, self.most_urgent + for k in to_remove: + del self._records[k] + return True, self.most_urgent + + kind: BlockKind | None = None + if "kind" in fields: + try: + kind = BlockKind(fields["kind"]) + except ValueError: + return False, self.most_urgent + if state != StatusState.BLOCKED: + kind = None + + progress: int | None = None + if "progress" in fields: + raw_prog = fields["progress"] + if not raw_prog.isdigit(): + return False, self.most_urgent + prog_val = int(raw_prog) + if not 0 <= prog_val <= 100: + return False, self.most_urgent + progress = prog_val + + app: str | None = None + if "app" in fields: + raw_app = fields["app"] + if not _APP_RE.match(raw_app): + return False, self.most_urgent + app = raw_app + + title: str | None = None + if "title" in fields: + title = _decode_b64_text( + fields["title"], + max_b64=MAX_TITLE_B64_BYTES, + max_decoded=MAX_TITLE_BYTES, + allow_tab_newline=False, + ) + if title is None: + return False, self.most_urgent + + msg: str | None = None + if "msg" in fields: + msg = _decode_b64_text( + fields["msg"], + max_b64=MAX_MSG_B64_BYTES, + max_decoded=MAX_MSG_BYTES, + allow_tab_newline=True, + ) + if msg is None: + return False, self.most_urgent + + if task_id not in self._records and len(self._records) >= self._max_records: + # Evict oldest non-root entry when full. + victim = next((k for k in self._records if k != ""), None) + if victim is not None: + del self._records[victim] + else: + return False, self.most_urgent + + effective_app = self._resolve_effective_app(task_id, app) + record = ProgramStatus( + state=state, + id=task_id, + kind=kind, + progress=progress, + app=app, + effective_app=effective_app, + title=title, + msg=msg, + ) + prev = self._records.get(task_id) + self._records[task_id] = record + return prev != record, record + + def apply_osc_9_4( + self, submode: int, value: int | None + ) -> tuple[bool, ProgramStatus | None]: + """Map ConEmu ``OSC 9;4;st;prog`` to root status before ``7501`` arrives.""" + if self._native_7501_seen: + return False, self.most_urgent + prog = None if value is None else max(0, min(100, value)) + if submode == 0: + if "" not in self._records: + return False, self.most_urgent + del self._records[""] + return True, self.most_urgent + if submode in (1, 3): + state = StatusState.WORKING + if submode == 3: + prog = None + elif submode == 2: + state = StatusState.ERROR + elif submode == 4: + state = StatusState.BLOCKED + else: + return False, self.most_urgent + rec = ProgramStatus(state=state, id="", progress=prog) + prev = self._records.get("") + self._records[""] = rec + return prev != rec, rec + + def on_prompt_start(self) -> bool: + """Prune ``working``, ``blocked``, and ``idle`` tasks at shell prompt start.""" + stale = [ + k + for k, r in self._records.items() + if r.state in (StatusState.WORKING, StatusState.BLOCKED, StatusState.IDLE) + ] + for k in stale: + del self._records[k] + return bool(stale) + + def on_process_exit(self) -> bool: + """Prune ``working``, ``blocked``, and ``idle`` tasks on process exit.""" + return self.on_prompt_start() + + def reset(self) -> None: + """Clear all task records and re-enable ``OSC 9;4`` fallback (``RIS``).""" + self._records.clear() + self._native_7501_seen = False + + +__all__ = [ + "BlockKind", + "ProgramStatus", + "ProgramStatusStore", + "StatusState", +] diff --git a/src/libvt/style.py b/src/libvt/style.py new file mode 100644 index 0000000..a4ab883 --- /dev/null +++ b/src/libvt/style.py @@ -0,0 +1,163 @@ +"""Terminal cell colors, SGR attributes, and hyperlink metadata.""" + +from __future__ import annotations + +import enum +from dataclasses import dataclass + + +class AnsiColor(enum.IntEnum): + """Standard and bright ECMA-48 / aixterm 16-color palette indices.""" + + BLACK = 0 + RED = 1 + GREEN = 2 + YELLOW = 3 + BLUE = 4 + MAGENTA = 5 + CYAN = 6 + WHITE = 7 + BRIGHT_BLACK = 8 + BRIGHT_RED = 9 + BRIGHT_GREEN = 10 + BRIGHT_YELLOW = 11 + BRIGHT_BLUE = 12 + BRIGHT_MAGENTA = 13 + BRIGHT_CYAN = 14 + BRIGHT_WHITE = 15 + + +@dataclass(frozen=True, slots=True) +class IndexedColor: + """256-color palette entry (``SGR 38;5;n`` / ``SGR 48;5;n``). + + Attributes + ---------- + index : int + Palette index in ``0..255``. Kept distinct from :class:`AnsiColor` for + indices ``0..15`` so ``SGR 38;5;1`` round-trips separately from + ``SGR 31``. + """ + + index: int + + def __post_init__(self) -> None: + """Validate that ``index`` falls within ``0..255``.""" + if not 0 <= self.index <= 255: + msg = f"IndexedColor index must be in 0..255, got {self.index}" + raise ValueError(msg) + + +@dataclass(frozen=True, slots=True) +class RgbColor: + """24-bit direct RGB color (``SGR 38;2;r;g;b`` / ``SGR 38:2::r:g:b``). + + Attributes + ---------- + r : int + Red channel in ``0..255``. + g : int + Green channel in ``0..255``. + b : int + Blue channel in ``0..255``. + """ + + r: int + g: int + b: int + + def __post_init__(self) -> None: + """Validate that all RGB channels fall within ``0..255``.""" + if not (0 <= self.r <= 255 and 0 <= self.g <= 255 and 0 <= self.b <= 255): + msg = f"RGB channels must be in 0..255, got ({self.r}, {self.g}, {self.b})" + raise ValueError(msg) + + +type Color = AnsiColor | IndexedColor | RgbColor | None + + +class UnderlineStyle(enum.IntEnum): + """ITU T.416 / Kitty extended underline styles (``SGR 4:x``).""" + + NONE = 0 + SINGLE = 1 + DOUBLE = 2 + CURLY = 3 + DOTTED = 4 + DASHED = 5 + + +@dataclass(frozen=True, slots=True) +class Hyperlink: + """``OSC 8`` hyperlink attached to printed cells independent of ``SGR 0``. + + Attributes + ---------- + uri : str + Target URI string. + id : str + Optional explicit ``id=`` parameter grouping multi-line link spans. + """ + + uri: str + id: str = "" + + +@dataclass(frozen=True, slots=True) +class Style: + """Immutable SGR graphic rendition attributes for a cell or active pen. + + Attributes + ---------- + fg : Color + Foreground color, or ``None`` for terminal default foreground. + bg : Color + Background color, or ``None`` for terminal default background. + underline_color : Color + Underline color (``SGR 58``), or ``None`` to inherit foreground. + bold : bool + Bold / increased intensity (``SGR 1``). + dim : bool + Faint / decreased intensity (``SGR 2``). + italic : bool + Italicized glyph posture (``SGR 3``). + underline : UnderlineStyle + Underline style (``SGR 4`` / ``SGR 4:x`` / ``SGR 21``). + blink : bool + Blink attribute (``SGR 5`` / ``SGR 6``). + reverse : bool + Reverse video foreground/background swap (``SGR 7``). + hidden : bool + Concealed / invisible text (``SGR 8``). + strikethrough : bool + Crossed-out text (``SGR 9``). + overline : bool + Overlined text (``SGR 53``). + """ + + fg: Color = None + bg: Color = None + underline_color: Color = None + bold: bool = False + dim: bool = False + italic: bool = False + underline: UnderlineStyle = UnderlineStyle.NONE + blink: bool = False + reverse: bool = False + hidden: bool = False + strikethrough: bool = False + overline: bool = False + + +DEFAULT_STYLE = Style() + +__all__ = [ + "DEFAULT_STYLE", + "AnsiColor", + "Color", + "Hyperlink", + "IndexedColor", + "RgbColor", + "Style", + "UnderlineStyle", +] diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py new file mode 100644 index 0000000..6c95eb9 --- /dev/null +++ b/src/libvt/terminal.py @@ -0,0 +1,2587 @@ +"""Sans-I/O virtual terminal state machine, immutable snapshots, and formatters.""" + +from __future__ import annotations + +import base64 +import binascii +import collections +import collections.abc +import enum +import html +import os +import typing as t +import urllib.parse +from dataclasses import dataclass + +from libvt._grid import ( + FrozenRow, + _CellExt, + _Row, + make_cell_ext, + pack_pen_base, + raw_width_bits, + unpack_style, +) +from libvt._ucd import ( + ClusterState, + WidthRole, + char_width, + sanitize_terminal_text, + step_cluster, +) +from libvt.config import ( + DEFAULT_LIMITS, + DEFAULT_POLICY, + DEFAULT_PROFILE, + Limits, + Policy, + Profile, +) +from libvt.events import ( + Bell, + ClipboardWrite, + ColorSchemeQueried, + EraseCause, + Event, + InBandResize, + KittyCommand, + KittyGraphic, + ProgramStatusChanged, + PromptKind, + PromptMark, + PromptZone, + Rect, + RenderHoldChanged, + ScreenErased, + SixelData, + SixelGraphic, + TitleChanged, + UnhandledSequence, + WorkingDirectoryChanged, +) +from libvt.exc import ProtocolError +from libvt.input import InputEvent, KittyKeyboardFlags, encode_input +from libvt.modes import ( + ALT_SCREEN_MODES, + DEC_PRIVATE_MASK, + TRANSIENT_SNAPSHOT_MODES, + Mode, + ModeState, +) +from libvt.parser import CsiParams, Parser, ParserState, parse_sgr +from libvt.screen import ( + Cell, + Cursor, + CursorShape, + RegionView, + RowView, + Screen, + ScreenSet, + ScrollRegion, + format_rows_text, + slice_grid, +) +from libvt.status import ProgramStatus, ProgramStatusStore +from libvt.style import ( + DEFAULT_STYLE, + AnsiColor, + Color, + Hyperlink, + IndexedColor, + RgbColor, + Style, + UnderlineStyle, +) + +# DEC Special Graphics ('0') mapping for 0x5F..0x7E (VT100 / xterm / tmux tty-acs.c). +_DEC_SPECIAL_GRAPHICS = str.maketrans( + { + "_": " ", + "`": "◆", + "a": "▒", + "b": "␉", + "c": "␌", + "d": "␍", + "e": "␊", + "f": "°", + "g": "±", + "h": "␤", + "i": "␋", + "j": "┘", + "k": "┐", + "l": "┌", + "m": "└", + "n": "┼", + "o": "⎺", + "p": "⎻", + "q": "─", + "r": "⎼", + "s": "⎽", + "t": "├", + "u": "┤", + "v": "┴", + "w": "┬", + "x": "│", + "y": "≤", + "z": "≥", + "{": "π", + "|": "≠", + "}": "£", + "~": "·", + }, +) + +_UK_CHARSET = str.maketrans({"#": "£"}) + +_SAFE_URI_PREFIXES = ("https://", "http://", "mailto:") + + +class StopOn(enum.IntFlag): + """Boundary conditions for :meth:`Terminal.feed_until`.""" + + NONE = 0 + EOF = 1 + GROUND = 2 + SYNC_START = 4 + SYNC_END = 8 + PROMPT_MARK = 16 + + +@dataclass(frozen=True, slots=True) +class StepResult: + """Return value from :meth:`Terminal.feed_until`. + + Attributes + ---------- + offset : int + Next unconsumed byte index inside the input buffer. + stopped_on : StopOn + Flag(s) that triggered termination of the step. + """ + + offset: int + stopped_on: StopOn + + +class OutputFormat(enum.StrEnum): + """Export target formats supported by :class:`Formatter`.""" + + PLAIN = "plain" + VT = "vt" + HTML = "html" + + +class FlightRecorder: + """Bounded raw-byte ring buffer capturing recent VT traffic for diagnostics.""" + + __slots__ = ("_buf", "_max_bytes", "_total_bytes") + + def __init__(self, *, max_bytes: int = 4_096) -> None: + self._max_bytes = max(64, max_bytes) + self._buf = bytearray() + self._total_bytes = 0 + + @property + def total_bytes(self) -> int: + """Return total byte count observed since initialization or ``clear()``.""" + return self._total_bytes + + def record(self, data: collections.abc.Buffer) -> None: + """Append *data*, retaining at most ``max_bytes`` trailing bytes.""" + mv = memoryview(data).cast("B") + n = len(mv) + if n == 0: + return + self._total_bytes += n + if n >= self._max_bytes: + self._buf[:] = mv[n - self._max_bytes :] + return + overflow = len(self._buf) + n - self._max_bytes + if overflow > 0: + del self._buf[:overflow] + self._buf.extend(mv) + + def tail(self, max_bytes: int = 256) -> bytes: + """Return up to *max_bytes* of the most recently recorded input bytes.""" + if max_bytes <= 0 or not self._buf: + return b"" + return bytes(self._buf[-max_bytes:]) + + def clear(self) -> None: + """Clear recorded bytes and reset ``total_bytes``.""" + self._buf.clear() + self._total_bytes = 0 + + +@dataclass(frozen=True, slots=True) +class _SavedCursor: + """Internal ``DECSC`` per-screen saved cursor and charset state. + + Attributes + ---------- + row : int + Saved zero-based row. + col : int + Saved zero-based column. + pending_wrap : bool + Saved pending-wrap state. + style : Style + Saved SGR pen. + decom : bool + Saved ``DECOM`` origin-mode flag. + g_sets : tuple[str, str, str, str] + Saved ``G0``..``G3`` character-set designations. + gl : int + Saved active locking-shift slot index (``0..3``). + protected : bool + Saved ``DECSCA`` character-protection pen attribute. + """ + + row: int = 0 + col: int = 0 + pending_wrap: bool = False + style: Style = DEFAULT_STYLE + decom: bool = False + g_sets: tuple[str, str, str, str] = ("B", "B", "B", "B") + gl: int = 0 + protected: bool = False + + +class Snapshot: + """Immutable point-in-time capture of terminal screen, history, and metadata.""" + + __slots__ = ( + "_cols", + "_history", + "_rows", + "active_is_alt", + "cursor", + "cwd", + "generation", + "modes", + "program_status", + "program_statuses", + "prompt_zones", + "title", + ) + + def __init__( + self, + *, + rows: tuple[_Row, ...], + history: tuple[FrozenRow, ...], + cols: int, + cursor: Cursor, + title: str, + cwd: str, + modes: frozenset[Mode], + active_is_alt: bool, + prompt_zones: tuple[PromptZone, ...], + program_status: ProgramStatus | None, + program_statuses: dict[str, ProgramStatus], + generation: int, + ) -> None: + self._rows = rows + self._history = history + self._cols = cols + self.cursor = cursor + self.title = title + self.cwd = cwd + self.modes = modes + self.active_is_alt = active_is_alt + self.prompt_zones = prompt_zones + self.program_status = program_status + self.program_statuses = program_statuses + self.generation = generation + + @property + def rows(self) -> int: + """Return snapshot height in rows.""" + return len(self._rows) + + @property + def cols(self) -> int: + """Return snapshot width in columns.""" + return self._cols + + @property + def history(self) -> tuple[RowView, ...]: + """Return immutable :class:`RowView` sequence over scrollback rows.""" + return tuple(RowView(fr) for fr in self._history) + + @property + def lines(self) -> tuple[str, ...]: + """Return right-trimmed text for every visible row in the snapshot.""" + return tuple(r.rstrip_text() for r in self._rows) + + @property + def text(self) -> str: + """Return visible snapshot text with trailing blank rows omitted.""" + return format_rows_text(self._rows) + + @t.overload + def __getitem__(self, key: int) -> RowView: ... + + @t.overload + def __getitem__(self, key: tuple[int, int]) -> Cell: ... + + @t.overload + def __getitem__( + self, + key: slice | tuple[slice | int, slice | int], + ) -> RegionView: ... + + def __getitem__( + self, + key: int | slice | tuple[slice | int, slice | int], + ) -> RowView | Cell | RegionView: + """Index a row, single ``(row, col)`` cell, or 2D region view.""" + return slice_grid(self._rows, self._cols, key) + + def format( + self, + output_format: OutputFormat = OutputFormat.PLAIN, + *, + policy: Policy = DEFAULT_POLICY, + ) -> str: + """Render this snapshot using :class:`Formatter`.""" + return Formatter(output_format, policy=policy).format_snapshot(self) + + def to_dict(self) -> dict[str, t.Any]: + """Serialize snapshot state into a deterministic JSON-compatible dict.""" + return { + "rows": self.rows, + "cols": self.cols, + "lines": list(self.lines), + "history_lines": [fr.text for fr in self._history], + "cursor": { + "row": self.cursor.row, + "col": self.cursor.col, + "visible": self.cursor.visible, + "shape": self.cursor.shape.value, + "blinking": self.cursor.blinking, + "pending_wrap": self.cursor.pending_wrap, + }, + "title": self.title, + "cwd": self.cwd, + "active_is_alt": self.active_is_alt, + "modes": sorted(m.name for m in self.modes if m.name is not None), + "program_status": ( + { + "state": self.program_status.state.value, + "id": self.program_status.id, + "progress": self.program_status.progress, + "effective_app": self.program_status.effective_app, + "title": self.program_status.title, + "msg": self.program_status.msg, + } + if self.program_status is not None + else None + ), + } + + +def _color_sgr_tokens(color: Color, *, fg: bool) -> list[str]: + if color is None: + return ["39" if fg else "49"] + if isinstance(color, AnsiColor): + idx = int(color) + if idx < 8: + return [str((30 if fg else 40) + idx)] + return [str((90 if fg else 100) + (idx - 8))] + prefix = "38" if fg else "48" + if isinstance(color, IndexedColor): + return [f"{prefix};5;{color.index}"] + return [f"{prefix};2;{color.r};{color.g};{color.b}"] + + +def _style_to_sgr(style: Style) -> str: + if style == DEFAULT_STYLE: + return "\x1b[0m" + parts: list[str] = ["0"] + if style.bold: + parts.append("1") + if style.dim: + parts.append("2") + if style.italic: + parts.append("3") + if style.underline == UnderlineStyle.SINGLE: + parts.append("4") + elif style.underline != UnderlineStyle.NONE: + parts.append(f"4:{int(style.underline)}") + if style.blink: + parts.append("5") + if style.reverse: + parts.append("7") + if style.hidden: + parts.append("8") + if style.strikethrough: + parts.append("9") + if style.overline: + parts.append("53") + if style.fg is not None: + parts.extend(_color_sgr_tokens(style.fg, fg=True)) + if style.bg is not None: + parts.extend(_color_sgr_tokens(style.bg, fg=False)) + if style.underline_color is not None: + ul = style.underline_color + if isinstance(ul, AnsiColor): + parts.append(f"58:5:{int(ul)}") + elif isinstance(ul, IndexedColor): + parts.append(f"58:5:{ul.index}") + else: + parts.append(f"58:2::{ul.r}:{ul.g}:{ul.b}") + return f"\x1b[{';'.join(parts)}m" + + +def _is_safe_uri(uri: str) -> bool: + low = uri.lstrip().lower() + return low.startswith(_SAFE_URI_PREFIXES) + + +class Formatter: + """Serialize a :class:`Snapshot` or :class:`Terminal` to text, VT, or HTML.""" + + __slots__ = ("output_format", "policy") + + def __init__( + self, + output_format: OutputFormat = OutputFormat.PLAIN, + *, + policy: Policy = DEFAULT_POLICY, + ) -> None: + self.output_format = output_format + self.policy = policy + + def format_snapshot(self, snapshot: Snapshot) -> str: + """Render *snapshot* in :attr:`output_format`.""" + if self.output_format == OutputFormat.PLAIN: + return snapshot.text + if self.output_format == OutputFormat.VT: + return self._render_vt(snapshot) + return self._render_html(snapshot) + + def _render_vt(self, snapshot: Snapshot) -> str: + out: list[str] = [] + export_modes = snapshot.modes - TRANSIENT_SNAPSHOT_MODES + if not snapshot.active_is_alt: + export_modes = export_modes - ALT_SCREEN_MODES + for mode in sorted(export_modes, key=int): + raw = int(mode) + if raw & DEC_PRIVATE_MASK: + code = raw & ~DEC_PRIVATE_MASK + if mode not in ( + Mode.DECAWM, + Mode.DECTCEM, + Mode.GRAPHEME_CLUSTERING, + ): + out.append(f"\x1b[?{code}h") + else: + out.append(f"\x1b[{raw}h") + if Mode.DECTCEM not in export_modes: + out.append("\x1b[?25l") + cur_style = DEFAULT_STYLE + cur_link: Hyperlink | None = None + for r_idx, row in enumerate(snapshot._rows): + if r_idx > 0: + out.append("\r\n" if not snapshot._rows[r_idx - 1].wrapped else "") + for c in range(row.used): + word = row.attr_at(c) + rb = raw_width_bits(word) + if rb in (int(WidthRole.SPACER_TAIL), int(WidthRole.SPACER_HEAD)): + continue + ext = row.ext_at(c) + style = unpack_style(word, ext) + link = ext.hyperlink if ext is not None else None + if link != cur_link: + if link is None: + out.append("\x1b]8;;\x1b\\") + else: + param = f"id={link.id}" if link.id else "" + out.append(f"\x1b]8;{param};{link.uri}\x1b\\") + cur_link = link + if style != cur_style: + out.append(_style_to_sgr(style)) + cur_style = style + out.append(row.chars[c]) + if cur_link is not None: + out.append("\x1b]8;;\x1b\\") + if cur_style != DEFAULT_STYLE: + out.append("\x1b[0m") + out.append(f"\x1b[{snapshot.cursor.row + 1};{snapshot.cursor.col + 1}H") + return "".join(out) + + def _render_html(self, snapshot: Snapshot) -> str: + lines: list[str] = ['
']
+        allow_unsafe = self.policy.allow_unsafe_uris
+        for row in snapshot._rows:
+            view = RowView(row)
+            chunks: list[str] = []
+            for run in view.runs:
+                escaped = html.escape(run.text)
+                style = run.style
+                css: list[str] = []
+                if style.bold:
+                    css.append("font-weight:bold")
+                if style.italic:
+                    css.append("font-style:italic")
+                if isinstance(style.fg, RgbColor):
+                    css.append(
+                        f"color:rgb({style.fg.r},{style.fg.g},{style.fg.b})",
+                    )
+                if isinstance(style.bg, RgbColor):
+                    css.append(
+                        f"background-color:rgb({style.bg.r},{style.bg.g},{style.bg.b})",
+                    )
+                span = (
+                    f'{escaped}'
+                    if css
+                    else escaped
+                )
+                if run.hyperlink is not None and (
+                    allow_unsafe or _is_safe_uri(run.hyperlink.uri)
+                ):
+                    href = html.escape(run.hyperlink.uri, quote=True)
+                    span = f'{span}'
+                chunks.append(span)
+            lines.append("".join(chunks))
+        lines.append("
") + return "\n".join(lines) + + +class _TerminalSink: + """Private ``ActionSink`` forwarding parser actions into :class:`Terminal`.""" + + __slots__ = ("_term",) + + def __init__(self, term: Terminal) -> None: + self._term = term + + def on_print(self, text: str) -> None: + self._term._handle_print(text) + + def on_execute(self, byte: int) -> None: + self._term._handle_execute(byte) + + def on_esc(self, intermediates: bytes, final: int) -> None: + self._term._handle_esc(intermediates, final) + + def on_csi( + self, + prefix: int, + params: CsiParams, + intermediates: bytes, + final: int, + ) -> None: + self._term._handle_csi(prefix, params, intermediates, final) + + def on_osc(self, code: int, data: bytes, terminator: bytes) -> None: + self._term._handle_osc(code, data, terminator) + + def on_dcs( + self, + prefix: int, + params: CsiParams, + intermediates: bytes, + final: int, + data: bytes, + ) -> None: + self._term._handle_dcs(prefix, params, intermediates, final, data) + + def on_apc(self, data: bytes) -> None: + self._term._handle_apc(data) + + +def _hex_encode(text: str) -> str: + return text.encode("utf-8").hex() + + +_TERMINFO_CAPS: dict[str, str] = { + "TN": "xterm-256color", + "Co": "256", + "colors": "256", + "RGB": "8/8/8", + "Tc": "", + "Smulx": "\x1b[4:%p1%dm", + "Setulc": "\x1b[58:2::%p1%{65536}%/%d:%p1%{256}%/%{255}%&%d:%p1%{255}%&%dm", + "Sync": "\x1b[?2026%?%p1%{1}%-%tl%eh%;", +} + + +class Terminal: + """Sans-I/O virtual terminal emulator over a streaming VT500 parser.""" + + def __init__( + self, + *, + rows: int = 24, + cols: int = 80, + scrollback: int = 2_000, + profile: Profile = DEFAULT_PROFILE, + policy: Policy = DEFAULT_POLICY, + limits: Limits = DEFAULT_LIMITS, + on_event: collections.abc.Callable[[Event], None] | None = None, + on_pty_write: collections.abc.Callable[[bytes], None] | None = None, + record_events: bool = False, + recorder: FlightRecorder | None = None, + c1_controls: bool = False, + ) -> None: + self._profile = profile + self._policy = policy + self._limits = limits + self._on_event = on_event + self._on_pty_write = on_pty_write + self._record_events = record_events + self._recorder = recorder + self._events: collections.deque[Event] = collections.deque( + maxlen=limits.max_events, + ) + self._screens = ScreenSet( + rows=rows, + cols=cols, + scrollback=scrollback, + keyboard_stack_depth=limits.max_keyboard_stack, + ) + self._modes = ModeState() + self._parser = Parser(c1_controls=c1_controls, limits=limits) + self._sink = _TerminalSink(self) + self._sgr_memo: dict[tuple[Style, CsiParams], Style] = {} + self._style: Style = DEFAULT_STYLE + self._protected: bool = False + self._pen_word: int = 0 + self._hyperlink: Hyperlink | None = None + self._cell_ext: _CellExt | None = None + self._g_sets: list[str] = ["B", "B", "B", "B"] + self._gl: int = 0 + self._single_shift: int | None = None + self._saved_primary = _SavedCursor() + self._saved_alt = _SavedCursor() + self._last_printed: str = "" + self._last_printed_pos: tuple[int, int] | None = None + self._cluster_state: ClusterState = ClusterState.NONE + self._cluster_len: int = 0 + self._title: str = "" + self._title_stack: list[str] = [] + self._cwd: str = "" + self._prompt_zones: collections.deque[PromptZone] = collections.deque( + maxlen=limits.max_prompt_zones, + ) + self._status_store = ProgramStatusStore( + max_records=limits.max_status_records, + ) + self._replies = bytearray() + self._generation: int = 0 + self._sync_generation: int = 0 + self._sync_hold_pending: bool = False + self._cached_snapshot: Snapshot | None = None + self._held_snapshot: Snapshot | None = None + self._step_event: StopOn = StopOn.NONE + self._passthrough_depth: int = 0 + + @classmethod + def from_size( + cls, + size: os.terminal_size, + *, + scrollback: int = 2_000, + profile: Profile = DEFAULT_PROFILE, + policy: Policy = DEFAULT_POLICY, + limits: Limits = DEFAULT_LIMITS, + ) -> Terminal: + """Construct a :class:`Terminal` from :class:`os.terminal_size`.""" + return cls( + rows=size.lines, + cols=size.columns, + scrollback=scrollback, + profile=profile, + policy=policy, + limits=limits, + ) + + @property + def rows(self) -> int: + """Return active screen height in rows.""" + return self._screens.active.rows + + @property + def cols(self) -> int: + """Return active screen width in columns.""" + return self._screens.active.cols + + @property + def profile(self) -> Profile: + """Return active :class:`~libvt.config.Profile`.""" + return self._profile + + @property + def policy(self) -> Policy: + """Return active :class:`~libvt.config.Policy`.""" + return self._policy + + @property + def limits(self) -> Limits: + """Return active :class:`~libvt.config.Limits`.""" + return self._limits + + @property + def parser_state(self) -> ParserState: + """Return current :class:`~libvt.parser.ParserState`.""" + return self._parser.state + + @property + def recorder(self) -> FlightRecorder | None: + """Return attached :class:`FlightRecorder`, if any.""" + return self._recorder + + @property + def screen(self) -> Screen: + """Return the currently active :class:`~libvt.screen.Screen`.""" + return self._screens.active + + @property + def screens(self) -> ScreenSet: + """Return the dual primary/alternate :class:`~libvt.screen.ScreenSet`.""" + return self._screens + + @property + def history(self) -> tuple[RowView, ...]: + """Return sealed scrollback :class:`~libvt.screen.RowView` lines.""" + return self._screens.primary.history + + @property + def cursor(self) -> Cursor: + """Return current zero-based :class:`~libvt.screen.Cursor`.""" + return self._screens.active.cursor + + @property + def title(self) -> str: + """Return window title set by ``OSC 0`` / ``OSC 2``.""" + return self._title + + @property + def cwd(self) -> str: + """Return working directory path reported by ``OSC 7`` / ``OSC 9;9``.""" + return self._cwd + + @property + def modes(self) -> ModeState: + """Return current :class:`~libvt.modes.ModeState`.""" + return self._modes + + @property + def kitty_keyboard_flags(self) -> KittyKeyboardFlags: + """Return active screen's :class:`~libvt.input.KittyKeyboardFlags`.""" + return self._screens.active.keyboard_stack.flags + + @property + def synchronized(self) -> bool: + """Return ``True`` while DEC mode ``?2026`` synchronized output is active.""" + return self._modes.is_set(Mode.SYNCHRONIZED_OUTPUT) + + @property + def sync_generation(self) -> int: + """Return monotonic ``?2026`` synchronized-update batch counter.""" + return self._sync_generation + + @property + def prompt_zones(self) -> tuple[PromptZone, ...]: + """Return recorded ``OSC 133`` prompt zones adjusted to current viewport.""" + scrolled = self._screens.primary.scrolled_total + return tuple( + PromptZone( + kind=z.kind, + row=z.abs_row - scrolled, + col=z.col, + exit_code=z.exit_code, + abs_row=z.abs_row, + ) + for z in self._prompt_zones + ) + + @property + def program_status(self) -> ProgramStatus | None: + """Return highest-urgency active ``OSC 7501`` / ``OSC 9;4`` status.""" + return self._status_store.most_urgent + + @property + def program_statuses(self) -> dict[str, ProgramStatus]: + """Return all active ``OSC 7501`` task records keyed by ``id``.""" + return self._status_store.records + + @property + def lines(self) -> tuple[str, ...]: + """Return right-trimmed visible lines of the active screen.""" + return self._screens.active.lines + + @property + def text(self) -> str: + """Return visible active-screen text with trailing blank rows omitted.""" + return self._screens.active.text + + @property + def committed(self) -> Snapshot: + """Return tear-free committed :class:`Snapshot` respecting ``?2026`` hold.""" + if self._sync_hold_pending: + self._ensure_sync_snapshot() + if self._held_snapshot is not None: + return self._held_snapshot + return self.snapshot() + + def _ensure_sync_snapshot(self) -> None: + if self._sync_hold_pending and self._held_snapshot is None: + self._held_snapshot = self.snapshot() + self._sync_hold_pending = False + + def snapshot(self) -> Snapshot: + """Capture an immutable :class:`Snapshot` of live terminal state.""" + if ( + self._cached_snapshot is not None + and self._cached_snapshot.generation == self._generation + ): + return self._cached_snapshot + scr = self._screens.active + snap = Snapshot( + rows=tuple(r.clone() for r in scr._rows), + history=tuple(self._screens.primary._history), + cols=scr.cols, + cursor=scr.cursor, + title=self._title, + cwd=self._cwd, + modes=self._modes.enabled_modes(), + active_is_alt=self._screens.active_is_alt, + prompt_zones=self.prompt_zones, + program_status=self._status_store.most_urgent, + program_statuses=self._status_store.records, + generation=self._generation, + ) + self._cached_snapshot = snap + return snap + + @t.overload + def __getitem__(self, key: int) -> RowView: ... + + @t.overload + def __getitem__(self, key: tuple[int, int]) -> Cell: ... + + @t.overload + def __getitem__( + self, + key: slice | tuple[slice | int, slice | int], + ) -> RegionView: ... + + def __getitem__( + self, + key: int | slice | tuple[slice | int, slice | int], + ) -> RowView | Cell | RegionView: + """Index a row, single ``(row, col)`` cell, or 2D region view.""" + return self._screens.active[key] + + def _emit_event(self, event: Event) -> None: + if self._record_events: + self._events.append(event) + if self._on_event is not None: + self._on_event(event) + + def _unhandled(self, kind: str, summary: str) -> None: + if self._policy.strict: + msg = f"unhandled {kind} sequence: {summary}" + raise ProtocolError(msg) + if self._record_events or self._on_event is not None: + self._emit_event(UnhandledSequence(kind=kind, summary=summary)) + + def drain_events(self) -> tuple[Event, ...]: + """Return and clear buffered :data:`~libvt.events.Event` records.""" + if not self._events: + return () + out = tuple(self._events) + self._events.clear() + return out + + def drain_replies(self) -> bytes: + """Return and clear buffered sans-I/O query reply bytes.""" + if not self._replies: + return b"" + out = bytes(self._replies) + self._replies.clear() + return out + + def encode(self, event: InputEvent, /) -> bytes: + """Encode *event* into outbound PTY bytes using active terminal modes.""" + return encode_input( + event, + modes=self._modes, + kitty_flags=self.kitty_keyboard_flags, + ) + + def expire_synchronized_output( + self, + sync_generation: int | None = None, + ) -> bool: + """Release a stalled ``?2026`` hold when *sync_generation* matches. + + Returns ``True`` if an active ``?2026`` batch was expired, or ``False`` + when ``?2026`` was already inactive or belonged to a newer batch. + """ + if not self.synchronized: + return False + if sync_generation is not None and sync_generation != self._sync_generation: + return False + self._modes.set_mode(Mode.SYNCHRONIZED_OUTPUT, enabled=False) + self._sync_hold_pending = False + self._held_snapshot = None + self._generation += 1 + self._emit_event( + RenderHoldChanged( + active=False, + sync_generation=self._sync_generation, + expired=True, + ), + ) + return True + + def notify_process_exit(self) -> None: + """Prune transient ``working`` / ``blocked`` ``OSC 7501`` status records.""" + if self._status_store.on_process_exit(): + self._generation += 1 + self._emit_event( + ProgramStatusChanged(status=self._status_store.most_urgent), + ) + + def _emit_reply(self, payload: bytes) -> None: + if self._on_pty_write is not None: + self._on_pty_write(payload) + return + if len(self._replies) + len(payload) <= self._limits.max_reply_bytes: + self._replies.extend(payload) + + def _clear_cluster_anchor(self) -> None: + self._last_printed_pos = None + self._cluster_state = ClusterState.NONE + self._cluster_len = 0 + + def _sync_pen_cache(self) -> None: + self._pen_word = pack_pen_base(self._style) + self._cell_ext = make_cell_ext( + self._style, + self._hyperlink, + protected=self._protected, + ) + + def _bce_pair(self) -> tuple[int, _CellExt | None]: + if self._style.bg is None and self._hyperlink is None: + return 0, None + bce_style = Style(bg=self._style.bg) + return pack_pen_base(bce_style), make_cell_ext(bce_style, self._hyperlink) + + def _notify_erase(self, rect: Rect, cause: EraseCause) -> None: + if ( + (self._record_events or self._on_event is not None) + and rect.rows > 0 + and rect.cols > 0 + ): + self._emit_event( + ScreenErased( + rect=rect, + cause=cause, + active_is_alt=self._screens.active_is_alt, + ), + ) + + def resize(self, *, rows: int, cols: int, reflow: bool = True) -> None: + """Resize terminal screens to ``(rows, cols)``.""" + self._before_mutate() + self._clear_cluster_anchor() + self._screens.resize(rows=rows, cols=cols, reflow=reflow) + self._generation += 1 + if self._modes.is_set(Mode.IN_BAND_RESIZE): + self._emit_reply(f"\x1b[48;{rows};{cols};0;0t".encode("ascii")) + self._emit_event(InBandResize(rows=rows, cols=cols)) + + def reset(self, *, soft: bool = False) -> None: + """Reset terminal state (``DECSTR`` when *soft* is ``True``, else ``RIS``).""" + self._before_mutate() + self._style = DEFAULT_STYLE + self._protected = False + self._hyperlink = None + self._sync_pen_cache() + self._last_printed = "" + self._clear_cluster_anchor() + self._g_sets = ["B", "B", "B", "B"] + self._gl = 0 + self._single_shift = None + was_sync = self.synchronized + was_alt = self._screens.active_is_alt + self._modes = ModeState() + self._sync_hold_pending = False + self._held_snapshot = None + if was_sync: + self._emit_event( + RenderHoldChanged( + active=False, + sync_generation=self._sync_generation, + ), + ) + if soft: + if was_alt: + self._modes.sync_alt_screen(active_is_alt=True) + scr = self._screens.active + scr.scroll_region = ScrollRegion( + top=0, + bottom=scr.rows - 1, + left=0, + right=scr.cols - 1, + ) + scr._cur_visible = True + scr._pending_wrap = False + scr.keyboard_stack.reset() + else: + self._parser.reset() + self._screens.active_is_alt = False + self._screens.primary.reset() + self._screens.alternate.reset() + self._saved_primary = _SavedCursor() + self._saved_alt = _SavedCursor() + self._title = "" + self._title_stack.clear() + self._cwd = "" + self._prompt_zones.clear() + self._status_store.reset() + self._notify_erase( + Rect(0, 0, self.rows, self.cols), + EraseCause.RESET, + ) + self._generation += 1 + + def _before_mutate(self) -> None: + if self._sync_hold_pending: + self._ensure_sync_snapshot() + + def feed_str(self, text: str, /) -> None: + """Encode *text* as UTF-8 and feed into the terminal.""" + self.feed(text.encode("utf-8")) + + def feed(self, data: collections.abc.Buffer, /) -> None: + """Consume all bytes in *data*, updating terminal state in place.""" + mv = memoryview(data) + if not mv: + return + if self._recorder is not None: + self._recorder.record(mv) + self._parser.feed_to(mv, self._sink) + self._generation += 1 + + def feed_until( + self, + data: collections.abc.Buffer, + *, + offset: int = 0, + stop: StopOn = StopOn.EOF | StopOn.SYNC_END, + ) -> StepResult: + """Feed bytes starting at *offset* until a *stop* boundary occurs.""" + mv = memoryview(data).cast("B") + n = len(mv) + if offset < 0 or offset > n: + msg = f"offset {offset} out of range for buffer of length {n}" + raise ValueError(msg) + idx = offset + while idx < n: + self._step_event = StopOn.NONE + state = self._parser.state + + # Bulk-advance GROUND printable ASCII when StopOn.GROUND is not requested. + if ( + state == ParserState.GROUND + and not self._parser.utf8_pending + and not (stop & StopOn.GROUND) + ): + end = idx + while end < n and 0x20 <= mv[end] < 0x7F: + end += 1 + if end > idx: + span = mv[idx:end] + if self._recorder is not None: + self._recorder.record(span) + self._parser.feed_to(span, self._sink) + idx = end + self._generation += 1 + continue + + # Bulk-advance interior payload bytes inside OSC / DCS / APC strings! + if state in ( + ParserState.OSC_STRING, + ParserState.DCS_PASSTHROUGH, + ParserState.SOS_PM_APC_STRING, + ): + end = idx + while end < n and mv[end] not in (0x07, 0x18, 0x1A, 0x1B, 0x9C): + end += 1 + if end > idx: + span = mv[idx:end] + if self._recorder is not None: + self._recorder.record(span) + self._parser.feed_to(span, self._sink) + idx = end + self._generation += 1 + continue + + one = mv[idx : idx + 1] + if self._recorder is not None: + self._recorder.record(one) + self._parser.feed_to(one, self._sink) + idx += 1 + self._generation += 1 + matched = self._step_event & stop + if ( + (stop & StopOn.GROUND) + and self._parser.state == ParserState.GROUND + and not self._parser.utf8_pending + ): + matched |= StopOn.GROUND + if matched: + return StepResult(offset=idx, stopped_on=matched) + return StepResult( + offset=n, + stopped_on=StopOn.EOF, + ) + + # --- Internal sink handlers --- + + def _effective_margins(self, scr: Screen) -> tuple[int, int, int, int]: + sr = scr.scroll_region + if self._modes.is_set(Mode.DECLRMM): + return sr.top, sr.bottom, sr.left, sr.right + return sr.top, sr.bottom, 0, scr.cols - 1 + + def _set_cursor( + self, + scr: Screen, + row: int, + col: int, + *, + pending_wrap: bool = False, + clear_cluster: bool = True, + ) -> None: + scr._cur_row = max(0, min(scr.rows - 1, row)) + scr._cur_col = max(0, min(scr.cols - 1, col)) + scr._pending_wrap = pending_wrap + if clear_cluster: + self._clear_cluster_anchor() + + def _linefeed(self, scr: Screen, *, carriage_return: bool = False) -> None: + self._before_mutate() + top, bottom, left, right = self._effective_margins(scr) + col = left if carriage_return else scr._cur_col + if scr._cur_row == bottom and left <= scr._cur_col <= right: + bce_word, bce_ext = self._bce_pair() + scr.scroll_up( + 1, + top=top, + bottom=bottom, + left=left, + right=right, + save_history=not self._screens.active_is_alt, + bce_word=bce_word, + bce_ext=bce_ext, + ) + self._notify_erase( + Rect(bottom, left, 1, right - left + 1), + EraseCause.SCROLL, + ) + self._set_cursor(scr, bottom, col, pending_wrap=False) + elif scr._cur_row < scr.rows - 1: + self._set_cursor(scr, scr._cur_row + 1, col, pending_wrap=False) + else: + self._set_cursor(scr, scr._cur_row, col, pending_wrap=False) + + def _map_charset(self, text: str) -> str: + if self._single_shift is not None: + ch0_cs = self._g_sets[self._single_shift] + self._single_shift = None + first = ( + text[0].translate(_DEC_SPECIAL_GRAPHICS) + if ch0_cs == "0" + else (text[0].translate(_UK_CHARSET) if ch0_cs == "A" else text[0]) + ) + if len(text) == 1: + return first + return first + self._map_charset(text[1:]) + + active_cs = self._g_sets[self._gl] + if active_cs == "B": + return text + if active_cs == "0": + return text.translate(_DEC_SPECIAL_GRAPHICS) + if active_cs == "A": + return text.translate(_UK_CHARSET) + return text + + def _handle_print(self, text: str) -> None: + self._before_mutate() + if self._single_shift is not None or self._g_sets[self._gl] != "B": + text = self._map_charset(text) + + scr = self._screens.active + autowrap = self._modes.is_set(Mode.DECAWM) + insert_mode = self._modes.is_set(Mode.IRM) + _, _, left, right = self._effective_margins(scr) + + if text.isascii() and not insert_mode: + pos = 0 + total = len(text) + while pos < total: + c_col = scr._cur_col + max_col = right if c_col <= right else scr.cols - 1 + min_col = left if c_col >= left else 0 + if scr._pending_wrap and autowrap: + scr._rows[scr._cur_row].wrapped = True + self._linefeed(scr) + self._set_cursor(scr, scr._cur_row, min_col, pending_wrap=False) + c_col = scr._cur_col + avail = max_col - c_col + 1 + seg = text[pos : pos + avail] + seg_len = len(seg) + scr._rows[scr._cur_row].write_ascii_slice( + c_col, + seg, + self._pen_word, + self._cell_ext, + ) + pos += seg_len + end_col = c_col + seg_len - 1 + if c_col + seg_len > max_col: + self._set_cursor( + scr, + scr._cur_row, + max_col, + pending_wrap=autowrap, + clear_cluster=False, + ) + else: + self._set_cursor( + scr, + scr._cur_row, + c_col + seg_len, + pending_wrap=False, + clear_cluster=False, + ) + self._last_printed = seg[-1] + self._last_printed_pos = (scr._cur_row, end_col) + self._cluster_state = ClusterState.BASE + self._cluster_len = 1 + return + + mode_2027 = self._modes.is_set(Mode.GRAPHEME_CLUSTERING) + max_cluster = self._limits.max_grapheme_codepoints + + for ch in text: + cp = ord(ch) + if self._last_printed_pos is not None: + extends, next_state, w_override = step_cluster( + self._cluster_state, + cp, + mode_2027=mode_2027, + ) + if extends: + self._cluster_state = next_state + if self._cluster_len >= max_cluster: + continue + pr, pc = self._last_printed_pos + if 0 <= pr < scr.rows and 0 <= pc < scr.cols: + row_obj = scr._rows[pr] + cur_role = raw_width_bits(row_obj.attr_at(pc)) + # Right-margin VS16 / Regional Indicator widening wrap! + eff_right = right if pc <= right else scr.cols - 1 + eff_left = left if pc >= left else 0 + if ( + w_override == 2 + and cur_role == int(WidthRole.NARROW) + and pc == eff_right + and autowrap + and eff_right - eff_left >= 1 + ): + combined = row_obj.chars[pc] + ch + bce_w, bce_e = self._bce_pair() + row_obj.write_spacer_head(pc, bce_w, bce_e) + row_obj.wrapped = True + self._linefeed(scr) + nr = scr._cur_row + scr._rows[nr].write_wide( + eff_left, + combined, + self._pen_word, + self._cell_ext, + ) + self._cluster_len += 1 + self._last_printed = combined + self._last_printed_pos = (nr, eff_left) + if eff_left + 1 >= eff_right: + self._set_cursor( + scr, + nr, + eff_right, + pending_wrap=autowrap, + clear_cluster=False, + ) + else: + self._set_cursor( + scr, + nr, + eff_left + 2, + pending_wrap=False, + clear_cluster=False, + ) + continue + + row_obj.append_grapheme( + pc, + ch, + width_override=w_override, + pen_word=self._pen_word, + cell_ext=self._cell_ext, + ) + self._cluster_len += 1 + self._last_printed = row_obj.chars[pc] + if ( + w_override == 2 + and cur_role == int(WidthRole.NARROW) + and scr._cur_row == pr + and scr._cur_col == pc + 1 + ): + if pc + 1 >= eff_right: + self._set_cursor( + scr, + pr, + eff_right, + pending_wrap=autowrap, + clear_cluster=False, + ) + else: + self._set_cursor( + scr, + pr, + pc + 2, + pending_wrap=False, + clear_cluster=False, + ) + elif ( + w_override == 1 + and cur_role == int(WidthRole.WIDE) + and scr._cur_row == pr + ): + self._set_cursor( + scr, + pr, + min(eff_right, pc + 1), + pending_wrap=False, + clear_cluster=False, + ) + continue + else: + _, next_state, _ = step_cluster( + ClusterState.NONE, + cp, + mode_2027=mode_2027, + ) + + width = char_width(ch) + if width == 0: + continue + + c_row = scr._cur_row + c_col = scr._cur_col + max_col = right if c_col <= right else scr.cols - 1 + min_col = left if c_col >= left else 0 + + if scr._pending_wrap and autowrap: + scr._rows[c_row].wrapped = True + self._linefeed(scr) + self._set_cursor(scr, scr._cur_row, min_col, pending_wrap=False) + c_row = scr._cur_row + c_col = scr._cur_col + + if width == 2 and c_col == max_col: + if autowrap and max_col - min_col >= 1: + bce_w, bce_e = self._bce_pair() + scr._rows[c_row].write_spacer_head(c_col, bce_w, bce_e) + scr._rows[c_row].wrapped = True + self._linefeed(scr) + self._set_cursor(scr, scr._cur_row, min_col, pending_wrap=False) + c_row = scr._cur_row + c_col = scr._cur_col + else: + ch = "\ufffd" + width = 1 + + row_obj = scr._rows[c_row] + if insert_mode: + bce_w, bce_e = self._bce_pair() + row_obj.insert_blanks( + c_col, + width, + left=min_col, + right=max_col, + bce_word=bce_w, + bce_ext=bce_e, + ) + + if width == 2 and c_col + 1 <= max_col: + row_obj.write_wide( + c_col, + ch, + self._pen_word, + self._cell_ext, + ) + placed_col = c_col + if c_col + 1 >= max_col: + self._set_cursor( + scr, + c_row, + max_col, + pending_wrap=autowrap, + clear_cluster=False, + ) + else: + self._set_cursor( + scr, + c_row, + c_col + 2, + pending_wrap=False, + clear_cluster=False, + ) + else: + row_obj.write_narrow( + c_col, + ch, + self._pen_word, + self._cell_ext, + ) + placed_col = c_col + if c_col >= max_col: + self._set_cursor( + scr, + c_row, + max_col, + pending_wrap=autowrap, + clear_cluster=False, + ) + else: + self._set_cursor( + scr, + c_row, + c_col + 1, + pending_wrap=False, + clear_cluster=False, + ) + + self._last_printed = ch + self._last_printed_pos = (c_row, placed_col) + self._cluster_state = next_state + self._cluster_len = 1 + + def _cursor_left(self, scr: Screen, count: int, *, is_backspace: bool) -> None: + _, top, left, right = ( + scr.scroll_region.bottom, + scr.scroll_region.top, + *self._effective_margins(scr)[2:], + ) + rev_wrap = self._modes.is_set(Mode.DECAWM) and ( + self._modes.is_set(Mode.REVERSE_WRAP) + or self._profile.pending_wrap_phantom_col + ) + n = max(1, count) + if scr._pending_wrap and rev_wrap: + scr._pending_wrap = False + self._clear_cluster_anchor() + n -= 1 + if n == 0: + return + + floor = left if scr._cur_col >= left else 0 + if ( + is_backspace + and rev_wrap + and scr._cur_col == floor + and scr._cur_row > top + and scr._rows[scr._cur_row - 1].wrapped + ): + self._set_cursor(scr, scr._cur_row - 1, right, pending_wrap=False) + return + + self._set_cursor( + scr, + scr._cur_row, + max(floor, scr._cur_col - n), + pending_wrap=False, + ) + + def _handle_execute(self, byte: int) -> None: + scr = self._screens.active + _, _, left, right = self._effective_margins(scr) + if byte == 0x07: # BEL + self._emit_event(Bell()) + elif byte == 0x08: # BS + self._cursor_left(scr, 1, is_backspace=True) + elif byte == 0x09: # HT + ceil = right if scr._cur_col <= right else scr.cols - 1 + nxt = next( + ( + t_col + for t_col in scr._tabstops_sorted + if scr._cur_col < t_col <= ceil + ), + ceil, + ) + self._set_cursor(scr, scr._cur_row, nxt, pending_wrap=False) + elif byte in (0x0A, 0x0B, 0x0C): # LF, VT, FF + self._linefeed(scr, carriage_return=self._modes.is_set(Mode.LNM)) + elif byte == 0x0D: # CR + floor = left if scr._cur_col >= left else 0 + self._set_cursor(scr, scr._cur_row, floor, pending_wrap=False) + elif byte == 0x0E: # SO -> G1 + self._gl = 1 + elif byte == 0x0F: # SI -> G0 + self._gl = 0 + + def _save_cursor(self) -> None: + scr = self._screens.active + saved = _SavedCursor( + row=scr._cur_row, + col=scr._cur_col, + pending_wrap=scr._pending_wrap, + style=self._style, + decom=self._modes.is_set(Mode.DECOM), + g_sets=( + self._g_sets[0], + self._g_sets[1], + self._g_sets[2], + self._g_sets[3], + ), + gl=self._gl, + protected=self._protected, + ) + if self._screens.active_is_alt: + self._saved_alt = saved + else: + self._saved_primary = saved + + def _restore_cursor(self) -> None: + scr = self._screens.active + saved = self._saved_alt if self._screens.active_is_alt else self._saved_primary + self._style = saved.style + self._protected = saved.protected + self._sync_pen_cache() + self._g_sets = list(saved.g_sets) + self._gl = saved.gl + self._single_shift = None + self._modes.set_mode(Mode.DECOM, enabled=saved.decom) + self._set_cursor( + scr, + saved.row, + saved.col, + pending_wrap=saved.pending_wrap, + ) + + def _handle_esc(self, intermediates: bytes, final: int) -> None: + scr = self._screens.active + if not intermediates: + if final == 0x37: # ESC 7 DECSC + self._save_cursor() + elif final == 0x38: # ESC 8 DECRC + self._restore_cursor() + elif final == 0x44: # ESC D IND + self._linefeed(scr) + elif final == 0x45: # ESC E NEL + self._linefeed(scr, carriage_return=True) + elif final == 0x48: # ESC H HTS + scr.add_tabstop(scr._cur_col) + elif final == 0x4D: # ESC M RI + self._before_mutate() + top, bottom, left, right = self._effective_margins(scr) + if scr._cur_row == top and left <= scr._cur_col <= right: + bce_w, bce_e = self._bce_pair() + scr.scroll_down( + 1, + top=top, + bottom=bottom, + left=left, + right=right, + bce_word=bce_w, + bce_ext=bce_e, + ) + self._notify_erase( + Rect(top, left, 1, right - left + 1), + EraseCause.SCROLL, + ) + self._clear_cluster_anchor() + elif scr._cur_row > 0: + self._set_cursor( + scr, scr._cur_row - 1, scr._cur_col, pending_wrap=False + ) + elif final == 0x4E: # ESC N SS2 -> G2 + self._single_shift = 2 + elif final == 0x4F: # ESC O SS3 -> G3 + self._single_shift = 3 + elif final == 0x6E: # ESC n LS2 -> G2 + self._gl = 2 + elif final == 0x6F: # ESC o LS3 -> G3 + self._gl = 3 + elif final == 0x63: # ESC c RIS + self.reset(soft=False) + elif final not in (0x3D, 0x3E): # ignore DECKPAM / DECKPNM + self._unhandled("esc", f"ESC {chr(final)}") + elif intermediates in (b"(", b")", b"*", b"+"): + slot = {b"(": 0, b")": 1, b"*": 2, b"+": 3}[intermediates] + desig = chr(final) + if desig in ("0", "A", "B"): + self._g_sets[slot] = desig + else: + self._g_sets[slot] = "B" + elif intermediates == b"#" and final == 0x38: # DECALN + self._before_mutate() + for r in scr._rows: + r.write_ascii_slice(0, "E" * scr.cols, 0, None) + self._set_cursor(scr, 0, 0, pending_wrap=False) + else: + inter_s = intermediates.decode("ascii", errors="replace") + self._unhandled("esc", f"ESC {inter_s}{chr(final)}") + + def _apply_mode(self, code: int, *, private: bool, enabled: bool) -> None: + raw = (DEC_PRIVATE_MASK | code) if private else code + try: + mode = Mode(raw) + except ValueError: + return + was_set = self._modes.is_set(mode) + + if mode in ALT_SCREEN_MODES: + self._before_mutate() + self._clear_cluster_anchor() + if enabled and not self._screens.active_is_alt: + if mode == Mode.ALT_SCREEN: + self._save_cursor() + self._screens.alternate.reset() + self._screens.active_is_alt = True + self._modes.sync_alt_screen(active_is_alt=True, entered_via=mode) + elif not enabled and self._screens.active_is_alt: + if mode in (Mode.ALT_SCREEN_1047, Mode.ALT_SCREEN): + self._screens.alternate.reset() + self._screens.active_is_alt = False + self._modes.sync_alt_screen(active_is_alt=False) + if mode == Mode.ALT_SCREEN: + self._restore_cursor() + elif not enabled: + self._modes.sync_alt_screen(active_is_alt=False) + return + + self._modes.set_mode(mode, enabled=enabled) + scr = self._screens.active + + if mode == Mode.DECTCEM: + scr._cur_visible = enabled + elif mode == Mode.DECOM: + top, _, left, _ = self._effective_margins(scr) + self._set_cursor( + scr, + top if enabled else 0, + left if enabled else 0, + pending_wrap=False, + ) + elif mode == Mode.DECLRMM and not enabled: + sr = scr.scroll_region + scr.scroll_region = ScrollRegion( + top=sr.top, + bottom=sr.bottom, + left=0, + right=scr.cols - 1, + ) + elif mode == Mode.DECSC_1048: + if enabled: + self._save_cursor() + else: + self._restore_cursor() + elif mode == Mode.SYNCHRONIZED_OUTPUT and enabled != was_set: + if enabled: + self._sync_generation += 1 + self._sync_hold_pending = True + self._held_snapshot = None + self._step_event |= StopOn.SYNC_START + else: + self._sync_hold_pending = False + self._held_snapshot = None + self._step_event |= StopOn.SYNC_END + self._emit_event( + RenderHoldChanged( + active=enabled, + sync_generation=self._sync_generation, + ), + ) + + def _erase_display( + self, + scr: Screen, + mode: int, + *, + selective: bool, + ) -> None: + self._before_mutate() + bce_w, bce_e = self._bce_pair() + cause = EraseCause.DECSED if selective else EraseCause.ED + c_row = scr._cur_row + c_col = scr._cur_col + if mode == 0: + scr._rows[c_row].clear_range( + c_col, + scr.cols, + bce_w, + bce_e, + selective=selective, + ) + for r in range(c_row + 1, scr.rows): + scr._rows[r].clear_range(0, scr.cols, bce_w, bce_e, selective=selective) + self._notify_erase(Rect(c_row, c_col, 1, scr.cols - c_col), cause) + if c_row + 1 < scr.rows: + self._notify_erase( + Rect(c_row + 1, 0, scr.rows - c_row - 1, scr.cols), + cause, + ) + elif mode == 1: + for r in range(c_row): + scr._rows[r].clear_range(0, scr.cols, bce_w, bce_e, selective=selective) + scr._rows[c_row].clear_range( + 0, + c_col + 1, + bce_w, + bce_e, + selective=selective, + ) + if c_row > 0: + self._notify_erase(Rect(0, 0, c_row, scr.cols), cause) + self._notify_erase(Rect(c_row, 0, 1, c_col + 1), cause) + elif mode in (2, 3): + for r in range(scr.rows): + scr._rows[r].clear_range(0, scr.cols, bce_w, bce_e, selective=selective) + if mode == 3 and not selective: + scr.clear_history() + self._notify_erase(Rect(0, 0, scr.rows, scr.cols), cause) + elif mode == 22 and not selective: + if not self._screens.active_is_alt: + scr.push_scrollback_and_clear(bce_w, bce_e) + else: + for r in range(scr.rows): + scr._rows[r].clear_range(0, scr.cols, bce_w, bce_e) + self._notify_erase(Rect(0, 0, scr.rows, scr.cols), cause) + self._set_cursor(scr, c_row, c_col, pending_wrap=False) + + def _erase_line( + self, + scr: Screen, + mode: int, + *, + selective: bool, + ) -> None: + self._before_mutate() + bce_w, bce_e = self._bce_pair() + cause = EraseCause.DECSEL if selective else EraseCause.EL + c_row = scr._cur_row + c_col = scr._cur_col + if mode == 0: + scr._rows[c_row].clear_range( + c_col, + scr.cols, + bce_w, + bce_e, + selective=selective, + ) + self._notify_erase(Rect(c_row, c_col, 1, scr.cols - c_col), cause) + elif mode == 1: + scr._rows[c_row].clear_range( + 0, + c_col + 1, + bce_w, + bce_e, + selective=selective, + ) + self._notify_erase(Rect(c_row, 0, 1, c_col + 1), cause) + elif mode == 2: + scr._rows[c_row].clear_range( + 0, + scr.cols, + bce_w, + bce_e, + selective=selective, + ) + self._notify_erase(Rect(c_row, 0, 1, scr.cols), cause) + self._set_cursor(scr, c_row, c_col, pending_wrap=False) + + def _handle_csi( + self, + prefix: int, + params: CsiParams, + intermediates: bytes, + final: int, + ) -> None: + scr = self._screens.active + top, bottom, left, right = self._effective_margins(scr) + + # DA2: CSI > c + if prefix == ord(">") and not intermediates and final == ord("c"): + self._emit_reply(self._profile.da2) + return + + # XTVERSION: CSI > q + if prefix == ord(">") and not intermediates and final == ord("q"): + self._emit_reply(f"\x1bP>|{self._profile.xtversion}\x1b\\".encode("ascii")) + return + + # Kitty keyboard protocol: CSI > flags u | CSI < n u | CSI = flags;m u | CSI ? u + if ( + not intermediates + and final == ord("u") + and prefix + in ( + ord(">"), + ord("<"), + ord("="), + ord("?"), + ) + ): + kbd = scr.keyboard_stack + if prefix == ord("?"): + self._emit_reply(f"\x1b[?{int(kbd.flags)}u".encode("ascii")) + elif prefix == ord(">"): + kbd.push(params.raw_or_default(0, 0)) + elif prefix == ord("<"): + kbd.pop(params.get(0, 1)) + elif prefix == ord("="): + kbd.set_flags(params.raw_or_default(0, 0), params.get(1, 1)) + return + + # DECRQM: CSI ? Ps $ p or CSI Ps $ p + if intermediates == b"$" and final == ord("p"): + private = prefix == ord("?") + code = params.raw_or_default(0, 0) + pm = int( + self._modes.decrpm( + code, + private=private, + active_is_alt=self._screens.active_is_alt, + ), + ) + q = "?" if private else "" + self._emit_reply(f"\x1b[{q}{code};{pm}$y".encode("ascii")) + return + + # DECSTR: CSI ! p + if prefix == 0 and intermediates == b"!" and final == ord("p"): + self.reset(soft=True) + return + + # DECSCUSR: CSI Ps SP q + if prefix == 0 and intermediates == b" " and final == ord("q"): + ps = params.raw_or_default(0, 0) + shape = CursorShape.BLOCK + blinking = True + if ps == 2: + shape, blinking = CursorShape.BLOCK, False + elif ps == 3: + shape, blinking = CursorShape.UNDERLINE, True + elif ps == 4: + shape, blinking = CursorShape.UNDERLINE, False + elif ps == 5: + shape, blinking = CursorShape.BAR, True + elif ps == 6: + shape, blinking = CursorShape.BAR, False + scr._cur_shape = shape + scr._cur_blinking = blinking + return + + # DECSCA: CSI Ps " q (character protection attribute) + if prefix == 0 and intermediates == b'"' and final == ord("q"): + ps = params.raw_or_default(0, 0) + self._protected = ps == 1 + self._sync_pen_cache() + return + + if intermediates: + inter_s = intermediates.decode("ascii", errors="replace") + pfx_s = chr(prefix) if prefix else "" + self._unhandled("csi", f"CSI {pfx_s}{inter_s}{chr(final)}") + return + + if prefix == ord("?"): + if final in (ord("h"), ord("l")): + enable = final == ord("h") + for val in params.values: + self._apply_mode(val, private=True, enabled=enable) + elif final == ord("J"): # DECSED + self._erase_display(scr, params.raw_or_default(0, 0), selective=True) + elif final == ord("K"): # DECSEL + self._erase_line(scr, params.raw_or_default(0, 0), selective=True) + elif final == ord("n"): # Private DSR (?6n DECXCPR, ?996n color scheme) + ps = params.raw_or_default(0, 0) + if ps == 6: + r_out = ( + (scr._cur_row - top + 1) + if self._modes.is_set(Mode.DECOM) + else (scr._cur_row + 1) + ) + c_out = ( + (scr._cur_col - left + 1) + if self._modes.is_set(Mode.DECOM) + else (scr._cur_col + 1) + ) + self._emit_reply(f"\x1b[?{r_out};{c_out}R".encode("ascii")) + elif ps == 996 and self._policy.allow_color_queries: + scheme = self._profile.color_scheme + self._emit_reply(f"\x1b[?997;{int(scheme)}n".encode("ascii")) + self._emit_event(ColorSchemeQueried(scheme=scheme)) + return + + if prefix != 0: + if prefix == ord(">") and final in (ord("m"), ord("n")): + # XTMODKEYS: accept quietly + return + self._unhandled("csi", f"CSI {chr(prefix)}{chr(final)}") + return + + ch_final = chr(final) + c_row = scr._cur_row + c_col = scr._cur_col + + if ch_final == "m": + self._style = parse_sgr(params, self._style, memo=self._sgr_memo) + self._sync_pen_cache() + elif ch_final in ("h", "l"): + enable = ch_final == "h" + for val in params.values: + self._apply_mode(val, private=False, enabled=enable) + elif ch_final == "A": # CUU + n = params.get(0, 1) + floor = top if c_row >= top else 0 + self._set_cursor(scr, max(floor, c_row - n), c_col) + elif ch_final == "B": # CUD + n = params.get(0, 1) + ceil = bottom if c_row <= bottom else scr.rows - 1 + self._set_cursor(scr, min(ceil, c_row + n), c_col) + elif ch_final == "C": # CUF + n = params.get(0, 1) + ceil = right if c_col <= right else scr.cols - 1 + self._set_cursor(scr, c_row, min(ceil, c_col + n)) + elif ch_final == "D": # CUB + self._cursor_left(scr, params.get(0, 1), is_backspace=False) + elif ch_final == "E": # CNL + n = params.get(0, 1) + ceil = bottom if c_row <= bottom else scr.rows - 1 + self._set_cursor(scr, min(ceil, c_row + n), left) + elif ch_final == "F": # CPL + n = params.get(0, 1) + floor = top if c_row >= top else 0 + self._set_cursor(scr, max(floor, c_row - n), left) + elif ch_final in ("G", "`"): # CHA / HPA + col_1 = params.get(0, 1) + if self._modes.is_set(Mode.DECOM): + target_c = min(right, left + col_1 - 1) + else: + target_c = min(scr.cols - 1, col_1 - 1) + self._set_cursor(scr, c_row, max(0, target_c)) + elif ch_final == "I": # CHT (Cursor Forward Tabulation) + count = params.get(0, 1) + ceil = right if c_col <= right else scr.cols - 1 + col_iter = c_col + for _ in range(count): + col_iter = next( + (t_c for t_c in scr._tabstops_sorted if col_iter < t_c <= ceil), + ceil, + ) + if col_iter >= ceil: + break + self._set_cursor(scr, c_row, col_iter, pending_wrap=False) + elif ch_final == "Z": # CBT (Cursor Backward Tabulation) + count = params.get(0, 1) + floor = left if c_col >= left else 0 + col_iter = c_col + for _ in range(count): + prev_tabs = [ + t_c for t_c in scr._tabstops_sorted if floor <= t_c < col_iter + ] + col_iter = prev_tabs[-1] if prev_tabs else floor + if col_iter <= floor: + break + self._set_cursor(scr, c_row, col_iter, pending_wrap=False) + elif ch_final == "d": # VPA + row_1 = params.get(0, 1) + if self._modes.is_set(Mode.DECOM): + target_r = min(bottom, top + row_1 - 1) + else: + target_r = min(scr.rows - 1, row_1 - 1) + self._set_cursor(scr, max(0, target_r), c_col) + elif ch_final in ("H", "f"): # CUP / HVP + row_1 = params.get(0, 1) + col_1 = params.get(1, 1) + if self._modes.is_set(Mode.DECOM): + r = min(bottom, max(top, top + row_1 - 1)) + c = min(right, max(left, left + col_1 - 1)) + else: + r = min(scr.rows - 1, max(0, row_1 - 1)) + c = min(scr.cols - 1, max(0, col_1 - 1)) + self._set_cursor(scr, r, c) + elif ch_final == "J": # ED + self._erase_display(scr, params.raw_or_default(0, 0), selective=False) + elif ch_final == "K": # EL + self._erase_line(scr, params.raw_or_default(0, 0), selective=False) + elif ch_final == "X": # ECH + self._before_mutate() + n = min(scr.cols - c_col, params.get(0, 1)) + bce_w, bce_e = self._bce_pair() + scr._rows[c_row].clear_range(c_col, c_col + n, bce_w, bce_e) + self._notify_erase(Rect(c_row, c_col, 1, n), EraseCause.ECH) + self._set_cursor(scr, c_row, c_col, pending_wrap=False) + elif ch_final == "@": # ICH + self._before_mutate() + n = params.get(0, 1) + bce_w, bce_e = self._bce_pair() + scr._rows[c_row].insert_blanks( + c_col, + n, + left=left, + right=right, + bce_word=bce_w, + bce_ext=bce_e, + ) + self._set_cursor(scr, c_row, c_col, pending_wrap=False) + elif ch_final == "P": # DCH + self._before_mutate() + n = params.get(0, 1) + bce_w, bce_e = self._bce_pair() + scr._rows[c_row].delete_cells( + c_col, + n, + left=left, + right=right, + bce_word=bce_w, + bce_ext=bce_e, + ) + self._set_cursor(scr, c_row, c_col, pending_wrap=False) + elif ch_final == "L": # IL + if top <= c_row <= bottom and left <= c_col <= right: + self._before_mutate() + n = params.get(0, 1) + bce_w, bce_e = self._bce_pair() + scr.scroll_down( + n, + top=c_row, + bottom=bottom, + left=left, + right=right, + bce_word=bce_w, + bce_ext=bce_e, + ) + self._notify_erase( + Rect(c_row, left, min(n, bottom - c_row + 1), right - left + 1), + EraseCause.SCROLL, + ) + self._set_cursor(scr, c_row, left) + elif ch_final == "M": # DL + if top <= c_row <= bottom and left <= c_col <= right: + self._before_mutate() + n = params.get(0, 1) + bce_w, bce_e = self._bce_pair() + scr.scroll_up( + n, + top=c_row, + bottom=bottom, + left=left, + right=right, + save_history=False, + bce_word=bce_w, + bce_ext=bce_e, + ) + self._notify_erase( + Rect( + max(c_row, bottom - n + 1), + left, + min(n, bottom - c_row + 1), + right - left + 1, + ), + EraseCause.SCROLL, + ) + self._set_cursor(scr, c_row, left) + elif ch_final == "S": # SU + self._before_mutate() + n = params.get(0, 1) + bce_w, bce_e = self._bce_pair() + scr.scroll_up( + n, + top=top, + bottom=bottom, + left=left, + right=right, + save_history=False, + bce_word=bce_w, + bce_ext=bce_e, + ) + self._notify_erase( + Rect( + max(top, bottom - n + 1), + left, + min(n, bottom - top + 1), + right - left + 1, + ), + EraseCause.SCROLL, + ) + self._clear_cluster_anchor() + elif ch_final == "T": # SD + self._before_mutate() + n = params.get(0, 1) + bce_w, bce_e = self._bce_pair() + scr.scroll_down( + n, + top=top, + bottom=bottom, + left=left, + right=right, + bce_word=bce_w, + bce_ext=bce_e, + ) + self._notify_erase( + Rect(top, left, min(n, bottom - top + 1), right - left + 1), + EraseCause.SCROLL, + ) + self._clear_cluster_anchor() + elif ch_final == "b": # REP + if self._last_printed: + count = min(self._limits.max_rep_count, params.get(0, 1)) + self._handle_print(self._last_printed * count) + elif ch_final == "r": # DECSTBM + t_arg = params.get(0, 1) - 1 + b_arg = params.get(1, scr.rows) - 1 + t_clamped = max(0, min(scr.rows - 1, t_arg)) + b_clamped = max(0, min(scr.rows - 1, b_arg)) + if t_clamped < b_clamped: + sr = scr.scroll_region + scr.scroll_region = ScrollRegion( + top=t_clamped, + bottom=b_clamped, + left=sr.left, + right=sr.right, + ) + decom = self._modes.is_set(Mode.DECOM) + _, _, eff_left, _ = self._effective_margins(scr) + self._set_cursor( + scr, + t_clamped if decom else 0, + eff_left if decom else 0, + ) + elif ch_final == "s": # DECSLRM (when ?69 set) or SCOSC + if self._modes.is_set(Mode.DECLRMM): + l_arg = params.get(0, 1) - 1 + r_arg = params.get(1, scr.cols) - 1 + l_clamped = max(0, min(scr.cols - 1, l_arg)) + r_clamped = max(0, min(scr.cols - 1, r_arg)) + if l_clamped < r_clamped: + sr = scr.scroll_region + scr.scroll_region = ScrollRegion( + top=sr.top, + bottom=sr.bottom, + left=l_clamped, + right=r_clamped, + ) + decom = self._modes.is_set(Mode.DECOM) + self._set_cursor( + scr, + sr.top if decom else 0, + l_clamped if decom else 0, + ) + else: + self._save_cursor() + elif ch_final == "u": # SCORC + self._restore_cursor() + elif ch_final == "g": # TBC + mode = params.raw_or_default(0, 0) + if mode == 0: + scr.clear_tabstop(c_col) + elif mode == 3: + scr.clear_all_tabstops() + elif ch_final == "c": # DA1 + if params.raw_or_default(0, 0) == 0: + self._emit_reply(self._profile.da1) + elif ch_final == "n": # DSR + ps = params.raw_or_default(0, 0) + if ps == 5: + self._emit_reply(b"\x1b[0n") + elif ps == 6: + r_out = ( + (c_row - top + 1) if self._modes.is_set(Mode.DECOM) else (c_row + 1) + ) + c_out = ( + (c_col - left + 1) + if self._modes.is_set(Mode.DECOM) + else (c_col + 1) + ) + self._emit_reply(f"\x1b[{r_out};{c_out}R".encode("ascii")) + elif ch_final == "t": # XTWINOPS + op = params.raw_or_default(0, 0) + if op == 18: # report text area size in chars + self._emit_reply(f"\x1b[8;{scr.rows};{scr.cols}t".encode("ascii")) + elif op == 14: # report text area size in pixels (16x8 nominal cell) + self._emit_reply( + f"\x1b[4;{scr.rows * 16};{scr.cols * 8}t".encode("ascii"), + ) + elif op == 21 and self._policy.allow_title_report: + safe_title = "".join( + ch for ch in self._title if " " <= ch <= "~" and ch != "\\" + ) + self._emit_reply(f"\x1b]l{safe_title}\x1b\\".encode("ascii")) + elif op == 22: # push title onto stack + if len(self._title_stack) < 16: + self._title_stack.append(self._title) + elif op == 23 and self._title_stack: # pop title from stack + self._title = self._title_stack.pop() + self._emit_event(TitleChanged(title=self._title)) + else: + self._unhandled("csi", f"CSI {ch_final}") + + def _update_cwd(self, raw_uri: str) -> None: + cleaned = sanitize_terminal_text(raw_uri.strip()) + if cleaned.startswith("file://"): + parsed = urllib.parse.urlsplit(cleaned) + host = parsed.hostname or "" + local_host = os.uname().nodename if hasattr(os, "uname") else "" + if host not in ("", "localhost", local_host): + return + path = urllib.parse.unquote(parsed.path) + else: + path = cleaned + self._cwd = path + self._emit_event(WorkingDirectoryChanged(uri=cleaned, path=path)) + + def _handle_osc(self, code: int, data: bytes, terminator: bytes) -> None: + scr = self._screens.active + out_term = b"\x07" if terminator == b"\x07" else b"\x1b\\" + + if code in (0, 2): + text = data.decode("utf-8", errors="replace") + self._title = text + self._emit_event(TitleChanged(title=text)) + elif code == 1: + return + elif code == 7: + self._update_cwd(data.decode("utf-8", errors="replace")) + elif code == 8: + text = data.decode("utf-8", errors="replace") + sep = text.find(";") + if sep == -1: + return + params_part = text[:sep] + uri = text[sep + 1 :] + if not uri: + self._hyperlink = None + else: + link_id = "" + for kv in params_part.split(":"): + if kv.startswith("id="): + link_id = kv[3:] + break + self._hyperlink = Hyperlink(uri=uri, id=link_id) + self._sync_pen_cache() + elif code == 9: + text = data.decode("utf-8", errors="replace") + parts = text.split(";") + if len(parts) >= 2 and parts[0] == "4" and parts[1].isdigit(): + sub = int(parts[1]) + prog = int(parts[2]) if len(parts) >= 3 and parts[2].isdigit() else None + changed, status = self._status_store.apply_osc_9_4(sub, prog) + if changed: + self._emit_event(ProgramStatusChanged(status=status, task_id="")) + elif len(parts) >= 2 and parts[0] == "9": + self._update_cwd(";".join(parts[1:])) + elif code in (10, 11) and data == b"?" and self._policy.allow_color_queries: + r, g, b = self._profile.fg_rgb if code == 10 else self._profile.bg_rgb + reply = ( + f"\x1b]{code};rgb:{r:02x}{r:02x}/{g:02x}{g:02x}/{b:02x}{b:02x}".encode( + "ascii", + ) + ) + self._emit_reply(reply + out_term) + elif code == 52: + semi = data.find(b";") + if semi == -1: + return + sel = data[:semi].decode("ascii", errors="ignore") or "c" + body = data[semi + 1 :] + if body == b"?": + if self._policy.allow_clipboard_read: + self._emit_reply(f"\x1b]52;{sel};\x1b\\".encode("ascii")) + return + if self._policy.allow_clipboard_write: + try: + raw_clip = base64.b64decode(body, validate=False) + clip_text = raw_clip.decode("utf-8", errors="replace") + except (binascii.Error, ValueError): + return + self._emit_event(ClipboardWrite(selection=sel, text=clip_text)) + elif code == 133: + text = data.decode("utf-8", errors="replace") + parts = text.split(";") + raw_kind = parts[0][:1] if parts and parts[0] else "" + if raw_kind in ("A", "B", "C", "D"): + kind = PromptKind(raw_kind) + exit_code: int | None = None + is_continuation = any(p.strip() == "k=s" for p in parts[1:]) + if ( + kind == PromptKind.COMMAND_FINISHED + and len(parts) >= 2 + and parts[1].lstrip("-").isdigit() + ): + exit_code = int(parts[1]) + abs_r = self._screens.primary.scrolled_total + scr._cur_row + zone = PromptZone( + kind=kind, + row=scr._cur_row, + col=scr._cur_col, + exit_code=exit_code, + abs_row=abs_r, + ) + self._prompt_zones.append(zone) + self._step_event |= StopOn.PROMPT_MARK + self._emit_event(PromptMark(zone=zone)) + if ( + kind == PromptKind.PROMPT_START + and not is_continuation + and self._status_store.on_prompt_start() + ): + self._emit_event( + ProgramStatusChanged(status=self._status_store.most_urgent), + ) + elif code == 7501: + if data == b"?": + has_consumer = ( + self._policy.allow_program_status_query + or self._on_event is not None + or self._record_events + ) + if has_consumer: + cap = self._profile.osc_7501_capabilities + self._emit_reply(f"\x1b]7501;{cap}".encode("ascii") + out_term) + return + changed, rec = self._status_store.apply_osc_7501(data) + if changed: + tid = rec.id if rec is not None else "" + self._emit_event(ProgramStatusChanged(status=rec, task_id=tid)) + else: + self._unhandled("osc", f"OSC {code}") + + def _handle_decrqss(self, req: bytes) -> None: + scr = self._screens.active + if req == b"m": + sgr_body = _style_to_sgr(self._style)[2:] # strip leading ESC [ + self._emit_reply(f"\x1bP1$r{sgr_body}\x1b\\".encode("ascii")) + elif req == b"r": + sr = scr.scroll_region + self._emit_reply( + f"\x1bP1$r{sr.top + 1};{sr.bottom + 1}r\x1b\\".encode("ascii"), + ) + elif req == b"s" and self._modes.is_set(Mode.DECLRMM): + sr = scr.scroll_region + self._emit_reply( + f"\x1bP1$r{sr.left + 1};{sr.right + 1}s\x1b\\".encode("ascii"), + ) + elif req == b" q": + shape_map = { + (CursorShape.BLOCK, True): 1, + (CursorShape.BLOCK, False): 2, + (CursorShape.UNDERLINE, True): 3, + (CursorShape.UNDERLINE, False): 4, + (CursorShape.BAR, True): 5, + (CursorShape.BAR, False): 6, + } + code = shape_map[(scr._cur_shape, scr._cur_blinking)] + self._emit_reply(f"\x1bP1$r{code} q\x1b\\".encode("ascii")) + elif req == b'"q': + code = 1 if self._protected else 0 + self._emit_reply(f'\x1bP1$r{code}"q\x1b\\'.encode("ascii")) + else: + self._emit_reply(b"\x1bP0$r\x1b\\") + + def _handle_xtgettcap(self, data: bytes) -> None: + for hex_name in data.split(b";"): + if not hex_name: + continue + try: + cap_name = bytes.fromhex(hex_name.decode("ascii")).decode("ascii") + except ValueError: + self._emit_reply(b"\x1bP0+r\x1b\\") + continue + if cap_name in _TERMINFO_CAPS: + val = _TERMINFO_CAPS[cap_name] + enc_k = _hex_encode(cap_name) + if val: + enc_v = _hex_encode(val) + self._emit_reply(f"\x1bP1+r{enc_k}={enc_v}\x1b\\".encode("ascii")) + else: + self._emit_reply(f"\x1bP1+r{enc_k}\x1b\\".encode("ascii")) + else: + self._emit_reply(b"\x1bP0+r\x1b\\") + + def _handle_dcs( + self, + prefix: int, + params: CsiParams, + intermediates: bytes, + final: int, + data: bytes, + ) -> None: + # DECRQSS: DCS $ q ST + if prefix == 0 and intermediates == b"$" and final == ord("q"): + self._handle_decrqss(data) + return + + # XTGETTCAP: DCS + q ST + if prefix == 0 and intermediates == b"+" and final == ord("q"): + self._handle_xtgettcap(data) + return + + # tmux passthrough: DCS tmux; ESC ESC ... ST (final='t', data=b"mux;...") + if ( + self._policy.unwrap_tmux_passthrough + and self._passthrough_depth < 2 + and prefix == 0 + and not intermediates + and final == ord("t") + and data.startswith(b"mux;") + ): + unwrapped = memoryview(data)[4:] + inner_parser = Parser(limits=self._limits) + self._passthrough_depth += 1 + try: + inner_parser.feed_to(unwrapped, self._sink) + finally: + self._passthrough_depth -= 1 + return + + # SIXEL: DCS Ps... q ST + if prefix == 0 and not intermediates and final == ord("q"): + if self._record_events or self._on_event is not None: + scr = self._screens.active + self._emit_event( + SixelGraphic( + data=SixelData( + row=scr._cur_row, + col=scr._cur_col, + params=params.values, + payload=data, + ), + ), + ) + return + + inter_s = intermediates.decode("ascii", errors="replace") + self._unhandled("dcs", f"DCS {inter_s}{chr(final)}") + + def _handle_apc(self, data: bytes) -> None: + if data.startswith(b"G"): + if self._record_events or self._on_event is not None: + body = data[1:] + sep = body.find(b";") + ctrl_bytes = body if sep == -1 else body[:sep] + payload = b"" if sep == -1 else body[sep + 1 :] + control: dict[str, str] = {} + for pair in ctrl_bytes.decode("ascii", errors="ignore").split(","): + if "=" in pair: + k, v = pair.split("=", 1) + control[k] = v + scr = self._screens.active + self._emit_event( + KittyGraphic( + command=KittyCommand( + row=scr._cur_row, + col=scr._cur_col, + control=control, + payload=payload, + ), + ), + ) + return + self._unhandled("apc", f"APC len={len(data)}") + + +def render( + data: collections.abc.Buffer | str, + /, + *, + rows: int = 24, + cols: int = 80, + profile: Profile = DEFAULT_PROFILE, +) -> str: + """Emulate *data* on a fresh ``(rows, cols)`` terminal and return ``text``.""" + term = Terminal(rows=rows, cols=cols, scrollback=0, profile=profile) + if isinstance(data, str): + term.feed_str(data) + else: + term.feed(data) + return term.text + + +class _StripSink: + __slots__ = ("parts",) + + def __init__(self) -> None: + self.parts: list[str] = [] + + def on_print(self, text: str) -> None: + self.parts.append(text) + + def on_execute(self, byte: int) -> None: + if byte == 0x0A: + self.parts.append("\n") + elif byte == 0x09: + self.parts.append("\t") + + def on_esc(self, intermediates: bytes, final: int) -> None: + pass + + def on_csi( + self, + prefix: int, + params: CsiParams, + intermediates: bytes, + final: int, + ) -> None: + pass + + def on_osc(self, code: int, data: bytes, terminator: bytes) -> None: + pass + + def on_dcs( + self, + prefix: int, + params: CsiParams, + intermediates: bytes, + final: int, + data: bytes, + ) -> None: + pass + + def on_apc(self, data: bytes) -> None: + pass + + +def strip(data: collections.abc.Buffer | str, /) -> str: + """Strip VT escape, CSI, OSC, DCS, and APC sequences, keeping plain text.""" + raw = data.encode("utf-8") if isinstance(data, str) else data + sink = _StripSink() + Parser().feed_to(raw, sink) + return "".join(sink.parts) + + +__all__ = [ + "FlightRecorder", + "Formatter", + "OutputFormat", + "Snapshot", + "StepResult", + "StopOn", + "Terminal", + "render", + "strip", +] diff --git a/src/libvt/testing.py b/src/libvt/testing.py new file mode 100644 index 0000000..8ed8da7 --- /dev/null +++ b/src/libvt/testing.py @@ -0,0 +1,204 @@ +"""Column-exact visual boxed screen formatting and test assertions for libvt.""" + +from __future__ import annotations + +import collections.abc +import textwrap + +from libvt._grid import raw_width_bits +from libvt._ucd import ( + WidthRole, + char_width, + display_width, + sanitize_terminal_text, +) +from libvt.codec import format_explain +from libvt.exc import ScreenAssertionError +from libvt.terminal import Snapshot, Terminal + + +def _format_row_cells(snap: Snapshot, row_idx: int, width: int) -> str: + row = snap._rows[row_idx] + parts: list[str] = [] + cols_used = 0 + c = 0 + limit = min(width, snap.cols) + while c < limit and cols_used < width: + word = row.attr_at(c) + rb = raw_width_bits(word) + if rb == int(WidthRole.SPACER_TAIL): + c += 1 + continue + if rb == int(WidthRole.SPACER_HEAD): + parts.append(" ") + cols_used += 1 + c += 1 + continue + cell_w = 2 if rb == int(WidthRole.WIDE) else 1 + if cols_used + cell_w > width: + parts.append(" ") + cols_used += 1 + break + parts.append(sanitize_terminal_text(row.chars[c])) + cols_used += cell_w + c += 1 + if cols_used < width: + parts.append(" " * (width - cols_used)) + return "".join(parts) + + +def _pad_expected_line(line: str, width: int) -> str: + sanitized = sanitize_terminal_text(line) + out: list[str] = [] + cols_used = 0 + for ch in sanitized: + cw = char_width(ch) + if cols_used + cw > width: + break + out.append(ch) + cols_used += cw + if cols_used < width: + out.append(" " * (width - cols_used)) + return "".join(out) + + +def format_screen_box( + target: Terminal | Snapshot, + *, + rows: int | None = None, + cols: int | None = None, +) -> str: + """Render *target* inside a column-aligned Unicode ``┌──┐`` / ``│..│`` frame. + + Soft-wrapped rows display a ``W`` marker immediately right of the right + border, and C0/C1/BiDi override codepoints are escaped safely. + """ + snap = target.snapshot() if isinstance(target, Terminal) else target + h = snap.rows if rows is None else min(rows, snap.rows) + w = snap.cols if cols is None else min(cols, snap.cols) + border_h = "─" * w + out = [f"┌{border_h}┐"] + for r in range(h): + content = _format_row_cells(snap, r, w) + wrap_mark = "W" if snap._rows[r].wrapped else "" + out.append(f"│{content}│{wrap_mark}") + out.append(f"└{border_h}┘") + return "\n".join(out) + + +def format_flight_recorder(target: Terminal) -> str: + """Render compact flight-recorder state and recent disassembled VT bytes.""" + modes_str = ", ".join(m.name for m in sorted(target.modes.enabled_modes(), key=int)) + lines = [ + "Flight Recorder:", + ( + f" cursor=({target.cursor.row}, {target.cursor.col}) " + f"pending_wrap={target.cursor.pending_wrap} " + f"alt={target.screens.active_is_alt} " + f"parser={target.parser_state.name}" + ), + f" modes=[{modes_str}]", + ] + if target.program_status is not None: + ps = target.program_status + lines.append( + f" program_status={ps.state.value} id={ps.id!r} progress={ps.progress}", + ) + rec = target.recorder + if rec is not None: + tail = rec.tail(256) + lines.append(f" recent_bytes ({len(tail)}/{rec.total_bytes}B): {tail!r}") + explained = format_explain(tail) + if explained: + lines.extend(f" {ln}" for ln in explained.splitlines()[-12:]) + return "\n".join(lines) + + +def assert_screen( + target: Terminal | Snapshot, + expected: str | collections.abc.Sequence[str], + *, + cursor: tuple[int, int] | None = None, +) -> None: + """Assert that *target*'s visible lines (and optional *cursor*) match *expected*. + + Parameters + ---------- + target : Terminal | Snapshot + Live terminal or immutable snapshot under test. + expected : str | Sequence[str] + Expected visible text (dedented when passed as a multi-line string) + or explicit sequence of row strings. + cursor : tuple[int, int] | None, optional + Expected zero-based ``(row, col)`` cursor coordinates, if checked. + + Raises + ------ + ScreenAssertionError + When visible lines or cursor coordinates differ from *expected*. + """ + snap = target.snapshot() if isinstance(target, Terminal) else target + if isinstance(expected, str): + cleaned = textwrap.dedent(expected).removeprefix("\n").removesuffix("\n") + raw_lines = cleaned.split("\n") if cleaned else [] + if ( + len(raw_lines) >= 2 + and raw_lines[0].startswith("┌") + and raw_lines[0].endswith("┐") + and raw_lines[-1].startswith("└") + and raw_lines[-1].endswith("┘") + ): + unboxed: list[str] = [] + for box_ln in raw_lines[1:-1]: + body = box_ln.removeprefix("│") + body = body.removesuffix("W") + body = body.removesuffix("│").rstrip(" ") + unboxed.append(body) + while unboxed and unboxed[-1] == "": + unboxed.pop() + exp_lines = unboxed + else: + exp_lines = raw_lines + else: + exp_lines = list(expected) + + actual_text = snap.text + act_lines = actual_text.split("\n") if actual_text else [] + + cursor_ok = cursor is None or (snap.cursor.row, snap.cursor.col) == cursor + if act_lines == exp_lines and cursor_ok: + return + + preview_rows = min(snap.rows, max(len(exp_lines), len(act_lines), 1)) + max_exp_w = max((display_width(x) for x in exp_lines), default=0) + max_act_w = max((display_width(x) for x in act_lines), default=0) + preview_cols = min(snap.cols, max(max_exp_w, max_act_w, 12)) + + actual_box = format_screen_box(snap, rows=preview_rows, cols=preview_cols) + exp_border = "─" * preview_cols + exp_box_lines = [f"┌{exp_border}┐"] + for idx in range(preview_rows): + line = exp_lines[idx] if idx < len(exp_lines) else "" + exp_box_lines.append(f"│{_pad_expected_line(line, preview_cols)}│") + exp_box_lines.append(f"└{exp_border}┘") + expected_box = "\n".join(exp_box_lines) + + details = [ + "Screen state mismatch:", + f"cursor actual=({snap.cursor.row}, {snap.cursor.col})" + + (f" expected={cursor}" if cursor is not None else ""), + "Expected:", + expected_box, + "Actual:", + actual_box, + ] + if isinstance(target, Terminal): + details.append(format_flight_recorder(target)) + raise ScreenAssertionError("\n".join(details)) + + +__all__ = [ + "assert_screen", + "format_flight_recorder", + "format_screen_box", +] diff --git a/tests/test_aio_and_pytest.py b/tests/test_aio_and_pytest.py new file mode 100644 index 0000000..8aeac53 --- /dev/null +++ b/tests/test_aio_and_pytest.py @@ -0,0 +1,141 @@ +"""Async stream, POSIX PTY subprocess, pytest fixture, and boxed assertion tests.""" + +from __future__ import annotations + +import asyncio +import sys + +import pytest + +import libvt +from libvt.aio import AsyncTerminalStream, open_pty +from libvt.pytest_plugin import PtyFactory, TerminalFactory +from libvt.terminal import FlightRecorder, Terminal +from libvt.testing import assert_screen + + +class _MemoryWriter: + """Minimal writer stub capturing reply bytes flushed by ``AsyncTerminalStream``.""" + + def __init__(self) -> None: + self.buffer = bytearray() + self.closed = False + + def write(self, data: bytes, /) -> None: + self.buffer.extend(data) + + async def drain(self) -> None: + await asyncio.sleep(0) + + def close(self) -> None: + self.closed = True + + async def wait_closed(self) -> None: + await asyncio.sleep(0) + + +async def test_async_terminal_stream_sync_coalescing_timeout_and_replies() -> None: + """``AsyncTerminalStream`` coalesces ``?2026``, expires wedges, and writes DSR.""" + reader = asyncio.StreamReader() + writer = _MemoryWriter() + stream = AsyncTerminalStream( + reader, + writer, + rows=4, + cols=20, + sync_timeout=0.05, + ) + + # Direct wait_for (without background start()) expires wedged ?2026h cleanly. + reader.feed_data(b"base\x1b[?2026h\x1b[Hwedged\x1b[6n") + snap = await stream.wait_for("wedged", timeout=0.5) + assert snap[0].text == "wedged" + assert bytes(writer.buffer) == b"\x1b[1;7R" + + # Background pump task mode coalesces normal ?2026h ... ?2026l batches cleanly. + async with AsyncTerminalStream( + asyncio.StreamReader(), + rows=4, + cols=20, + sync_timeout=0.05, + ) as bg_stream: + bg_stream.reader.feed_data(b"\x1b[?2026h\x1b[Hatomic-ok\x1b[?2026l") + snap2 = await bg_stream.wait_for("atomic-ok", timeout=0.5) + assert snap2[0].text == "atomic-ok" + + +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX pty required") +async def test_open_pty_and_vt_pty_live_posix_subprocess( + vt_pty: PtyFactory, +) -> None: + """``open_pty`` and ``vt_pty`` bridge live child processes and DSR replies.""" + child_code = ( + "import sys, tty; " + "tty.setcbreak(sys.stdin.fileno()); " + "sys.stdout.write('\\x1b]7501;state=working:id=job\\x1b\\\\hello\\x1b[6n'); " + "sys.stdout.flush(); " + "reply = b''; " + "\nwhile not reply.endswith(b'R'):\n" + " ch = sys.stdin.buffer.read(1)\n" + " if not ch: break\n" + " reply += ch\n" + "print(' DSR=' + repr(reply.decode('ascii', 'replace')), flush=True); " + "line = b''\n" + "while not line.endswith((b'\\r', b'\\n')):\n" + " b = sys.stdin.buffer.read(1)\n" + " if not b: break\n" + " line += b\n" + "print('ECHO=' + line.decode('utf-8').strip(), flush=True)" + ) + async with open_pty( + (sys.executable, "-u", "-c", child_code), + rows=6, + cols=40, + ) as pty_sess: + await pty_sess.wait_for("DSR='\\x1b[1;6R'", timeout=3.0) + assert "job" in pty_sess.terminal.program_statuses + pty_sess.resize(rows=8, cols=50) + pty_sess.send("ping") + pty_sess.send_key("enter") + snap = await pty_sess.wait_for("ECHO=ping", timeout=3.0) + assert "ECHO=ping" in snap.text + # After exit, active working status is pruned automatically. + assert pty_sess.terminal.program_statuses == {} + + async with vt_pty( + (sys.executable, "-c", "print('fixture-pty-ok')"), + rows=4, + cols=30, + ) as sess2: + await sess2.wait_for("fixture-pty-ok", timeout=3.0) + + +def test_pytest_fixtures_and_assert_screen_diagnostics( + vt_terminal: Terminal, + vt_factory: TerminalFactory, + vt_parser: libvt.Parser, + vt_recorder: FlightRecorder, +) -> None: + """Fixtures construct clean instances and ``assert_screen`` escapes BiDi spoofs.""" + assert vt_terminal.rows == 24 + assert vt_terminal.cols == 80 + assert vt_terminal.recorder is vt_recorder + assert isinstance(vt_parser, libvt.Parser) + + small = vt_factory(rows=2, cols=8) + small.feed("日本ok\r\nline2".encode()) + assert_screen( + small, + "┌────────┐\n│日本ok │\n│line2 │\n└────────┘", + ) + + # BiDi spoofing in cells is escaped in failure diffs alongside FlightRecorder dump. + spoof_term = vt_factory(rows=1, cols=10, recorder=vt_recorder) + spoof_term.feed(b"\x1b[31mhi") + spoof_term.screen._rows[0].chars[2] = "\u202e" + spoof_term.screen._rows[0].used = 3 + with pytest.raises(AssertionError) as exc_info: + assert_screen(spoof_term, "┌──────────┐\n│mismatch │\n└──────────┘") + msg = str(exc_info.value) + assert "\\u202e" in msg + assert "Flight Recorder:" in msg diff --git a/tests/test_codec_and_cli.py b/tests/test_codec_and_cli.py new file mode 100644 index 0000000..2b62996 --- /dev/null +++ b/tests/test_codec_and_cli.py @@ -0,0 +1,58 @@ +"""Declarative VT sequence explainer and ``python -m libvt`` CLI tests.""" + +from __future__ import annotations + +import pathlib +import subprocess +import sys + +import pytest + +from libvt.__main__ import main +from libvt.codec import explain, format_explain + + +def test_codec_explain_and_format_explain() -> None: + """``explain`` and ``format_explain`` annotate SGR, CSI, OSC, DCS, and UTF-8.""" + sample = ( + b"\x1b[?2026h\x1b[1;38:2::10:20:30mHi\r\n" + b"\x1b]7501;state=working\x1b\\\x1bP>|libvt\x1b\\\x1b[?2026l" + ) + items = explain(sample) + kinds = {it.kind for it in items} + mnemonics = {it.mnemonic for it in items} + assert {"CSI", "PRINT", "C0", "OSC", "DCS"} <= kinds + assert "SGR" in mnemonics + assert "DECSET" in mnemonics + + rendered = format_explain(sample) + assert "SGR" in rendered + assert "7501" in rendered + + +def test_cli_explain_render_and_strip( + tmp_path: pathlib.Path, + capsys: pytest.CaptureFixture[str], +) -> None: + """``python -m libvt`` subcommands process files and stdin byte streams.""" + sample_file = tmp_path / "sample.vt" + sample_file.write_bytes(b"\x1b[1;32mhello\x1b[0m\r\nworld") + + assert main(["strip", str(sample_file)]) == 0 + assert capsys.readouterr().out == "hello\nworld\n" + + assert main(["render", "--rows", "2", "--cols", "8", str(sample_file)]) == 0 + assert capsys.readouterr().out == "hello\nworld\n" + + assert main(["explain", str(sample_file)]) == 0 + explained = capsys.readouterr().out + assert "SGR" in explained + + proc = subprocess.run( + (sys.executable, "-m", "libvt", "strip"), + input=b"\x1b[1;34mpiped\x1b[0m\n", + capture_output=True, + check=False, + ) + assert proc.returncode == 0 + assert proc.stdout == b"piped\n" diff --git a/tests/test_libvt.py b/tests/test_libvt.py index 09eecbd..3df3a6b 100644 --- a/tests/test_libvt.py +++ b/tests/test_libvt.py @@ -1,7 +1,12 @@ -"""Package smoke and import-hygiene tests for libvt.""" +"""Package smoke, import-hygiene, top-level helper, and docstring tests for libvt.""" from __future__ import annotations +import dataclasses +import importlib +import inspect +import pkgutil +import re import subprocess import sys @@ -17,7 +22,7 @@ def test_package_metadata() -> None: def test_import_libvt_leaves_optional_subsystems_unloaded() -> None: - """Importing ``libvt`` in a fresh interpreter does not import ``asyncio``.""" + """Importing ``libvt`` in a fresh interpreter avoids heavy stdlib/plugin modules.""" proc = subprocess.run( ( sys.executable, @@ -25,6 +30,8 @@ def test_import_libvt_leaves_optional_subsystems_unloaded() -> None: ( "import sys, libvt; " "assert 'asyncio' not in sys.modules, list(sys.modules); " + "assert 'pty' not in sys.modules, list(sys.modules); " + "assert 'termios' not in sys.modules, list(sys.modules); " "assert 'pytest' not in sys.modules, list(sys.modules)" ), ), @@ -33,3 +40,40 @@ def test_import_libvt_leaves_optional_subsystems_unloaded() -> None: check=False, ) assert proc.returncode == 0, proc.stderr + + +def test_top_level_render_strip_and_unicode_helpers() -> None: + """Top-level progressive-disclosure helpers render, strip, and measure text.""" + rendered = libvt.render(b"\x1b[1;32mok\x1b[0m\r\ndone", rows=4, cols=10) + assert rendered == "ok\ndone" + + term = libvt.Terminal(rows=4, cols=10) + term.feed(b"\x1b[1;32mok\x1b[0m\r\ndone") + assert term[0, 0].style.fg == libvt.AnsiColor.GREEN + + assert libvt.strip(b"\x1b[31mred\x1b[0m green") == "red green" + assert libvt.UNICODE_VERSION >= "15.0.0" + assert libvt.display_width("日本") == 4 + assert libvt.display_width("🧑‍🌾") == 2 + assert libvt.sanitize_terminal_text("safe\u202eevil\x07") == "safe\\u202eevil\\x07" + + +def test_public_dataclass_attributes_documented() -> None: + """Every public dataclass documents all public fields under ``Attributes``.""" + missing: list[str] = [] + for modinfo in pkgutil.iter_modules(libvt.__path__, "libvt."): + if modinfo.name.startswith("libvt._"): + continue + mod = importlib.import_module(modinfo.name) + for cls_name, cls_obj in inspect.getmembers(mod, inspect.isclass): + if cls_obj.__module__ != modinfo.name or cls_name.startswith("_"): + continue + if not dataclasses.is_dataclass(cls_obj): + continue + doc = inspect.getdoc(cls_obj) or "" + for fld in dataclasses.fields(cls_obj): + if fld.name.startswith("_"): + continue + if not re.search(rf"^\s*{re.escape(fld.name)}\s*:", doc, re.MULTILINE): + missing.append(f"{modinfo.name}.{cls_name}.{fld.name}") + assert missing == [] diff --git a/tests/test_parser.py b/tests/test_parser.py new file mode 100644 index 0000000..04c5524 --- /dev/null +++ b/tests/test_parser.py @@ -0,0 +1,141 @@ +"""Streaming VT500 parser, SGR subparameter, UTF-8, and C1 isolation tests.""" + +from __future__ import annotations + +import libvt +from libvt.config import Limits +from libvt.parser import ( + Action, + ApcDispatch, + CsiDispatch, + DcsDispatch, + OscDispatch, + Parser, + ParserState, + Print, +) +from libvt.style import AnsiColor, IndexedColor, RgbColor, UnderlineStyle + + +def _coalesce_prints(actions: list[Action]) -> list[Action]: + """Merge adjacent ``Print`` actions so arbitrary chunk cuts compare equal.""" + merged: list[Action] = [] + for act in actions: + if isinstance(act, Print) and merged and isinstance(merged[-1], Print): + merged[-1] = Print(merged[-1].text + act.text) + else: + merged.append(act) + return merged + + +def test_chunk_cut_invariance_across_byte_steps() -> None: + """Arbitrary chunk boundaries yield identical parsed actions and terminal state.""" + payload = ( + b"\x1b[?2026h\x1b[1;4:3;38:2::40:180:160;58:5:196m" + + "Hello 日本 🧑‍🌾 🇯🇵!".encode() + + b"\x1b]8;id=1;https://example.com\x1b\\link\x1b]8;;\x07" + + b"\x1b]7501;state=working:progress=42\x1b\\" + + b"\x1bP1;2+q544e\x1b\\\x1b_Gi=1;AAAA\x1b\\\x1b[?2026l" + ) + + ref_actions = _coalesce_prints(Parser().feed(payload)) + ref_term = libvt.Terminal(rows=6, cols=40) + ref_term.feed(payload) + ref_snap = ref_term.snapshot() + + for step in (1, 2, 3, 5, 7, 13, 31): + parser = Parser() + term = libvt.Terminal(rows=6, cols=40) + chunked_actions: list[Action] = [] + for idx in range(0, len(payload), step): + chunk = payload[idx : idx + step] + chunked_actions.extend(parser.feed(chunk)) + term.feed(chunk) + assert _coalesce_prints(chunked_actions) == ref_actions + assert term.snapshot().text == ref_snap.text + assert term.cursor == ref_snap.cursor + + +def test_sgr_colon_subparameters_and_indexed_vs_ansi() -> None: + """Colon SGR subparameters, 24-bit RGB, and palette color variants stay distinct.""" + term = libvt.Terminal(rows=4, cols=20) + term.feed( + b"\x1b[1;2;4:3;38:2::40:180:160;48;5;1;58:5:196mA\x1b[22;31;24;59mB\x1b[0mC", + ) + cell_a = term[0, 0] + assert cell_a.style.bold is True + assert cell_a.style.dim is True + assert cell_a.style.underline == UnderlineStyle.CURLY + assert cell_a.style.fg == RgbColor(40, 180, 160) + assert cell_a.style.bg == IndexedColor(1) + assert cell_a.style.bg != AnsiColor.RED + assert cell_a.style.underline_color == IndexedColor(196) + + cell_b = term[0, 1] + assert cell_b.style.bold is False + assert cell_b.style.dim is False + assert cell_b.style.fg == AnsiColor.RED + assert cell_b.style.underline == UnderlineStyle.NONE + assert cell_b.style.underline_color is None + + cell_c = term[0, 2] + assert cell_c.style == libvt.Style() + + +def test_utf8_0x9c_inside_osc_dcs_apc_does_not_break_out() -> None: + """UTF-8 ``0x9C`` continuation bytes never terminate string control payloads.""" + title = "Build “日本” Ü 😜" + assert 0x9C in title.encode("utf-8") + + term = libvt.Terminal(rows=4, cols=30) + term.feed(f"\x1b]2;{title}\x07ok".encode()) + assert term.title == title + assert term.text == "ok" + + parser = Parser() + actions = parser.feed( + b"\x1bPq" + title.encode("utf-8") + b"\x1b\\" + b"\x1b_" + title.encode("utf-8") + b"\x1b\\", + ) + assert len(actions) == 2 + assert isinstance(actions[0], DcsDispatch) + assert actions[0].data == title.encode("utf-8") + assert isinstance(actions[1], ApcDispatch) + assert actions[1].data == title.encode("utf-8") + + # Explicit 8-bit C1 opt-in handles single-byte CSI (0x9B) and OSC/ST (0x9D/0x9C). + c1_actions = Parser(c1_controls=True).feed(b"\x9b12;34H\x9d2;ascii\x9c") + assert len(c1_actions) == 2 + assert isinstance(c1_actions[0], CsiDispatch) + assert c1_actions[0].params.values == (12, 34) + assert c1_actions[0].final == ord("H") + assert c1_actions[1] == OscDispatch(2, b"ascii", b"\x9c") + + +def test_incomplete_utf8_flushed_before_c0_control() -> None: + """Incomplete UTF-8 bytes emit ``U+FFFD`` before an intervening C0 control runs.""" + term = libvt.Terminal(rows=4, cols=10) + term.feed(b"\xe2\x82\nX") + # U+FFFD prints at (0, 0) advancing cursor to col 1; LF moves to (1, 1). + assert term[0].text == "\ufffd" + assert term[1].text == " X" + + +def test_double_esc_st_and_oversized_payload_recovery() -> None: + """Double ``ESC`` aborts cleanly and oversized strings resynchronize.""" + term = libvt.Terminal(rows=4, cols=20, limits=Limits(max_osc_bytes=16)) + # First ESC enters OSC_ESC; second ESC cancels OSC and begins ESC \ ST no-op. + term.feed(b"\x1b]2;short\x1b\x1b\\after") + assert term.text == "after" + + term.reset() + term.feed(b"\x1b]2;" + (b"x" * 64) + b"\x07clean") + assert term.title == "" + assert term.text == "clean" + assert term.parser_state == ParserState.GROUND + + # Exercise SGR memo FIFO eviction past 256 unique entries. + for idx in range(300): + r = idx & 0xFF + term.feed(f"\x1b[38;2;{r};10;20m.".encode("ascii")) + assert term[0, 0].text != "" diff --git a/tests/test_protocols_and_input.py b/tests/test_protocols_and_input.py new file mode 100644 index 0000000..f98b7ee --- /dev/null +++ b/tests/test_protocols_and_input.py @@ -0,0 +1,209 @@ +"""Rex OSC 7501, OSC 133/7/52, queries, tmux passthrough, and input encoding tests.""" + +from __future__ import annotations + +import base64 + +import pytest + +import libvt +from libvt.config import Policy, Profile +from libvt.events import ( + ClipboardWrite, + ColorSchemeQueried, + ProgramStatusChanged, + WorkingDirectoryChanged, +) +from libvt.exc import UnsafePasteError +from libvt.input import ( + FocusEvent, + KeyEvent, + KeyMod, + KittyKeyboardFlags, + MouseAction, + MouseButton, + MouseEvent, + PasteEvent, +) +from libvt.status import BlockKind, StatusState + + +def test_osc_7501_rex_grammar_hierarchy_urgency_and_queries() -> None: + """Rex ``OSC 7501`` enforces grammar, hierarchy, urgency, and pruning.""" + silent_term = libvt.Terminal(rows=4, cols=30) + # Query is silent by default when neither policy nor event consumer is attached. + silent_term.feed(b"\x1b]7501;?\x07") + assert silent_term.drain_replies() == b"" + + # Attaching an event consumer enables capability replies mirroring BEL vs ST. + term = libvt.Terminal(rows=6, cols=40, record_events=True) + term.feed(b"\x1b]7501;?\x07") + assert term.drain_replies().endswith(b"\x07") + term.feed(b"\x1b]7501;?\x1b\\") + reply_st = term.drain_replies() + assert reply_st.startswith(b"\x1b]7501;?:") + assert reply_st.endswith(b"\x1b\\") + + # OSC 9;4 fallback populates root status until native 7501 arrives. + term.feed(b"\x1b]9;4;1;35\x07") + assert term.program_status is not None + assert term.program_status.state == StatusState.WORKING + assert term.program_status.progress == 35 + + # Native 7501 hierarchical tasks with base64 title/msg and ancestor app inheritance. + b64_title = base64.b64encode("Compiling 日本".encode()).decode("ascii") + term.feed( + f"\x1b]7501;state=working:id=build:app=cargo:progress=50:title={b64_title}\x1b\\".encode(), + ) + term.feed(b"\x1b]7501;state=blocked:id=build/sign:kind=auth\x1b\\") + # ConEmu 9;4 is ignored once native 7501 has been observed. + term.feed(b"\x1b]9;4;0\x07") + + child = term.program_statuses["build/sign"] + assert child.effective_app == "cargo" + assert child.kind == BlockKind.AUTH + assert term.program_statuses["build"].title == "Compiling 日本" + # Priority: blocked outranks working! + assert term.program_status == child + + # Base64 title containing BiDi or C0 spoofing is rejected. + spoof_b64 = base64.b64encode("ok\u202eevil".encode()).decode("ascii") + term.feed(f"\x1b]7501;state=error:id=spoof:title={spoof_b64}\x1b\\".encode()) + assert "spoof" not in term.program_statuses + + # Secondary prompt OSC 133;A;k=s keeps active status; primary OSC 133;A clears root. + term.feed(b"\x1b]7501;state=working\x1b\\") + assert "" in term.program_statuses + term.feed(b"\x1b]133;A;k=s\x07") + assert "" in term.program_statuses + term.feed(b"\x1b]133;A\x07") + assert "" not in term.program_statuses + + # Process exit prunes working/blocked tasks while preserving terminal done/error. + term.feed(b"\x1b]7501;state=done:id=lint\x1b\\") + term.notify_process_exit() + assert "lint" in term.program_statuses + assert "build" not in term.program_statuses + assert "build/sign" not in term.program_statuses + + term.feed(b"\x1b]7501;state=working:id=tree\x1b\\") + term.feed(b"\x1b]7501;state=working:id=tree/leaf\x1b\\") + term.feed(b"\x1b]7501;state=clear:id=tree\x1b\\") + assert "tree" not in term.program_statuses + assert "tree/leaf" not in term.program_statuses + assert any(isinstance(e, ProgramStatusChanged) for e in term.drain_events()) + + +def test_osc_133_abs_row_osc_7_osc_52_and_tmux_passthrough() -> None: + """``OSC 133`` ``abs_row``, ``OSC 7``/``52``, queries, and ``DCS tmux;`` unwrap.""" + term = libvt.Terminal( + rows=3, + cols=20, + scrollback=20, + profile=Profile(color_scheme=libvt.ColorScheme.LIGHT), + record_events=True, + ) + for idx in range(5): + seq = ( + f"\x1b]133;A\x07$ \x1b]133;B\x07cmd{idx}\r\n" + f"\x1b]133;C\x07out\r\n\x1b]133;D;0\x07" + ) + term.feed(seq.encode()) + zones = term.prompt_zones + assert len(zones) >= 4 + assert [z.abs_row for z in zones] == sorted(z.abs_row for z in zones) + assert zones[-1].exit_code == 0 + + # OSC 7 file URI decoding (local host accepted, remote host ignored by default). + term.feed(b"\x1b]7;file://localhost/tmp/my%20dir\x07") + assert term.cwd == "/tmp/my dir" + term.feed(b"\x1b]7;file://remote-box.example/srv\x07") + assert term.cwd == "/tmp/my dir" + + # OSC 52 write emits ClipboardWrite; '?' query is silent unless enabled. + clip_b64 = base64.b64encode(b"copied").decode("ascii") + term.feed(f"\x1b]52;c;{clip_b64}\x07\x1b]52;c;?\x07".encode("ascii")) + assert term.drain_replies() == b"" + events = term.drain_events() + assert any(isinstance(e, WorkingDirectoryChanged) for e in events) + assert ClipboardWrite(selection="c", text="copied") in events + + # XTVERSION, DECRQSS, XTGETTCAP, OSC 10/11, ?2031 / ?996n, and DCS tmux; unwrap. + term.feed( + b"\x1b[>q\x1bP$qm\x1b\\\x1bP+q544e\x1b\\\x1b]10;?\x07\x1b[?2031h\x1b[?996n", + ) + replies = term.drain_replies() + assert b"\x1bP>|libvt" in replies + assert b"\x1bP1$r" in replies + assert b"\x1bP1+r544e=" in replies + assert b"\x1b]10;rgb:" in replies + assert b"\x1b[?997;2n" in replies + assert ColorSchemeQueried(scheme=libvt.ColorScheme.LIGHT) in term.drain_events() + + # Unwrap 1-level (ST and BEL) and 2-level nested DCS tmux; passthrough. + term.feed(b"\x1bPtmux;\x1b\x1b]2;bel-title\x07\x1b\\") + assert term.title == "bel-title" + term.feed(b"\x1bPtmux;\x1b\x1b]7501;state=done:id=inner\x1b\x1b\\\x1b\\") + assert "inner" in term.program_statuses + term.feed( + b"\x1bPtmux;\x1b\x1bPtmux;" + b"\x1b\x1b\x1b\x1b]7501;state=done:id=nested2\x1b\x1b\x1b\x1b\\" + b"\x1b\x1b\\\x1b\\", + ) + assert "nested2" in term.program_statuses + + +def test_kitty_keyboard_stack_and_input_encoding() -> None: + """``KittyKeyboardStack`` isolates ``CSI u`` from ``SCORC`` and encodes input.""" + term = libvt.Terminal(rows=4, cols=20) + # Save cursor at (1, 3), push Kitty DISAMBIGUATE, then restore cursor with CSI u. + term.feed(b"\x1b[2;4H\x1b[s\x1b[>1u\x1b[1;1H\x1b[u\x1b[?u") + assert term.cursor.row == 1 + assert term.cursor.col == 3 + assert term.kitty_keyboard_flags == KittyKeyboardFlags.DISAMBIGUATE + assert term.drain_replies() == b"\x1b[?1u" + + # Kitty CSI u key encoding vs DECCKM legacy encoding. + assert term.encode(KeyEvent.parse("escape")) == b"\x1b[27u" + assert term.encode(KeyEvent.parse("ctrl+a")) == b"\x1b[97;5u" + + # Popping returns to legacy mode; DECCKM switches Up arrow from CSI A to SS3 A. + term.feed(b"\x1b[<1u\x1b[?1h") + assert term.encode(KeyEvent.parse("up")) == b"\x1bOA" + + # Mouse SGR (?1006 + ?1000) and Focus (?1004). + term.feed(b"\x1b[?1000;1006;1004h") + click = MouseEvent( + row=2, + col=4, + button=MouseButton.LEFT, + action=MouseAction.PRESS, + modifiers=KeyMod.SHIFT, + ) + assert term.encode(click) == b"\x1b[<4;5;3M" + assert term.encode(FocusEvent(focused=True)) == b"\x1b[I" + + +def test_paste_event_fail_closed_and_character_sanitize() -> None: + r"""``PasteEvent`` blocks nested ``\x1b[201~`` bypasses and unbracketed newlines.""" + term = libvt.Terminal(rows=4, cols=20) + with pytest.raises(UnsafePasteError): + term.encode(PasteEvent("ls\nrm -rf /")) + assert ( + term.encode(PasteEvent("line1\nline2", allow_unbracketed_newlines=True)) + == b"line1\nline2" + ) + + term.feed(b"\x1b[?2004h") + assert term.encode(PasteEvent("hello\nworld")) == b"\x1b[200~hello\nworld\x1b[201~" + + # Classic .replace("\x1b[201~", "") smuggling vector fails closed! + with pytest.raises(UnsafePasteError): + term.encode(PasteEvent("safe\x1b[20\x1b[201~1~;evil\n")) + + # Character-level sanitize strips ESC cleanly so no ESC [ 201 ~ can ever reassemble. + sanitized = term.encode(PasteEvent("hi\x1b[20\x1b[201~1~", sanitize=True)) + assert sanitized == b"\x1b[200~hi[20[201~1~\x1b[201~" + + # Policy allow_clipboard_read remains default False. + assert Policy().allow_clipboard_read is False diff --git a/tests/test_terminal.py b/tests/test_terminal.py new file mode 100644 index 0000000..a77517d --- /dev/null +++ b/tests/test_terminal.py @@ -0,0 +1,174 @@ +"""Terminal emulation, charsets, modes, reflow, sync stepping, and format tests.""" + +from __future__ import annotations + +import pytest + +import libvt +from libvt.config import TMUX_PROFILE, XTERM_PROFILE, Policy +from libvt.events import InBandResize, RenderHoldChanged +from libvt.exc import ProtocolError +from libvt.terminal import OutputFormat, StopOn + + +def test_dec_special_graphics_g0_g3_so_si_ss2_ss3_and_decsc() -> None: + """``G0..G3`` DEC Special Graphics translate box drawing and ``DECSC``/``DECRC``.""" + term = libvt.Terminal(rows=4, cols=16) + # DECSC at col 5 saves G0='0'; DECRC restores col 5 and G0='0' ('x' -> '│'). + term.feed(b"\x1b(0lqqqk\x1b7\x1b(B plain\x1b8x") + assert term[0].text == "┌───┐│plain" + + # G1 via SO/SI (0x0E / 0x0F), G2 via SS2 (ESC N), G3 via SS3 (ESC O). + term.reset() + term.feed(b"\x1b)0\x0emqj\x0fa\x1b*0\x1bNl\x1b+0\x1bOkz") + assert term[0].text == "└─┘a┌┐z" + + +def test_cbt_cht_decsca_decsed_decsel_and_csi_22_j() -> None: + """``CBT``/``CHT``, ``DECSCA`` selective erase, and ``CSI 22 J`` scroll-push.""" + term = libvt.Terminal(rows=4, cols=24, scrollback=20) + # CHT 2 jumps 0 -> 16; 'a' prints at 16 (cursor -> 17); CBT 2 steps 17 -> 16 -> 8. + term.feed(b"\x1b[2Ia\x1b[2Zb") + assert term[0, 16].text == "a" + assert term[0, 8].text == "b" + + # DECSCA: CSI 1 " q protects cells from DECSEL (CSI ? 2 K) & DECSED (CSI ? 2 J). + term.reset() + term.feed(b'\x1b[1"qSAFE\x1b[0"qWIPE\x1b[?2K') + assert term[0].text == "SAFE" + term.feed(b"\x1b[?2J") + assert term[0].text == "SAFE" + # Unconditional ED 2 erases protected cells too. + term.feed(b"\x1b[2J") + assert term[0].text == "" + + # CSI 22 J (xterm / Ghostty E3 scroll-clear) pushes viewport lines into scrollback. + term.reset() + term.feed(b"first\r\nsecond") + term.feed(b"\x1b[22J") + assert term.text == "" + assert [r.text for r in term.history] == ["first", "second"] + + +def test_alt_screen_single_truth_decrqm_and_mode_aliases() -> None: + """``?47``, ``?1047``, and ``?1049`` report real buffer state via ``DECRQM``.""" + term = libvt.Terminal(rows=4, cols=12) + term.feed(b"primary\x1b[?47h\x1b[?1049l\x1b[?47$p") + assert term[0].text == "primary" + assert term.screens.active_is_alt is False + # Status 2 means recognized & reset (NOT stale 1 = set). + assert term.drain_replies() == b"\x1b[?47;2$y" + + +def test_tmux_vs_xterm_pending_wrap_and_reverse_wrap() -> None: + """``TMUX_PROFILE`` models phantom-column ``pending_wrap`` and soft-wrap ``BS``.""" + xt = libvt.Terminal(rows=3, cols=5, profile=XTERM_PROFILE) + xt.feed(b"12345\x1b[1DX") + assert xt[0].text == "123X5" + + tm = libvt.Terminal(rows=3, cols=5, profile=TMUX_PROFILE) + tm.feed(b"12345\x1b[1DX") + assert tm[0].text == "1234X" + + # Soft-wrap BS across row boundary in TMUX_PROFILE vs XTERM_PROFILE with ?45h. + tm.reset() + tm.feed(b"abcdef\x08\x08Z") + assert tm[0].text == "abcdZ" + + xt.reset() + xt.feed(b"\x1b[?45habcdef\x08\x08Z") + assert xt[0].text == "abcdZ" + + +def test_resize_reflow_primary_vs_alt_and_inband_2048() -> None: + """Primary soft-wrapped lines reflow on resize; alt crops; ``?2048`` notifies.""" + term = libvt.Terminal(rows=4, cols=10, scrollback=20, record_events=True) + term.feed(b"\x1b[?2048h0123456789abcdefgh\r\nhard") + assert term[0].text == "0123456789" + assert term[0].wrapped is True + assert term[1].text == "abcdefgh" + assert term[2].text == "hard" + + term.resize(rows=4, cols=20) + assert term[0].text == "0123456789abcdefgh" + assert term[0].wrapped is False + assert term[1].text == "hard" + assert term.drain_replies() == b"\x1b[48;4;20;0;0t" + events = term.drain_events() + assert InBandResize(rows=4, cols=20) in events + + # Alt screen never reflows logical lines. + term.feed(b"\x1b[?1049h\x1b[H0123456789abcdefgh") + term.resize(rows=4, cols=10) + assert term[0].text == "0123456789" + assert term[0].wrapped is False + + +def test_synchronized_output_cow_feed_until_and_generation_expiry() -> None: + """``?2026`` CoW holds ``committed``, ``feed_until`` steps, and expiry checks.""" + term = libvt.Terminal(rows=4, cols=16, record_events=True) + term.feed(b"frame-0") + assert term.committed[0].text == "frame-0" + + batch = b"\x1b[?2026h\x1b[Hpartial\x1b[?2026l\x1b[?2026h\x1b[Hframe-2" + res1 = term.feed_until(batch, stop=StopOn.SYNC_END) + assert res1.stopped_on == StopOn.SYNC_END + assert term.synchronized is False + assert term.committed[0].text == "partial" + + term.feed(batch[res1.offset :]) + assert term.synchronized is True + assert term.committed[0].text == "partial" + assert term.snapshot()[0].text == "frame-2" + + cur_gen = term.sync_generation + assert term.expire_synchronized_output(cur_gen - 1) is False + assert term.synchronized is True + assert term.expire_synchronized_output(cur_gen) is True + assert term.synchronized is False + assert term.committed[0].text == "frame-2" + hold_events = [e for e in term.drain_events() if isinstance(e, RenderHoldChanged)] + assert hold_events[-1] == RenderHoldChanged( + active=False, + sync_generation=cur_gen, + expired=True, + ) + + # StopOn.GROUND must not fire in the middle of a multi-byte UTF-8 sequence. + utf8_term = libvt.Terminal(rows=2, cols=10) + part1 = utf8_term.feed_until("日".encode()[:2], stop=StopOn.GROUND) + assert part1.stopped_on == StopOn.EOF + part2 = utf8_term.feed_until("日A".encode()[2:], stop=StopOn.GROUND) + assert part2.stopped_on == StopOn.GROUND + assert part2.offset == 1 + assert utf8_term[0, 0].text == "日" + + +def test_formatter_plain_vt_html_xss_and_snapshot_to_dict() -> None: + """Formatters roundtrip VT, coalesce HTML spans, block XSS URIs, and serialize.""" + term = libvt.Terminal(rows=3, cols=20) + term.feed( + b"\x1b[1;38;2;200;40;40mhi\x1b[0m " + b"\x1b]8;;https://example.com\x07ok\x1b]8;;\x07 " + b"\x1b]8;;javascript:alert(1)\x07bad\x1b]8;;\x07", + ) + snap = term.snapshot() + assert snap.format(OutputFormat.PLAIN) == "hi ok bad" + + html_out = snap.format(OutputFormat.HTML) + assert 'href="https://example.com"' in html_out + assert "javascript:" not in html_out + + vt_text = snap.format(OutputFormat.VT) + roundtrip = libvt.Terminal(rows=3, cols=20) + roundtrip.feed_str(vt_text) + assert roundtrip.text == snap.text + assert roundtrip[0, 0].style == snap[0, 0].style + + payload_dict = snap.to_dict() + assert payload_dict["rows"] == 3 + assert payload_dict["cols"] == 20 + + strict_term = libvt.Terminal(rows=2, cols=10, policy=Policy(strict=True)) + with pytest.raises(ProtocolError): + strict_term.feed(b"\x1b[999z") diff --git a/tests/test_ucd_and_grid.py b/tests/test_ucd_and_grid.py new file mode 100644 index 0000000..2d41f63 --- /dev/null +++ b/tests/test_ucd_and_grid.py @@ -0,0 +1,209 @@ +"""Unicode 17 clustering, cell-grid invariants, RLE scrollback, and fuzz tests.""" + +from __future__ import annotations + +import random +import time + +import libvt +from libvt._ucd import WidthRole +from libvt.modes import Mode + + +def test_unicode_width_flags_zwj_incb_and_variation_selectors() -> None: + """Flags, ZWJ emoji, Indic conjuncts, and VS15/VS16 obey ``?2027`` width rules.""" + term = libvt.Terminal(rows=4, cols=10) + # Two adjacent Regional Indicator flag pairs occupy 2 + 2 = 4 columns. + term.feed("🇯🇵🇺🇸!".encode()) + assert term.cursor.col == 5 + assert term[0, 0].text == "🇯🇵" + assert term[0, 0].width == 2 + assert term[0, 2].text == "🇺🇸" + assert term[0, 2].width == 2 + assert term[0, 4].text == "!" + + # Streaming 1-byte chunks of ZWJ emoji and Indic conjuncts. + term.reset() + for b in "🧑‍🌾क्षA".encode(): + term.feed(bytes([b])) + assert term[0, 0].text == "🧑‍🌾" + assert term[0, 0].width == 2 + assert term[0, 2].text == "क्ष" + assert term[0, 3].text == "A" + + # VS16 widening at right margin (col == cols - 1) wraps cleanly with SPACER_HEAD. + narrow_term = libvt.Terminal(rows=3, cols=4) + narrow_term.feed("abc❤️".encode()) + assert narrow_term[0].text == "abc" + assert narrow_term[0].wrapped is True + assert narrow_term[1, 0].text == "❤️" + assert narrow_term[1, 0].width == 2 + assert narrow_term.cursor.row == 1 + assert narrow_term.cursor.col == 2 + + # Disabling ?2027 leaves narrow base + VS16 at width 1. + legacy = libvt.Terminal(rows=2, cols=6) + legacy.feed(b"\x1b[?2027l" + "❤\ufe0fX".encode()) + assert legacy[0, 0].width == 1 + assert legacy[0, 1].text == "X" + + +def test_combining_mark_cap_and_cluster_anchor_invalidation() -> None: + """Combining floods stay O(1) capped and cursor moves clear cluster anchors.""" + term = libvt.Terminal(rows=4, cols=10) + t0 = time.perf_counter() + term.feed(("a" + ("\u0301" * 5_000)).encode("utf-8")) + elapsed = time.perf_counter() - t0 + assert elapsed < 0.25 + assert len(term[0, 0].text) == term.limits.max_grapheme_codepoints + + # Moving cursor before sending a combining mark must NOT mutate the earlier cell. + term.reset() + term.feed(b"ab") + term.feed(b"\x1b[1;1H" + "\u0301".encode()) + assert term[0, 0].text == "a" + assert term[0, 1].text == "b" + + +def test_row_clear_range_ich_dch_wide_healing_and_frozen_rle() -> None: + """Explicit spaces survive ``EL 0``, ``ICH``/``DCH`` heal pairs, and RLE works.""" + term = libvt.Terminal(rows=3, cols=6, scrollback=20) + term.feed(b" \x1b[K") + assert term.screen._rows[0].used == 3 + + # ICH splitting wide cell at col=1 heals col=0 and clears wide head pushed to col=5. + term.reset() + term.feed("日本語".encode()) + term.feed(b"\x1b[1;2H\x1b[1@") + row0 = term.screen._rows[0] + for col in range(6): + role = ( + WidthRole((row0.attrs[col] >> 60) & 0b11) + if row0.attrs is not None + else WidthRole.NARROW + ) + if role == WidthRole.WIDE: + assert col + 1 < 6 + assert row0.attrs is not None + next_role = WidthRole((row0.attrs[col + 1] >> 60) & 0b11) + assert next_role == WidthRole.SPACER_TAIL + if role == WidthRole.SPACER_TAIL: + assert col > 0 + assert row0.attrs is not None + prev_role = WidthRole((row0.attrs[col - 1] >> 60) & 0b11) + assert prev_role == WidthRole.WIDE + + # DCH splitting wide pairs at col=1 heals col=0. + term.reset() + term.feed("日本語".encode()) + term.feed(b"\x1b[1;2H\x1b[2P") + row0 = term.screen._rows[0] + for col in range(6): + role = ( + WidthRole((row0.attrs[col] >> 60) & 0b11) + if row0.attrs is not None + else WidthRole.NARROW + ) + if role == WidthRole.WIDE: + assert row0.attrs is not None + assert ( + WidthRole((row0.attrs[col + 1] >> 60) & 0b11) == WidthRole.SPACER_TAIL + ) + if role == WidthRole.SPACER_TAIL: + assert row0.attrs is not None + assert WidthRole((row0.attrs[col - 1] >> 60) & 0b11) == WidthRole.WIDE + + # Scroll styled + wide lines into FrozenRow RLE history and inspect runs/cells. + term.reset() + for idx in range(8): + term.feed(f"\x1b[38;2;10;20;{idx * 20}m日{idx}\r\n".encode()) + assert len(term.history) >= 5 + hist_row = term.history[0] + assert hist_row.text == "日0" + assert hist_row[0].text == "日" + assert hist_row[0].width == 2 + assert len(hist_row.runs) >= 1 + + +def _assert_grid_invariants(term: libvt.Terminal) -> None: + """Assert cursor bounds and wide-cell head/tail pairing across active rows.""" + scr = term.screen + assert 0 <= scr.cursor.row < scr.rows + assert 0 <= scr.cursor.col < scr.cols + for r_idx, raw_row in enumerate(scr._rows): + assert len(raw_row.chars) == scr.cols + assert 0 <= raw_row.used <= scr.cols + if raw_row.attrs is None: + continue + for c_idx in range(scr.cols): + role = WidthRole((raw_row.attrs[c_idx] >> 60) & 0b11) + if role == WidthRole.WIDE: + assert c_idx + 1 < scr.cols, f"orphan WIDE at ({r_idx}, {c_idx})" + tail_role = WidthRole((raw_row.attrs[c_idx + 1] >> 60) & 0b11) + assert tail_role == WidthRole.SPACER_TAIL + elif role == WidthRole.SPACER_TAIL: + assert c_idx > 0, f"orphan SPACER_TAIL at ({r_idx}, 0)" + head_role = WidthRole((raw_row.attrs[c_idx - 1] >> 60) & 0b11) + assert head_role == WidthRole.WIDE + + +def test_randomized_invariants_400_trials() -> None: + """400-trial seeded fuzzing preserves grid, wide-spacer, and cursor invariants.""" + rng = random.Random(20261121) + tokens: tuple[bytes, ...] = ( + b"abc", + "日本".encode(), + "🧑‍🌾".encode(), + "🇯🇵".encode(), + "❤\ufe0f".encode(), + "a\u0301".encode(), + b"\r", + b"\n", + b"\x08", + b"\t", + b"\x1b[A", + b"\x1b[B", + b"\x1b[C", + b"\x1b[D", + b"\x1b[Z", + b"\x1b[I", + b"\x1b[2@", + b"\x1b[2P", + b"\x1b[2X", + b"\x1b[K", + b"\x1b[1K", + b"\x1b[2K", + b"\x1b[J", + b"\x1b[L", + b"\x1b[M", + b"\x1b[2;5r", + b"\x1b[r", + b"\x1b[?69h\x1b[2;7s", + b"\x1b[?69l", + b"\x1b(0lqqqk\x1b(B", + b"\x1b[38;2;12;34;56;4:3m", + b"\x1b[0m", + b"\x1b[?1049h", + b"\x1b[?1049l", + b"\x1b[?2026h", + b"\x1b[?2026l", + ) + + for trial in range(400): + rows = rng.choice((4, 6, 8)) + cols = rng.choice((6, 8, 12)) + term = libvt.Terminal(rows=rows, cols=cols, scrollback=50) + stream = b"".join(rng.choice(tokens) for _ in range(32)) + idx = 0 + while idx < len(stream): + step = rng.randint(1, 9) + term.feed(stream[idx : idx + step]) + idx += step + _assert_grid_invariants(term) + if trial % 5 == 0: + term.resize(rows=rng.choice((3, 6, 9)), cols=rng.choice((5, 8, 14))) + _assert_grid_invariants(term) + if term.modes.is_set(Mode.ALT_SCREEN): + term.feed(b"\x1b[?1049l") + snap = term.snapshot() + assert snap.rows == term.rows From c2f36db4d0b592fd2879107eea8c52f50487bc3e Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 21 Nov 2026 15:26:06 -0600 Subject: [PATCH 03/29] Docs(feat[site]): Add API reference and guides why: Callers need executable documentation covering the sans-I/O terminal API, two-tier RLE grid, synchronized-output stepping, Rex OSC 7501 status tracking, mode-aware input encoding, and public modules. what: - Expand README.md, docs/index.md, and docs/quickstart.md with doctested usage examples - Add topic guides for architecture, ?2026 sync/asyncio, protocols/input, and pyte migration - Add Sphinx API reference pages across all public libvt modules - Update AGENTS.md module map and record 0.1.x deliverables in CHANGES --- AGENTS.md | 38 +++++++++------- CHANGES | 72 ++++++++++++++++++++++++++++++ README.md | 64 ++++++++++++++++++++++++-- docs/api/aio.md | 6 +++ docs/api/codec.md | 6 +++ docs/api/config.md | 6 +++ docs/api/events.md | 6 +++ docs/api/exc.md | 6 +++ docs/api/index.md | 57 +++++++++++++++++++++-- docs/api/input.md | 6 +++ docs/api/libvt.md | 1 + docs/api/modes.md | 6 +++ docs/api/parser.md | 6 +++ docs/api/screen.md | 6 +++ docs/api/status.md | 6 +++ docs/api/style.md | 6 +++ docs/api/terminal.md | 6 +++ docs/api/testing.md | 6 +++ docs/index.md | 22 +++++---- docs/quickstart.md | 57 ++++++++++++++++++++--- docs/topics/architecture.md | 61 +++++++++++++++++++++++++ docs/topics/index.md | 43 +++++++++++++++++- docs/topics/migrating-from-pyte.md | 46 +++++++++++++++++++ docs/topics/protocols-and-input.md | 58 ++++++++++++++++++++++++ docs/topics/sync-and-asyncio.md | 58 ++++++++++++++++++++++++ src/libvt/input.py | 2 +- 26 files changed, 614 insertions(+), 43 deletions(-) create mode 100644 docs/api/aio.md create mode 100644 docs/api/codec.md create mode 100644 docs/api/config.md create mode 100644 docs/api/events.md create mode 100644 docs/api/exc.md create mode 100644 docs/api/input.md create mode 100644 docs/api/modes.md create mode 100644 docs/api/parser.md create mode 100644 docs/api/screen.md create mode 100644 docs/api/status.md create mode 100644 docs/api/style.md create mode 100644 docs/api/terminal.md create mode 100644 docs/api/testing.md create mode 100644 docs/topics/architecture.md create mode 100644 docs/topics/migrating-from-pyte.md create mode 100644 docs/topics/protocols-and-input.md create mode 100644 docs/topics/sync-and-asyncio.md diff --git a/AGENTS.md b/AGENTS.md index 01785e5..f7f60bf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,11 +1,13 @@ # AGENTS.md libvt is a pure-Python, zero-dependency, typed virtual terminal emulator -and streaming VT parser (`Parser` → `Effects` → `Terminal` / `Screen` / -`Snapshot`). It ships an `asyncio` stream adapter (`libvt.aio`), a -namespace-safe pytest plugin (`libvt.pytest_plugin`), and visual boxed -screen assertions (`libvt.testing`), serving [libtmux](https://github.com/tmux-python/libtmux) -and general Python terminal testing without LGPL copyleft obligations. +and streaming VT parser (`Parser` → `Terminal` / `Screen` / `Snapshot` + +`Event`s). It ships a transport-only `asyncio` stream and POSIX PTY +adapter (`libvt.aio`), a namespace-safe pytest plugin +(`libvt.pytest_plugin`), mode-aware input encoders (`libvt.input`), and +visual boxed screen assertions (`libvt.testing`), serving +[libtmux](https://github.com/tmux-python/libtmux) and general Python +terminal testing without LGPL copyleft obligations. Follow the conventions already in the tree, and keep a change scoped to what was asked for. @@ -14,13 +16,14 @@ what was asked for. | Path | What it is | | ---- | ---------- | -| `src/libvt/parser.py`, `modes.py`, `style.py` | VT500 byte parser, CSI subparameters, modes, and SGR styles | -| `src/libvt/_grid.py`, `screen.py`, `terminal.py` | Packed row storage, `Screen` / `ScreenSet`, `Terminal`, and `Snapshot` | -| `src/libvt/aio.py` | Transport-only `asyncio` stream wrapper (`AsyncTerminalStream`) | -| `src/libvt/testing.py`, `pytest_plugin.py` | Visual boxed screen assertions and `vt_*` pytest fixtures | -| `tests/` | Unit, property, and fixture tests, one file per module under test | -| `docs/` | Sphinx/MyST site: `topics/` (concepts), `api/` (autodoc), `project/` (contributing, releasing, ADRs) | -| `scripts/` | Cross-commit and in-process VT throughput benchmark harnesses | +| `src/libvt/parser.py`, `modes.py`, `style.py`, `config.py` | VT500 byte parser, CSI subparameters, modes, SGR styles, and `Profile` / `Policy` / `Limits` | +| `src/libvt/_ucd.py`, `_grid.py`, `screen.py`, `terminal.py` | Unicode 17 width/clustering tables, packed viewport & RLE scrollback rows, `Screen` / `ScreenSet`, `Terminal`, `Snapshot`, and `Formatter` | +| `src/libvt/status.py`, `events.py`, `input.py`, `codec.py` | Rex `OSC 7501` program status store, closed `Event` union, mode-aware input encoders, and cold-path VT sequence explainer | +| `src/libvt/aio.py`, `__main__.py` | `AsyncTerminalStream`, POSIX `open_pty()`, and `python -m libvt` CLI (`explain`, `render`, `strip`) | +| `src/libvt/testing.py`, `pytest_plugin.py`, `exc.py` | Boxed `assert_screen`, `FlightRecorder` diagnostics, `vt_*` pytest fixtures, and exceptions | +| `tests/` | Unit, property fuzz, PTY, CLI, and fixture tests | +| `docs/` | Sphinx/MyST site: `topics/` (concepts), `api/` (autodoc), `project/` (contributing, releasing, ADRs `0001`–`0010`) | +| `scripts/` | Unicode table generator (`generate_ucd.py`) and VT throughput benchmarks (`bench_vt.py`, `benchmark.py`) | | `README.md` | Doctested quickstart — every `>>> ` block is a real test | | `CHANGES` | The changelog, rendered as a docs page | | `MIGRATION` | Deprecation and migration notes | @@ -51,14 +54,15 @@ be stated twice, the file listed above is the one that governs. - A passing gate is evidence only once it has been shown capable of failing. Pair a new test with a deliberate break that proves it bites. - Maintain strict clean-room MIT provenance: derive state transitions - and test vectors from public standards (ECMA-48, DEC STD 070, Paul Flo - Williams' VT500 state diagram) and permissive (`MIT`, `ISC`, - `Apache-2.0`, `BSD`) references — never copy or translate from `LGPL` - or `GPL` terminal implementations (`pyte`, `vte`/GTK, `asciinema`). + and test vectors from public standards (ECMA-48, ITU T.416, Unicode + UAX #11 / #29, Paul Flo Williams' VT500 state diagram) and permissive + (`MIT`, `ISC`, `Apache-2.0`, `BSD`) references — never copy or + translate from `LGPL` or `GPL` terminal implementations (`pyte`, + `vte`/GTK, `asciinema`). Python >= 3.12 is the compatibility floor, and runtime dependencies stay empty (`dependencies = []`). Importing `libvt` performs no I/O and does -not load `asyncio` or `pytest`. +not load `asyncio`, `pty`, or `pytest`. ## References diff --git a/CHANGES b/CHANGES index 302fb2b..fb38220 100644 --- a/CHANGES +++ b/CHANGES @@ -5,3 +5,75 @@ _Notes on the upcoming release will go here._ + +### What's new + +#### 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 +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 +{func}`~libvt.terminal.render`, {func}`~libvt.terminal.strip`, and +{func}`~libvt.codec.explain` helpers handle common rendering, stripping, +and sequence disassembly tasks, backed by `python -m libvt` CLI +subcommands. + +{class}`~libvt.parser.Parser` decodes incremental UTF-8, colon-delimited +ITU T.416 SGR subparameters (`4:3`, `38:2::R:G:B`, `58:5:idx`), `G0`–`G3` +character-set designations (`ESC ( 0` DEC Special Graphics, `SO`/`SI`, +`SS2`/`SS3`), `CBT`/`CHT`, `DECSCA`/`DECSED`/`DECSEL`, `CSI 22 J`, and +`DCS tmux;` passthrough unwrapping while isolating UTF-8 `0x9C` bytes +from 8-bit `C1` string terminators. Bundled Unicode 17.0.0 two-stage +tables drive East Asian width and DEC `?2027` grapheme clustering across +ZWJ emoji, Regional Indicator flag pairs, Indic conjuncts, and `VS15` / +`VS16` variation selectors. See {doc}`topics/architecture` for details. + +#### Synchronized output stepping, Rex `OSC 7501`, and host queries (#2) + +{meth}`~libvt.terminal.Terminal.committed`, +{meth}`~libvt.terminal.Terminal.feed_until`, and +{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 +escape sequences, and span-coalesced HTML with URI scheme allowlisting. + +{class}`~libvt.status.ProgramStatusStore` and +{class}`~libvt.status.ProgramStatus` implement the Rex `OSC 7501` +Program Status specification, including hierarchical task identifiers, +ancestor `app` inheritance, urgency ranking, base64 `title`/`msg` +validation, consumer-gated `OSC 7501 ; ?` capability replies, `OSC 9;4` +fallback, and lifecycle pruning alongside `OSC 133` prompt zones, +`OSC 7` working directory updates, `OSC 52` clipboard writes, `DA1`/`DA2`, +`DSR`, `DECRQM`, `DECRQSS`, `XTVERSION`, `XTGETTCAP`, and `?2031`/`?996n` +color-scheme queries. Configuration splits cleanly across +{class}`~libvt.config.Profile`, {class}`~libvt.config.Policy`, and +{class}`~libvt.config.Limits`. See {doc}`topics/protocols-and-input` for +details. + +#### Mode-aware input encoding, `asyncio` PTY bridge, and pytest plugin (#2) + +{class}`~libvt.input.KeyEvent`, {class}`~libvt.input.MouseEvent`, +{class}`~libvt.input.FocusEvent`, and {class}`~libvt.input.PasteEvent` +encode outbound PTY bytes against active terminal modes, including +per-screen Kitty `CSI u` keyboard stacks (`>u`, `= 3.12 (CPython and PyPy) @@ -31,13 +51,49 @@ $ pip install libvt ## Quickstart -`libvt` performs no network or filesystem I/O and leaves `asyncio` -unloaded on `import libvt`: +One-liner helpers render, strip, or disassemble VT byte streams without +managing an emulator instance: ```python >>> import libvt ->>> libvt.__title__ -'libvt' +>>> libvt.render(b"\x1b[1;32mready\x1b[0m\r\nitem 1", rows=4, cols=20) +'ready\nitem 1' +>>> libvt.strip(b"\x1b[31merror:\x1b[0m failed") +'error: failed' +``` + +Stateful emulation tracks zero-based `(row, col)` cells, SGR colon +subparameters, query replies, and `OSC 7501` program status: + +```python +>>> term = libvt.Terminal(rows=4, cols=20) +>>> term.feed(b"\x1b[1;4:3;38:2::40:180:160mstatus\x1b[0m\x1b[6n") +>>> term[0, 0].style.underline + +>>> term.drain_replies() +b'\x1b[1;7R' +>>> term.feed(b"\x1b]7501;state=working:id=build:progress=60\x1b\\") +>>> term.program_status.value, term.program_status.progress +('working', 60) +``` + +Boxed visual assertions verify CJK wide-character alignment and cursor +coordinates in tests: + +```python +>>> from libvt.testing import assert_screen +>>> t = libvt.Terminal(rows=2, cols=8) +>>> t.feed("日本ok\r\ndone".encode()) +>>> assert_screen( +... t, +... """ +... ┌────────┐ +... │日本ok │ +... │done │ +... └────────┘ +... """, +... cursor=(1, 4), +... ) ``` ## License diff --git a/docs/api/aio.md b/docs/api/aio.md new file mode 100644 index 0000000..d3951a4 --- /dev/null +++ b/docs/api/aio.md @@ -0,0 +1,6 @@ +# `libvt.aio` + +```{eval-rst} +.. automodule:: libvt.aio + :members: +``` diff --git a/docs/api/codec.md b/docs/api/codec.md new file mode 100644 index 0000000..533e74f --- /dev/null +++ b/docs/api/codec.md @@ -0,0 +1,6 @@ +# `libvt.codec` + +```{eval-rst} +.. automodule:: libvt.codec + :members: +``` diff --git a/docs/api/config.md b/docs/api/config.md new file mode 100644 index 0000000..4a9fa7c --- /dev/null +++ b/docs/api/config.md @@ -0,0 +1,6 @@ +# `libvt.config` + +```{eval-rst} +.. automodule:: libvt.config + :members: +``` diff --git a/docs/api/events.md b/docs/api/events.md new file mode 100644 index 0000000..e8b71f2 --- /dev/null +++ b/docs/api/events.md @@ -0,0 +1,6 @@ +# `libvt.events` + +```{eval-rst} +.. automodule:: libvt.events + :members: +``` diff --git a/docs/api/exc.md b/docs/api/exc.md new file mode 100644 index 0000000..c028e03 --- /dev/null +++ b/docs/api/exc.md @@ -0,0 +1,6 @@ +# `libvt.exc` + +```{eval-rst} +.. automodule:: libvt.exc + :members: +``` diff --git a/docs/api/index.md b/docs/api/index.md index 1de76f2..4cf7b57 100644 --- a/docs/api/index.md +++ b/docs/api/index.md @@ -12,13 +12,49 @@ Public modules and types shipped by `libvt`. :::{grid-item-card} `libvt` :link: libvt :link-type: doc -Top-level package exports and metadata. +Top-level re-exports, progressive-disclosure helpers, and package metadata. ::: -:::{grid-item-card} `libvt.pytest_plugin` -:link: pytest_plugin +:::{grid-item-card} `libvt.terminal` +:link: terminal :link-type: doc -Pytest plugin entry point and fixtures. +`Terminal`, `Snapshot`, `Formatter`, `FlightRecorder`, `render`, and `strip`. +::: + +:::{grid-item-card} `libvt.screen` +:link: screen +:link-type: doc +`Screen`, `ScreenSet`, `Cell`, `RowView`, `RowRun`, `RegionView`, and `Cursor`. +::: + +:::{grid-item-card} `libvt.parser` +:link: parser +:link-type: doc +Streaming VT500 `Parser`, `CsiParams`, `Action` records, and `parse_sgr`. +::: + +:::{grid-item-card} `libvt.style` & `libvt.modes` +:link: style +:link-type: doc +`Style`, `AnsiColor`, `IndexedColor`, `RgbColor`, `Hyperlink`, and DEC/ANSI `Mode`s. +::: + +:::{grid-item-card} `libvt.config`, `events`, & `status` +:link: config +:link-type: doc +`Profile`, `Policy`, `Limits`, closed `Event` union, and `OSC 7501` `ProgramStatus`. +::: + +:::{grid-item-card} `libvt.input` & `libvt.codec` +:link: input +:link-type: doc +Mode-aware `KeyEvent`, `MouseEvent`, `PasteEvent`, and VT sequence `explain`. +::: + +:::{grid-item-card} `libvt.aio`, `testing`, & `pytest_plugin` +:link: aio +:link-type: doc +`AsyncTerminalStream`, POSIX `open_pty`, `assert_screen`, and `vt_*` fixtures. ::: :::: @@ -53,5 +89,18 @@ Active deprecations and migration guidance. :maxdepth: 1 libvt +terminal +screen +parser +style +modes +config +events +status +input +codec +aio +testing pytest_plugin +exc ``` diff --git a/docs/api/input.md b/docs/api/input.md new file mode 100644 index 0000000..d913a23 --- /dev/null +++ b/docs/api/input.md @@ -0,0 +1,6 @@ +# `libvt.input` + +```{eval-rst} +.. automodule:: libvt.input + :members: +``` diff --git a/docs/api/libvt.md b/docs/api/libvt.md index 6cbd611..f7b2d28 100644 --- a/docs/api/libvt.md +++ b/docs/api/libvt.md @@ -3,4 +3,5 @@ ```{eval-rst} .. automodule:: libvt :members: + :no-index: ``` diff --git a/docs/api/modes.md b/docs/api/modes.md new file mode 100644 index 0000000..22a8570 --- /dev/null +++ b/docs/api/modes.md @@ -0,0 +1,6 @@ +# `libvt.modes` + +```{eval-rst} +.. automodule:: libvt.modes + :members: +``` diff --git a/docs/api/parser.md b/docs/api/parser.md new file mode 100644 index 0000000..4fa6010 --- /dev/null +++ b/docs/api/parser.md @@ -0,0 +1,6 @@ +# `libvt.parser` + +```{eval-rst} +.. automodule:: libvt.parser + :members: +``` diff --git a/docs/api/screen.md b/docs/api/screen.md new file mode 100644 index 0000000..e0c6234 --- /dev/null +++ b/docs/api/screen.md @@ -0,0 +1,6 @@ +# `libvt.screen` + +```{eval-rst} +.. automodule:: libvt.screen + :members: +``` diff --git a/docs/api/status.md b/docs/api/status.md new file mode 100644 index 0000000..7b76aa0 --- /dev/null +++ b/docs/api/status.md @@ -0,0 +1,6 @@ +# `libvt.status` + +```{eval-rst} +.. automodule:: libvt.status + :members: +``` diff --git a/docs/api/style.md b/docs/api/style.md new file mode 100644 index 0000000..af9e6c1 --- /dev/null +++ b/docs/api/style.md @@ -0,0 +1,6 @@ +# `libvt.style` + +```{eval-rst} +.. automodule:: libvt.style + :members: +``` diff --git a/docs/api/terminal.md b/docs/api/terminal.md new file mode 100644 index 0000000..0338642 --- /dev/null +++ b/docs/api/terminal.md @@ -0,0 +1,6 @@ +# `libvt.terminal` + +```{eval-rst} +.. automodule:: libvt.terminal + :members: +``` diff --git a/docs/api/testing.md b/docs/api/testing.md new file mode 100644 index 0000000..178afc5 --- /dev/null +++ b/docs/api/testing.md @@ -0,0 +1,6 @@ +# `libvt.testing` + +```{eval-rst} +.. automodule:: libvt.testing + :members: +``` diff --git a/docs/index.md b/docs/index.md index 2be2df3..81f38e7 100644 --- a/docs/index.md +++ b/docs/index.md @@ -5,31 +5,31 @@ Pure-Python, zero-dependency, typed virtual terminal emulator and streaming VT parser (`py3-none-any.whl` — no C shared library required). -::::{grid} 1 1 3 3 +::::{grid} 1 1 2 2 :gutter: 2 2 3 3 :::{grid-item-card} Quickstart :link: quickstart :link-type: doc -Install `libvt` and inspect package metadata. +Render VT streams, inspect cells, and write boxed screen assertions. ::: :::{grid-item-card} Topics :link: topics/index :link-type: doc -Parser state machine, screen storage, and sans-I/O design. +Sans-I/O layering, RLE scrollback, `?2026` stepping, `OSC 7501`, and input encoding. ::: :::{grid-item-card} API Reference :link: api/index :link-type: doc -Public modules, types, and pytest fixtures. +Public modules, dataclasses, protocols, and `vt_*` pytest fixtures. ::: -:::{grid-item-card} Project +:::{grid-item-card} Project & ADRs :link: project/index :link-type: doc -Contributing, code style, releases, and architecture decisions. +Contributing, code style, releases, and Architecture Decision Records `0001`–`0010`. ::: :::: @@ -50,8 +50,14 @@ $ pip install libvt ```python >>> import libvt ->>> libvt.__title__ -'libvt' +>>> term = libvt.Terminal(rows=4, cols=20) +>>> term.feed(b"\x1b[1;31mhello\x1b[0m \xe6\x97\xa5\xe6\x9c\xac") +>>> term.text +'hello 日本' +>>> term[0, 0].style.fg + +>>> term.cursor.row, term.cursor.col +(0, 10) ``` ```{toctree} diff --git a/docs/quickstart.md b/docs/quickstart.md index 3ed1f7d..720399d 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -17,15 +17,58 @@ $ uv add libvt $ pip install libvt ``` -## Importing `libvt` +## One-liner helpers -Importing `libvt` performs no I/O and keeps `asyncio` and `pytest` -unloaded until explicitly imported: +{func}`libvt.render`, {func}`libvt.strip`, and {func}`libvt.explain` +cover one-shot rendering, control-sequence stripping, and byte-stream +disassembly: ```python >>> import libvt ->>> libvt.__package_name__ -'libvt' ->>> libvt.__license__ -'MIT' +>>> libvt.render(b"\x1b[32mok\x1b[0m\r\nnext", rows=3, cols=10) +'ok\nnext' +>>> libvt.strip(b"\x1b[1mbold\x1b[0m plain") +'bold plain' +>>> [s.mnemonic for s in libvt.explain(b"\x1b[1;31mhi\x1b[0m")] +['SGR', 'TEXT', 'SGR'] +``` + +## Stateful emulation + +{class}`libvt.Terminal` uses keyword-only `(rows, cols)` dimensions and +zero-based `(row, col)` indexing across cells, rows, and 2D slices: + +```python +>>> term = libvt.Terminal(rows=4, cols=20) +>>> term.feed(b"\x1b(0lqqqk\x1b(B\r\n\x1b[4:3mwave\x1b[0m") +>>> term.lines[:2] +('┌───┐', 'wave') +>>> term[1, 0].style.underline + +``` + +## Mode-aware input and paste safety + +{meth}`libvt.Terminal.encode` serializes keys, mouse events, focus +changes, and bracketed pastes according to active terminal modes: + +```python +>>> term = libvt.Terminal(rows=4, cols=20) +>>> term.feed(b"\x1b[>1u\x1b[?2004h") +>>> term.encode(libvt.KeyEvent.parse("ctrl+k")) +b'\x1b[107;5u' +>>> term.encode(libvt.PasteEvent("line 1\nline 2")) +b'\x1b[200~line 1\nline 2\x1b[201~' +``` + +## Pytest assertions + +{func}`libvt.testing.assert_screen` compares visible text and optional +cursor coordinates, accepting either plain lines or boxed diagrams: + +```python +>>> from libvt.testing import assert_screen +>>> term = libvt.Terminal(rows=2, cols=8) +>>> term.feed("日本!\r\nok".encode()) +>>> assert_screen(term, "日本!\nok", cursor=(1, 2)) ``` diff --git a/docs/topics/architecture.md b/docs/topics/architecture.md new file mode 100644 index 0000000..9e7ac49 --- /dev/null +++ b/docs/topics/architecture.md @@ -0,0 +1,61 @@ +(topics-architecture)= + +# Architecture & Grid Storage + +`libvt` separates terminal emulation into four acyclic layers so callers +import only the machinery they need: + +1. **Streaming parser** ({mod}`libvt.parser`): 14-state VT500 byte + machine with colon-subparameter `CSI` bitmasks, incremental UTF-8 + decoding, 7-bit string termination, and `DCS tmux;` `ESC ESC` + collapsing. +2. **Grid and screen model** ({mod}`libvt.screen`): Zero-based + `(row, col)` viewport with lazy 64-bit `array('Q')` attribute words, + wide-spacer boundary healing, run-length-encoded scrollback rows, and + primary-screen soft-wrap resize reflow. +3. **Sans-I/O terminal facade** ({mod}`libvt.terminal`, + {mod}`libvt.status`, {mod}`libvt.input`, {mod}`libvt.codec`): + Coordinates dual primary/alternate screens, `Profile` / `Policy` / + `Limits`, `OSC 7501` status records, outbound replies, and input + encoding with zero system calls. +4. **Transport and test edges** ({mod}`libvt.aio`, + {mod}`libvt.testing`, {mod}`libvt.pytest_plugin`): Optional + `asyncio` stream/PTY runners and pytest diagnostics. + +## Configuration split + +{class}`~libvt.config.Profile`, {class}`~libvt.config.Policy`, and +{class}`~libvt.config.Limits` separate compatibility identity from +security gates and resource caps: + +```python +>>> import libvt +>>> term = libvt.Terminal( +... rows=3, +... cols=5, +... profile=libvt.TMUX_PROFILE, +... policy=libvt.Policy(strict=False), +... limits=libvt.Limits(max_osc_bytes=8192), +... ) +>>> term.feed(b"12345\x1b[1DX") +>>> term[0].text +'1234X' +``` + +## Two-tier viewport and RLE scrollback + +Active viewport rows keep plain ASCII lines at a single uniform 64-bit +word and promote to `array('Q')` only when styled or wide cells appear. +Evicted scrollback lines freeze into immutable run-length-encoded rows +exposed through {attr}`~libvt.terminal.Terminal.history`: + +```python +>>> term = libvt.Terminal(rows=2, cols=12, scrollback=10) +>>> term.feed(b"\x1b[32mline-0\x1b[0m\r\nline-1\r\nline-2") +>>> [r.text for r in term.history] +['line-0'] +>>> term.history[0].runs[0].style.fg + +``` + +For rationale and memory measurements, see {doc}`../project/adr/index`. diff --git a/docs/topics/index.md b/docs/topics/index.md index bd9dc54..639462b 100644 --- a/docs/topics/index.md +++ b/docs/topics/index.md @@ -2,5 +2,44 @@ # Topics -Conceptual guides for `libvt`'s VT parser, screen state, and testing -utilities. +Conceptual guides covering `libvt`'s sans-I/O architecture, synchronize +stepping, terminal protocols, and migration patterns. + +::::{grid} 1 1 2 2 +:gutter: 2 2 3 3 + +:::{grid-item-card} Architecture & Grid Storage +:link: architecture +:link-type: doc +Sans-I/O layering, lazy 64-bit viewport rows, RLE scrollback, and Unicode 17 clustering. +::: + +:::{grid-item-card} Synchronized Output & `asyncio` +:link: sync-and-asyncio +:link-type: doc +DEC `?2026` copy-on-write holds, `feed_until`, `AsyncTerminalStream`, and `open_pty`. +::: + +:::{grid-item-card} Protocols & Input Encoding +:link: protocols-and-input +:link-type: doc +Rex `OSC 7501` Program Status, `OSC 133`, host queries, Kitty `CSI u`, and paste safety. +::: + +:::{grid-item-card} Migrating from `pyte` +:link: migrating-from-pyte +:link-type: doc +Translating screen setup, coordinates, alternate screens, and replies to `libvt`. +::: + +:::: + +```{toctree} +:hidden: +:maxdepth: 2 + +architecture +sync-and-asyncio +protocols-and-input +migrating-from-pyte +``` diff --git a/docs/topics/migrating-from-pyte.md b/docs/topics/migrating-from-pyte.md new file mode 100644 index 0000000..19dedb0 --- /dev/null +++ b/docs/topics/migrating-from-pyte.md @@ -0,0 +1,46 @@ +(topics-migrating-from-pyte)= + +# Migrating from `pyte` + +`libvt` provides an MIT-licensed, zero-dependency replacement for legacy +Python terminal emulators with native support for `?1049` alternate +screens, colon SGR subparameters, bidirectional query replies, and +Unicode 17 grapheme clustering. + +## Dimension order and coordinates + +`libvt` uses keyword-only `(rows, cols)` dimensions and zero-based +`(row, col)` indexing everywhere: + +```python +>>> import libvt +>>> term = libvt.Terminal(rows=24, cols=80) +>>> term.feed(b"\x1b[2;5Hhello") +>>> term.cursor.row, term.cursor.col +(1, 9) +>>> term[1, 4].text +'h' +``` + +## Single byte-stream entry point + +Instead of pairing a separate `ByteStream` with a `Screen` or +`HistoryScreen`, feed `bytes`, `bytearray`, or `memoryview` directly to +{meth}`libvt.Terminal.feed` (or UTF-8 strings via +{meth}`libvt.Terminal.feed_str`): + +```python +>>> term = libvt.Terminal(rows=4, cols=20, scrollback=500) +>>> term.feed(b"first\r\n\x1b[?1049hfullscreen\x1b[?1049l") +>>> term.text +'first' +``` + +## Bidirectional replies and side-effect events + +Terminal queries (`CSI 6 n`, `CSI c`, `DECRQM`, `DECRQSS`, `XTVERSION`, +`XTGETTCAP`, `OSC 10/11 ; ?`) accumulate in +{meth}`libvt.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`. diff --git a/docs/topics/protocols-and-input.md b/docs/topics/protocols-and-input.md new file mode 100644 index 0000000..d938466 --- /dev/null +++ b/docs/topics/protocols-and-input.md @@ -0,0 +1,58 @@ +(topics-protocols-and-input)= + +# Protocols & Input Encoding + +## Rex `OSC 7501` Program Status + +`libvt` implements the Rex `OSC 7501` Program Status grammar (`:`-joined +`key=value` pairs, hierarchical `/` task identifiers, ancestor `app` +inheritance, base64 `title` and `msg`, and `OSC 9;4` ConEmu progress +fallback): + +```python +>>> import base64, libvt +>>> term = libvt.Terminal(rows=4, cols=30, record_events=True) +>>> title_b64 = base64.b64encode(b"Running pytest").decode("ascii") +>>> term.feed( +... f"\x1b]7501;state=working:id=ci:app=pytest:progress=75:title={title_b64}\x1b\\".encode() +... ) +>>> term.feed(b"\x1b]7501;state=blocked:id=ci/approve:kind=permission\x1b\\") +>>> term.program_status.id, term.program_status.effective_app +('ci/approve', 'pytest') +``` + +`OSC 7501 ; ?` capability queries stay silent unless `on_event`, +`record_events=True`, or `Policy(allow_program_status_query=True)` +indicates an active status consumer. + +## Semantic prompts (`OSC 133`) and queries + +`OSC 133` prompt markers record monotonic `abs_row` indices across +scrollback eviction so stored prompt zones remain valid as output +scrolls: + +```python +>>> term = libvt.Terminal(rows=2, cols=20, scrollback=10) +>>> term.feed(b"\x1b]133;A\x07$ \x1b]133;B\x07ls\r\nfile.py\r\n\x1b]133;D;0\x07") +>>> [(z.kind.value, z.exit_code) for z in term.prompt_zones] +[('A', None), ('B', None), ('D', 0)] +``` + +## Outbound input encoding and paste safety + +{func}`~libvt.input.encode_input` and {meth}`~libvt.terminal.Terminal.encode` +consult `DECCKM`, mouse modes (`?9`, `?1000`, `?1002`, `?1003`, `?1006`, +`?1016`), focus reporting (`?1004`), bracketed paste (`?2004`), and the +active screen's Kitty `CSI u` keyboard stack: + +```python +>>> term = libvt.Terminal(rows=4, cols=20) +>>> term.feed(b"\x1b[?1h") +>>> term.encode(libvt.KeyEvent.parse("up")) +b'\x1bOA' +``` + +{func}`~libvt.input.encode_paste` fails closed with +{exc}`~libvt.exc.UnsafePasteError` whenever pasted text contains `ESC`, +8-bit `C1` bytes, `NUL`, `DEL`, or unbracketed newlines rather than +relying on single-pass substring replacement. diff --git a/docs/topics/sync-and-asyncio.md b/docs/topics/sync-and-asyncio.md new file mode 100644 index 0000000..7075964 --- /dev/null +++ b/docs/topics/sync-and-asyncio.md @@ -0,0 +1,58 @@ +(topics-sync-and-asyncio)= + +# Synchronized Output & `asyncio` + +Modern TUI applications wrap screen redraws in DEC private mode `?2026` +(`CSI ? 2026 h` … `CSI ? 2026 l`) so observers never inspect half-drawn +frames. + +## Copy-on-write `?2026` holds and `feed_until` + +While `term.synchronized` is `True`, {attr}`~libvt.terminal.Terminal.committed` +returns the pre-batch {class}`~libvt.terminal.Snapshot` while +{meth}`~libvt.terminal.Terminal.snapshot` reflects live in-progress +mutations: + +```python +>>> import libvt +>>> term = libvt.Terminal(rows=2, cols=16) +>>> term.feed(b"stable") +>>> term.feed(b"\x1b[?2026h\x1b[2J\x1b[Hredrawing") +>>> term.committed.text +'stable' +>>> term.snapshot().text +'redrawing' +>>> term.feed(b"\x1b[?2026l") +>>> term.committed.text +'redrawing' +``` + +{meth}`~libvt.terminal.Terminal.feed_until` steps through concatenated +captures and stops cleanly at `?2026l` (`StopOn.SYNC_END`), `OSC 133` +prompt boundaries, or `OSC 7501` status transitions: + +```python +>>> batch = b"\x1b[?2026h\x1b[Hf1\x1b[?2026l\x1b[?2026h\x1b[Hf2\x1b[?2026l" +>>> t = libvt.Terminal(rows=2, cols=8) +>>> step = t.feed_until(batch, stop=libvt.StopOn.SYNC_END) +>>> t.text, step.stopped_on +('f1', ) +``` + +If an application crashes mid-frame without closing `?2026l`, +{meth}`~libvt.terminal.Terminal.expire_synchronized_output` releases the +hold only when `sync_generation` still matches the stalled batch. + +## `AsyncTerminalStream` and `open_pty` + +{mod}`libvt.aio` wraps sans-I/O terminals for `asyncio` readers/writers +and POSIX pseudo-terminals without adding background threads to the core: + +- {class}`~libvt.aio.AsyncTerminalStream` pumps an + `asyncio.StreamReader`, flushes {meth}`~libvt.terminal.Terminal.drain_replies` + to an optional writer, and coalesces `wait_for(...)` wakeups across + `?2026` batches up to `sync_timeout`. +- {func}`~libvt.aio.open_pty` spawns a child process attached to + `pty.openpty()` with initial `TIOCSWINSZ` window dimensions, forwards + terminal query replies, and calls + {meth}`~libvt.terminal.Terminal.notify_process_exit` on teardown. diff --git a/src/libvt/input.py b/src/libvt/input.py index 387c38a..51d6f96 100644 --- a/src/libvt/input.py +++ b/src/libvt/input.py @@ -111,7 +111,7 @@ class KeyEvent: (``"enter"``, ``"tab"``, ``"escape"``, ``"backspace"``, ``"up"``, ``"down"``, ``"right"``, ``"left"``, ``"home"``, ``"end"``, ``"page_up"``, ``"page_down"``, ``"insert"``, ``"delete"``, - ``"f1"``..``"f12"``). + ``"f1"`` through ``"f12"``). modifiers : KeyMod Active modifier bitmask. action : KeyAction From 94ef6f1f81611cfd69bdad2783575f73d08b70dc Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 21 Nov 2026 17:07:46 -0600 Subject: [PATCH 04/29] Core(fix[vt]): Harden UCD 17, parser, and grid why: Align Unicode 17 clustering, string-escape framing, passthrough policy, cross-row wide healing, and OSC 7 host checks with standards. what: - Compile SHA-256-pinned Unicode 17.0.0 UCD and Emoji tables and verify all 766 GraphemeBreakTest vectors - Add ParserState.STRING_ESC, encoding="utf-8"|"latin-1", Passthrough event, and default-deny Policy.allow_passthrough - Heal cross-row SPACER_HEAD cells across horizontal and margin edits - Replace os.uname() in Terminal OSC 7 handling with Policy.osc7_hosts and Terminal.cwd_uri --- scripts/generate_ucd.py | 646 ++++++++++------ src/libvt/__init__.py | 2 + src/libvt/_ucd.py | 357 ++++++--- src/libvt/config.py | 19 +- src/libvt/events.py | 15 + src/libvt/parser.py | 299 ++++---- src/libvt/screen.py | 57 ++ src/libvt/terminal.py | 152 +++- tests/fixtures/GraphemeBreakTest-17.0.0.txt | 796 ++++++++++++++++++++ tests/test_parser.py | 64 +- tests/test_protocols_and_input.py | 63 +- tests/test_ucd_and_grid.py | 160 +++- 12 files changed, 2018 insertions(+), 612 deletions(-) create mode 100644 tests/fixtures/GraphemeBreakTest-17.0.0.txt diff --git a/scripts/generate_ucd.py b/scripts/generate_ucd.py index 2de3858..0ede2c6 100644 --- a/scripts/generate_ucd.py +++ b/scripts/generate_ucd.py @@ -1,100 +1,71 @@ -"""Generate the compact two-stage Unicode 17.0 width & UAX #29 table in libvt._ucd.""" +"""Compile SHA-256-pinned Unicode 17.0.0 UCD & Emoji tables into ``libvt._ucd``.""" from __future__ import annotations +import argparse import base64 +import hashlib import pathlib -import unicodedata +import urllib.request import zlib -PROP_NONE = 0 -PROP_CONTROL = 1 -PROP_EXTEND = 2 -PROP_ZWJ = 3 -PROP_REGIONAL_INDICATOR = 4 -PROP_SPACING_MARK = 5 -PROP_EXTENDED_PICTOGRAPHIC = 6 -PROP_INCB_CONSONANT = 7 -PROP_INCB_LINKER = 8 -PROP_VS15 = 9 -PROP_VS16 = 10 -PROP_EMOJI_MODIFIER = 11 - -EXT_PICT_BIT = 0x40 -BIDI_SPOOF_BIT = 0x80 - -# Unicode Indic_Conjunct_Break=Linker (Virama / Halant) codepoints across Indic scripts. -INCB_LINKERS: frozenset[int] = frozenset( - { - 0x094D, # Devanagari - 0x09CD, # Bengali - 0x0A4D, # Gurmukhi - 0x0ACD, # Gujarati - 0x0B4D, # Oriya - 0x0BCD, # Tamil - 0x0C4D, # Telugu - 0x0CCD, # Kannada - 0x0D4D, # Malayalam - 0x0DCA, # Sinhala - 0x1039, # Myanmar - 0x17D2, # Khmer - 0x1A60, # Tai Tham - 0x1B44, # Balinese - 0xA9C0, # Javanese - }, -) - -INCB_CONSONANT_RANGES: tuple[tuple[int, int], ...] = ( - (0x0915, 0x0939), - (0x0958, 0x095F), - (0x0978, 0x097F), - (0x0995, 0x09B9), - (0x09DC, 0x09DF), - (0x09F0, 0x09F1), - (0x0A15, 0x0A39), - (0x0A59, 0x0A5E), - (0x0A95, 0x0AB9), - (0x0B15, 0x0B39), - (0x0B5C, 0x0B5D), - (0x0B95, 0x0BB9), - (0x0C15, 0x0C39), - (0x0C58, 0x0C5A), - (0x0C95, 0x0CB9), - (0x0D15, 0x0D3A), - (0x0D9A, 0x0DC6), -) - -# Official Unicode Extended_Pictographic core blocks for UAX #29 GB11 ZWJ sequences. -EXT_PICT_RANGES: tuple[tuple[int, int], ...] = ( - (0x00A9, 0x00A9), - (0x00AE, 0x00AE), - (0x203C, 0x203C), - (0x2049, 0x2049), - (0x2122, 0x2122), - (0x2139, 0x2139), - (0x2194, 0x2199), - (0x21A9, 0x21AA), - (0x231A, 0x231B), - (0x2328, 0x2328), - (0x23CF, 0x23CF), - (0x23E9, 0x23F3), - (0x23F8, 0x23FA), - (0x24C2, 0x24C2), - (0x25AA, 0x25AB), - (0x25B6, 0x25B6), - (0x25C0, 0x25C0), - (0x25FB, 0x25FE), - (0x2600, 0x27BF), - (0x2934, 0x2935), - (0x2B05, 0x2B07), - (0x2B1B, 0x2B1C), - (0x2B50, 0x2B50), - (0x2B55, 0x2B55), - (0x3030, 0x3030), - (0x303D, 0x303D), - (0x3297, 0x3299), - (0x1F000, 0x1FAFF), -) +UNICODE_VERSION = "17.0.0" +_BASE_URL = f"https://www.unicode.org/Public/{UNICODE_VERSION}" + +PINNED_UCD_FILES: dict[str, tuple[str, str]] = { + "DerivedCoreProperties.txt": ( + f"{_BASE_URL}/ucd/DerivedCoreProperties.txt", + "24c7fed1195c482faaefd5c1e7eb821c5ee1fb6de07ecdbaa64b56a99da22c08", + ), + "DerivedGeneralCategory.txt": ( + f"{_BASE_URL}/ucd/extracted/DerivedGeneralCategory.txt", + "d62e5bab70ca74f099343f71224fa051cb1fdd61a1ab45c0488c44cfc0b6102e", + ), + "EastAsianWidth.txt": ( + f"{_BASE_URL}/ucd/EastAsianWidth.txt", + "ea7ce50f3444a050333448dffef1cadd9325af55cbb764b4a2280faf52170a33", + ), + "GraphemeBreakProperty.txt": ( + f"{_BASE_URL}/ucd/auxiliary/GraphemeBreakProperty.txt", + "d6b51d1d2ae5c33b451b7ed994b48f1f4dc62b2272a5831e7fd418514a6bae89", + ), + "GraphemeBreakTest.txt": ( + f"{_BASE_URL}/ucd/auxiliary/GraphemeBreakTest.txt", + "e2d134d2c52919bace503ebb6a551c1855fe1a1faec18478c78fff254a1793ec", + ), + "emoji-data.txt": ( + f"{_BASE_URL}/ucd/emoji/emoji-data.txt", + "2cb2bb9455cda83e8481541ecf5b6dfda66a3bb89efa3fa7c5297eccf607b72b", + ), + "emoji-variation-sequences.txt": ( + f"{_BASE_URL}/ucd/emoji/emoji-variation-sequences.txt", + "bb3d09ef03f206012c7532dd52dc0a21c9efddba0135ea4cf0d9201b8b9bba7e", + ), +} + +GCB_IDS: dict[str, int] = { + "Other": 0, + "CR": 1, + "LF": 2, + "Control": 3, + "Extend": 4, + "ZWJ": 5, + "Regional_Indicator": 6, + "Prepend": 7, + "SpacingMark": 8, + "L": 9, + "V": 10, + "T": 11, + "LV": 12, + "LVT": 13, +} + +INCB_IDS: dict[str, int] = { + "None": 0, + "Linker": 1, + "Consonant": 2, + "Extend": 3, +} BIDI_SPOOF: frozenset[int] = frozenset( { @@ -105,66 +76,147 @@ ) -def _in_ranges(cp: int, ranges: tuple[tuple[int, int], ...]) -> bool: - return any(lo <= cp <= hi for lo, hi in ranges) +def _ensure_verified_file(ucd_dir: pathlib.Path, filename: str) -> pathlib.Path: + url, expected_sha256 = PINNED_UCD_FILES[filename] + path = ucd_dir / filename + if not path.exists(): + ucd_dir.mkdir(parents=True, exist_ok=True) + with urllib.request.urlopen(url, timeout=30) as resp: + data = resp.read() + path.write_bytes(data) + actual_sha256 = hashlib.sha256(path.read_bytes()).hexdigest() + if actual_sha256 != expected_sha256: + msg = ( + f"SHA-256 mismatch for {filename}: " + f"expected {expected_sha256}, got {actual_sha256}" + ) + raise RuntimeError(msg) + return path + + +def _parse_codepoint_ranges( + path: pathlib.Path, + *, + value_col: int = 1, + filter_col1: str | None = None, +) -> dict[int, str]: + result: dict[int, str] = {} + for raw in path.read_text(encoding="utf-8").splitlines(): + line = raw.split("#", 1)[0].strip() + if not line: + continue + parts = [part.strip() for part in line.split(";")] + if filter_col1 is not None and parts[1] != filter_col1: + continue + val = parts[value_col] + rng = parts[0] + if ".." in rng: + lo_s, hi_s = rng.split("..") + lo, hi = int(lo_s, 16), int(hi_s, 16) + else: + lo = hi = int(rng, 16) + for cp in range(lo, hi + 1): + result[cp] = val + return result + + +def _parse_emoji_sets(path: pathlib.Path) -> tuple[set[int], set[int]]: + ext_pict: set[int] = set() + emoji_mod: set[int] = set() + for raw in path.read_text(encoding="utf-8").splitlines(): + line = raw.split("#", 1)[0].strip() + if not line: + continue + parts = [part.strip() for part in line.split(";")] + prop = parts[1] + if prop not in ("Extended_Pictographic", "Emoji_Modifier"): + continue + rng = parts[0] + if ".." in rng: + lo_s, hi_s = rng.split("..") + lo, hi = int(lo_s, 16), int(hi_s, 16) + else: + lo = hi = int(rng, 16) + target = ext_pict if prop == "Extended_Pictographic" else emoji_mod + target.update(range(lo, hi + 1)) + return ext_pict, emoji_mod -def _classify(cp: int) -> int: - if 0xD800 <= cp <= 0xDFFF: - return PROP_CONTROL << 2 - ch = chr(cp) - bidi_bit = BIDI_SPOOF_BIT if cp in BIDI_SPOOF else 0 - if cp < 0x20 or 0x7F <= cp < 0xA0: - return (PROP_CONTROL << 2) | bidi_bit - if 0x20 <= cp <= 0x7E: - return 1 # width=1, prop=NONE - - if cp == 0x200D: - return (PROP_ZWJ << 2) | bidi_bit - if cp == 0xFE0E: - return (PROP_VS15 << 2) | bidi_bit - if cp == 0xFE0F: - return (PROP_VS16 << 2) | bidi_bit - if 0xFE00 <= cp <= 0xFE0D or 0xE0100 <= cp <= 0xE01EF: - return (PROP_EXTEND << 2) | bidi_bit - if 0x1F1E6 <= cp <= 0x1F1FF: - # Single Regional Indicator has base width 1; pair widens to 2 under ?2027. - return 1 | (PROP_REGIONAL_INDICATOR << 2) | bidi_bit - if 0x1F3FB <= cp <= 0x1F3FF: - return 2 | (PROP_EMOJI_MODIFIER << 2) | EXT_PICT_BIT | bidi_bit - if cp in INCB_LINKERS: - return (PROP_INCB_LINKER << 2) | bidi_bit - - cat = unicodedata.category(ch) - if cat in ("Mn", "Me") or unicodedata.combining(ch): - return (PROP_EXTEND << 2) | bidi_bit - if cat == "Mc": - eaw = unicodedata.east_asian_width(ch) - w = 2 if eaw in ("W", "F") else 1 - return w | (PROP_SPACING_MARK << 2) | bidi_bit - if cat == "Cf": - return (PROP_CONTROL << 2) | bidi_bit - - eaw = unicodedata.east_asian_width(ch) - width = 2 if eaw in ("W", "F") else 1 - - if _in_ranges(cp, INCB_CONSONANT_RANGES) and cat == "Lo": - return width | (PROP_INCB_CONSONANT << 2) | bidi_bit - if _in_ranges(cp, EXT_PICT_RANGES) and cat in ("So", "Sk", "Sm", "Po"): - return width | (PROP_EXTENDED_PICTOGRAPHIC << 2) | EXT_PICT_BIT | bidi_bit - - return width | bidi_bit - - -def build_tables() -> tuple[bytes, bytes]: - """Build deduplicated stage-1 (u16 LE) and stage-2 (u8) 256-codepoint tables.""" +def _parse_emoji_vs_bases(path: pathlib.Path) -> set[int]: + bases: set[int] = set() + for raw in path.read_text(encoding="utf-8").splitlines(): + line = raw.split("#", 1)[0].strip() + if not line: + continue + seq = [int(tok, 16) for tok in line.split(";")[0].split()] + if len(seq) == 2 and seq[1] == 0xFE0F: + bases.add(seq[0]) + return bases + + +def build_tables(ucd_dir: pathlib.Path) -> tuple[bytes, bytes]: + """Compile deduplicated stage-1 and stage-2 u16LE 256-codepoint tables.""" + gcb_map = _parse_codepoint_ranges( + _ensure_verified_file(ucd_dir, "GraphemeBreakProperty.txt"), + value_col=1, + ) + incb_map = _parse_codepoint_ranges( + _ensure_verified_file(ucd_dir, "DerivedCoreProperties.txt"), + value_col=2, + filter_col1="InCB", + ) + eaw_map = _parse_codepoint_ranges( + _ensure_verified_file(ucd_dir, "EastAsianWidth.txt"), + value_col=1, + ) + gc_map = _parse_codepoint_ranges( + _ensure_verified_file(ucd_dir, "DerivedGeneralCategory.txt"), + value_col=1, + ) + ext_pict, emoji_mod = _parse_emoji_sets( + _ensure_verified_file(ucd_dir, "emoji-data.txt"), + ) + vs_bases = _parse_emoji_vs_bases( + _ensure_verified_file(ucd_dir, "emoji-variation-sequences.txt"), + ) + _ensure_verified_file(ucd_dir, "GraphemeBreakTest.txt") + block_map: dict[bytes, int] = {} stage1_indices: list[int] = [] stage2_blocks: list[bytes] = [] for block_idx in range(0x110000 >> 8): base = block_idx << 8 - block = bytes(_classify(base + offset) for offset in range(256)) + words: list[bytes] = [] + for offset in range(256): + cp = base + offset + gcb = GCB_IDS[gcb_map.get(cp, "Other")] + incb = INCB_IDS[incb_map.get(cp, "None")] + gc = gc_map.get(cp, "Cn") + eaw = eaw_map.get(cp, "N") + if 0xD800 <= cp <= 0xDFFF or cp < 0x20 or 0x7F <= cp < 0xA0: + width = 0 + elif cp == 0x00AD or 0x1F1E6 <= cp <= 0x1F1FF: + width = 1 + elif gc in ("Mn", "Me", "Cf") and gcb != GCB_IDS["Prepend"]: + width = 0 + elif eaw in ("W", "F"): + width = 2 + else: + width = 1 + + entry = ( + width + | (gcb << 2) + | (incb << 6) + | ((1 if cp in ext_pict else 0) << 8) + | ((1 if cp in emoji_mod else 0) << 9) + | ((1 if cp in vs_bases else 0) << 10) + | ((1 if cp in BIDI_SPOOF else 0) << 11) + ) + words.append(entry.to_bytes(2, "little")) + + block = b"".join(words) idx = block_map.get(block) if idx is None: idx = len(stage2_blocks) @@ -184,10 +236,18 @@ def render_module(stage1: bytes, stage2: bytes) -> str: lines = [compressed[i : i + 76] for i in range(0, len(compressed), 76)] b85_literal = "\n".join(f' "{ln}"' for ln in lines) - ver = unicodedata.unidata_version - return f'''"""Generated two-stage Unicode {ver} cell-width and UAX #29 table. + return f'''"""Generated two-stage Unicode {UNICODE_VERSION} width and UAX #29 table. Regenerate with ``uv run python scripts/generate_ucd.py``. + +Packed 16-bit entry layout in ``_STAGE2``: +- bits ``0..1``: cell width (``0``, ``1``, or ``2``) +- bits ``2..5``: ``Grapheme_Cluster_Break`` property ID (``0..13``) +- bits ``6..7``: ``Indic_Conjunct_Break`` property ID (``0..3``) +- bit ``8``: ``Extended_Pictographic`` +- bit ``9``: ``Emoji_Modifier`` +- bit ``10``: ``emoji-variation-sequences.txt`` ``FE0E``/``FE0F`` base +- bit ``11``: BiDi control / spoofing codepoint """ from __future__ import annotations @@ -208,59 +268,91 @@ class WidthRole(enum.IntEnum): SPACER_HEAD = 3 -class ClusterState(enum.IntEnum): - """Scalar UAX #29 grapheme cluster continuation state.""" - - NONE = 0 - BASE = 1 - RI_ODD = 2 - EXT_PICT = 3 - EXT_PICT_ZWJ = 4 - INCB_CONS = 5 - INCB_LINKER = 6 - - -PROP_NONE = 0 -PROP_CONTROL = 1 -PROP_EXTEND = 2 -PROP_ZWJ = 3 -PROP_REGIONAL_INDICATOR = 4 -PROP_SPACING_MARK = 5 -PROP_EXTENDED_PICTOGRAPHIC = 6 -PROP_INCB_CONSONANT = 7 -PROP_INCB_LINKER = 8 -PROP_VS15 = 9 -PROP_VS16 = 10 -PROP_EMOJI_MODIFIER = 11 - -EXT_PICT_BIT = 0x40 -BIDI_SPOOF_BIT = 0x80 - -UNICODE_VERSION = "{unicodedata.unidata_version}" +GCB_OTHER = 0 +GCB_CR = 1 +GCB_LF = 2 +GCB_CONTROL = 3 +GCB_EXTEND = 4 +GCB_ZWJ = 5 +GCB_REGIONAL_INDICATOR = 6 +GCB_PREPEND = 7 +GCB_SPACING_MARK = 8 +GCB_L = 9 +GCB_V = 10 +GCB_T = 11 +GCB_LV = 12 +GCB_LVT = 13 + +INCB_NONE = 0 +INCB_LINKER = 1 +INCB_CONSONANT = 2 +INCB_EXTEND = 3 + +EXT_PICT_BIT = 1 << 8 +EMOJI_MOD_BIT = 1 << 9 +EMOJI_VS_BASE_BIT = 1 << 10 +BIDI_SPOOF_BIT = 1 << 11 + +CLUSTER_NONE = 0 +_ACTIVE_BIT = 1 + +UNICODE_VERSION = "{UNICODE_VERSION}" _PACKED_B85 = ( {b85_literal} ) -def _unpack_tables() -> tuple[array.array[int], bytes]: +def _unpack_tables() -> tuple[array.array[int], array.array[int]]: raw = zlib.decompress(base64.b85decode(_PACKED_B85)) s1_len = int.from_bytes(raw[:4], "little") s1 = array.array("H") s1.frombytes(raw[4 : 4 + s1_len]) + s2 = array.array("H") + s2.frombytes(raw[4 + s1_len :]) if sys.byteorder != "little": s1.byteswap() - return s1, raw[4 + s1_len :] + s2.byteswap() + return s1, s2 _STAGE1, _STAGE2 = _unpack_tables() def ucd_lookup(cp: int) -> int: - """Return packed 8-bit width and UAX #29 property entry for codepoint *cp*.""" + """Return packed 16-bit width and UAX #29 property word for codepoint *cp*.""" if 0 <= cp <= 0x10FFFF: return _STAGE2[(_STAGE1[cp >> 8] << 8) | (cp & 0xFF)] - return PROP_CONTROL << 2 + return GCB_CONTROL << 2 + + +def _pack_state( + gcb: int, + ri_odd: int, + ep_state: int, + incb_state: int, + vs_base: int, +) -> int: + return ( + _ACTIVE_BIT + | (gcb << 1) + | (ri_odd << 5) + | (ep_state << 6) + | (incb_state << 8) + | (vs_base << 10) + ) + + +def init_cluster_state(cp: int, *, mode_2027: bool = True) -> int: + """Return initial packed cluster state for base codepoint *cp*.""" + entry = ucd_lookup(cp) + gcb = (entry >> 2) & 0x0F + incb = (entry >> 6) & 0x03 + ep = 1 if (entry & EXT_PICT_BIT) else 0 + vs_b = 1 if (entry & EMOJI_VS_BASE_BIT) else 0 + ri_odd = 1 if (mode_2027 and gcb == GCB_REGIONAL_INDICATOR) else 0 + incb_st = 1 if incb == INCB_CONSONANT else 0 + return _pack_state(gcb, ri_odd, ep, incb_st, vs_b) def char_width(ch: str) -> int: @@ -272,67 +364,139 @@ def char_width(ch: str) -> int: def step_cluster( - prev_state: ClusterState, + prev_state: int, cp: int, *, mode_2027: bool, -) -> tuple[bool, ClusterState, int]: +) -> tuple[bool, int, int]: """Evaluate UAX #29 continuation between *prev_state* and codepoint *cp*. Returns ------- - tuple[bool, ClusterState, int] + tuple[bool, int, int] ``(extends_previous, next_state, width_override)`` where ``width_override`` is ``-1`` (keep current cluster width), ``1`` - (narrow via ``VS15``), or ``2`` (widen via ``VS16``, emoji modifier, - ZWJ pictographic, or Regional Indicator pair). + (narrow via ``VS15`` on an emoji variation base), or ``2`` (widen via + ``VS16`` on an emoji variation base, emoji modifier, ZWJ pictographic, + Regional Indicator pair, or wide glyph after ``Prepend``). """ entry = ucd_lookup(cp) - prop = (entry >> 2) & 0x0F - - if prev_state != ClusterState.NONE: - if prop == PROP_EXTEND: - return True, prev_state, -1 - if prop == PROP_VS16: - return True, prev_state, (2 if mode_2027 else -1) - if prop == PROP_VS15: - return True, prev_state, (1 if mode_2027 else -1) - if mode_2027: - if prop == PROP_SPACING_MARK: - next_st = ( - prev_state - if prev_state in (ClusterState.INCB_CONS, ClusterState.EXT_PICT) - else ClusterState.BASE - ) - return True, next_st, -1 - if prop == PROP_ZWJ: - next_st = ( - ClusterState.EXT_PICT_ZWJ - if prev_state == ClusterState.EXT_PICT - else ClusterState.BASE - ) - return True, next_st, -1 - if prop == PROP_EMOJI_MODIFIER and prev_state == ClusterState.EXT_PICT: - return True, ClusterState.EXT_PICT, 2 - if prev_state == ClusterState.EXT_PICT_ZWJ and (entry & EXT_PICT_BIT): - return True, ClusterState.EXT_PICT, 2 - if prop == PROP_REGIONAL_INDICATOR and prev_state == ClusterState.RI_ODD: - return True, ClusterState.BASE, 2 - if prop == PROP_INCB_LINKER and prev_state == ClusterState.INCB_CONS: - return True, ClusterState.INCB_LINKER, -1 - if prop == PROP_INCB_CONSONANT and prev_state == ClusterState.INCB_LINKER: - return True, ClusterState.INCB_CONS, -1 - - # Start of a new base cell (or dropped standalone zero-width character). - if prop == PROP_REGIONAL_INDICATOR and mode_2027: - return False, ClusterState.RI_ODD, -1 - if entry & EXT_PICT_BIT: - return False, ClusterState.EXT_PICT, -1 - if prop == PROP_INCB_CONSONANT: - return False, ClusterState.INCB_CONS, -1 - if (entry & 0b11) == 0: - return False, ClusterState.NONE, -1 - return False, ClusterState.BASE, -1 + gcb = (entry >> 2) & 0x0F + incb = (entry >> 6) & 0x03 + ep = bool(entry & EXT_PICT_BIT) + w = entry & 0b11 + + if prev_state & _ACTIVE_BIT: + prev_g = (prev_state >> 1) & 0x0F + ri_odd = (prev_state >> 5) & 0x01 + ep_state = (prev_state >> 6) & 0x03 + incb_state = (prev_state >> 8) & 0x03 + vs_base = (prev_state >> 10) & 0x01 + + if not mode_2027: + if gcb == GCB_EXTEND: + return True, _pack_state(gcb, 0, ep_state, incb_state, 0), -1 + if w == 0: + return False, CLUSTER_NONE, -1 + return False, init_cluster_state(cp, mode_2027=False), -1 + + joined = False + if prev_g == GCB_CR and gcb == GCB_LF: + joined = True + elif prev_g in (GCB_CR, GCB_LF, GCB_CONTROL) or gcb in ( + GCB_CR, + GCB_LF, + GCB_CONTROL, + ): + joined = False + elif ( + (prev_g == GCB_L and gcb in (GCB_L, GCB_V, GCB_LV, GCB_LVT)) + or (prev_g in (GCB_LV, GCB_V) and gcb in (GCB_V, GCB_T)) + or (prev_g in (GCB_LVT, GCB_T) and gcb == GCB_T) + or gcb in (GCB_EXTEND, GCB_ZWJ, GCB_SPACING_MARK) + or prev_g == GCB_PREPEND + or (incb_state == 2 and incb == INCB_CONSONANT) + or (ep_state == 2 and ep) + or (ri_odd == 1 and gcb == GCB_REGIONAL_INDICATOR) + ): + joined = True + + if joined: + w_override = -1 + if cp == 0xFE0F and vs_base: + w_override = 2 + elif cp == 0xFE0E and vs_base: + w_override = 1 + elif ( + ((entry & EMOJI_MOD_BIT) and ep_state == 1) + or (ep_state == 2 and ep) + or (ri_odd == 1 and gcb == GCB_REGIONAL_INDICATOR) + or (prev_g == GCB_PREPEND and w == 2) + ): + w_override = 2 + + next_ri = (ri_odd ^ 1) if gcb == GCB_REGIONAL_INDICATOR else 0 + if ep_state == 1 and gcb == GCB_EXTEND: + next_ep = 1 + elif ep_state == 1 and gcb == GCB_ZWJ: + next_ep = 2 + elif ep: + next_ep = 1 + else: + next_ep = 0 + + if incb == INCB_CONSONANT: + next_incb = 1 + elif incb_state in (1, 2) and incb == INCB_LINKER: + next_incb = 2 + elif incb_state in (1, 2) and incb == INCB_EXTEND: + next_incb = incb_state + else: + next_incb = 0 + + next_vs = ( + 1 if (prev_g == GCB_PREPEND and (entry & EMOJI_VS_BASE_BIT)) else 0 + ) + return ( + True, + _pack_state(gcb, next_ri, next_ep, next_incb, next_vs), + w_override, + ) + + if w == 0 and gcb in (GCB_CR, GCB_LF, GCB_CONTROL, GCB_EXTEND, GCB_ZWJ): + return False, CLUSTER_NONE, -1 + return False, init_cluster_state(cp, mode_2027=mode_2027), -1 + + +def segment_graphemes(text: str) -> list[str]: + """Segment *text* into Unicode 17.0.0 UAX #29 extended grapheme clusters.""" + if not text: + return [] + clusters: list[str] = [] + buf: list[str] = [text[0]] + state = init_cluster_state(ord(text[0]), mode_2027=True) + for ch in text[1:]: + cp = ord(ch) + entry = ucd_lookup(cp) + gcb = (entry >> 2) & 0x0F + prev_g = (state >> 1) & 0x0F + if prev_g in (GCB_CR, GCB_LF, GCB_CONTROL) and not ( + prev_g == GCB_CR and gcb == GCB_LF + ): + clusters.append("".join(buf)) + buf = [ch] + state = init_cluster_state(cp, mode_2027=True) + continue + extends, next_state, _ = step_cluster(state, cp, mode_2027=True) + if extends: + buf.append(ch) + state = next_state + else: + clusters.append("".join(buf)) + buf = [ch] + state = init_cluster_state(cp, mode_2027=True) + clusters.append("".join(buf)) + return clusters def display_width(text: str, *, mode_2027: bool = True) -> int: @@ -341,13 +505,12 @@ def display_width(text: str, *, mode_2027: bool = True) -> int: return sum(1 for ch in text if " " <= ch <= "~") total = 0 cur_w = 0 - state = ClusterState.NONE + state = CLUSTER_NONE for ch in text: cp = ord(ch) - if 0x20 <= cp <= 0x7E: - total += cur_w + if 0x20 <= cp <= 0x7E and state == CLUSTER_NONE: cur_w = 1 - state = ClusterState.BASE + state = init_cluster_state(cp, mode_2027=mode_2027) continue extends, state, w_override = step_cluster(state, cp, mode_2027=mode_2027) if extends: @@ -375,24 +538,33 @@ def sanitize_terminal_text(text: str) -> str: __all__ = [ "BIDI_SPOOF_BIT", + "CLUSTER_NONE", "UNICODE_VERSION", - "ClusterState", "WidthRole", "char_width", "display_width", + "init_cluster_state", "sanitize_terminal_text", + "segment_graphemes", "step_cluster", "ucd_lookup", ] ''' -def main() -> int: - """Regenerate ``src/libvt/_ucd.py`` from ``unicodedata``.""" - stage1, stage2 = build_tables() - target = ( - pathlib.Path(__file__).resolve().parent.parent / "src" / "libvt" / "_ucd.py" +def main(argv: list[str] | None = None) -> int: + """Regenerate ``src/libvt/_ucd.py`` from SHA-256-verified Unicode 17.0.0 data.""" + repo_root = pathlib.Path(__file__).resolve().parent.parent + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--ucd-dir", + type=pathlib.Path, + default=repo_root / ".cache" / "ucd" / UNICODE_VERSION, + help="Directory holding SHA-256-verified Unicode 17.0.0 UCD text files.", ) + args = parser.parse_args(argv) + stage1, stage2 = build_tables(args.ucd_dir) + target = repo_root / "src" / "libvt" / "_ucd.py" target.write_text(render_module(stage1, stage2), encoding="utf-8") return 0 diff --git a/src/libvt/__init__.py b/src/libvt/__init__.py index 1d3facf..d16517b 100644 --- a/src/libvt/__init__.py +++ b/src/libvt/__init__.py @@ -45,6 +45,7 @@ InBandResize, KittyCommand, KittyGraphic, + Passthrough, ProgramStatusChanged, PromptKind, PromptMark, @@ -166,6 +167,7 @@ "OutputFormat", "Parser", "ParserState", + "Passthrough", "PasteEvent", "Policy", "Profile", diff --git a/src/libvt/_ucd.py b/src/libvt/_ucd.py index 11ec4bd..330cd25 100644 --- a/src/libvt/_ucd.py +++ b/src/libvt/_ucd.py @@ -1,6 +1,15 @@ -"""Generated two-stage Unicode 17.0.0 cell-width and UAX #29 table. +"""Generated two-stage Unicode 17.0.0 width and UAX #29 table. Regenerate with ``uv run python scripts/generate_ucd.py``. + +Packed 16-bit entry layout in ``_STAGE2``: +- bits ``0..1``: cell width (``0``, ``1``, or ``2``) +- bits ``2..5``: ``Grapheme_Cluster_Break`` property ID (``0..13``) +- bits ``6..7``: ``Indic_Conjunct_Break`` property ID (``0..3``) +- bit ``8``: ``Extended_Pictographic`` +- bit ``9``: ``Emoji_Modifier`` +- bit ``10``: ``emoji-variation-sequences.txt`` ``FE0E``/``FE0F`` base +- bit ``11``: BiDi control / spoofing codepoint """ from __future__ import annotations @@ -21,87 +30,130 @@ class WidthRole(enum.IntEnum): SPACER_HEAD = 3 -class ClusterState(enum.IntEnum): - """Scalar UAX #29 grapheme cluster continuation state.""" - - NONE = 0 - BASE = 1 - RI_ODD = 2 - EXT_PICT = 3 - EXT_PICT_ZWJ = 4 - INCB_CONS = 5 - INCB_LINKER = 6 - - -PROP_NONE = 0 -PROP_CONTROL = 1 -PROP_EXTEND = 2 -PROP_ZWJ = 3 -PROP_REGIONAL_INDICATOR = 4 -PROP_SPACING_MARK = 5 -PROP_EXTENDED_PICTOGRAPHIC = 6 -PROP_INCB_CONSONANT = 7 -PROP_INCB_LINKER = 8 -PROP_VS15 = 9 -PROP_VS16 = 10 -PROP_EMOJI_MODIFIER = 11 - -EXT_PICT_BIT = 0x40 -BIDI_SPOOF_BIT = 0x80 +GCB_OTHER = 0 +GCB_CR = 1 +GCB_LF = 2 +GCB_CONTROL = 3 +GCB_EXTEND = 4 +GCB_ZWJ = 5 +GCB_REGIONAL_INDICATOR = 6 +GCB_PREPEND = 7 +GCB_SPACING_MARK = 8 +GCB_L = 9 +GCB_V = 10 +GCB_T = 11 +GCB_LV = 12 +GCB_LVT = 13 + +INCB_NONE = 0 +INCB_LINKER = 1 +INCB_CONSONANT = 2 +INCB_EXTEND = 3 + +EXT_PICT_BIT = 1 << 8 +EMOJI_MOD_BIT = 1 << 9 +EMOJI_VS_BASE_BIT = 1 << 10 +BIDI_SPOOF_BIT = 1 << 11 + +CLUSTER_NONE = 0 +_ACTIVE_BIT = 1 UNICODE_VERSION = "17.0.0" _PACKED_B85 = ( - "c-rk8hoa;pa9E?Fp5;{RtLu5{*?aH3_ZsZIpMJ!BxP+1rLJ}aPY{JajeVc?Zg@G9=oB{@j;SSD&4" - "9yMJ>0;)Z-kp*4>!Xt?Dv6vZiQ2D8=" - "QvQ;SRVH&cI!($Ge%-_pr~sa395A$D-z@zN@F?bxFsHJ$4e?J9J!!z(KJO|" - "Ii3-BVm1TVuY@G86pufrSgCcFi2!#mDY-woi@4c}|rc^^KIzdj7s^hfY<1l~SjIeiMBS)P3E^!^v" - "@^Cjd!Yj?lWet*qm{f7Pj7QTb;+5aEl$6DH-;Ai*+eudxQclZPTgumc#_{Xq@gj>b4Ne3G*f0Qs`" - "!h{JECQO(xVZww76DCZUFk!;g;=k};(n7+72@`G*vmQX>Lgq|AFH+|yL0rHSL(+I#5hO+U8zf>V{" - ")RO`R`Tdv1kM|Yrc`2v6cb!a4mOtcF*r}vjzXoG1@20!r7y4isD;^M3$MWyC+n+3q>R-wvblqpemdATlc>BG|X0N_0hKgb)f_`gf=p(;" - "IpEnAH-Kz$ol3()cAiuBv_lEujeJ+1Vzm{c#KB-#)39SEnT-CoW{Rhb3$pq4Vm8n?zgOHqvuz*Nt" - "=1a&hS7Z&?rVDSe-8saj-x#2W*H?z5X5#=a6VYC$BhF9EuO2%>s{=XHvOSyFZgPa0O%OO9@eJ)v8A<3V" - "FljBc*|&gKnFp=1TvCLu#kbXj@+g-QEH0i3;Tjz?$NiLUvMa|P7yLiTJh&GdZ6-Jf@DTo?F_!VQmvm_w_vs%w6tr>gJQ)^AgrWV_Z>Cs|^4vrZQE+Lv74%x" - "Y#Vz0XlZZ36I?EXm)s|m+4x}E31r5}7l)_4Tyk;&" - "%yXTJ{Ma*Me;hh6ahDz)u0Irv#clVc6o!=sQsW(AckQ~n9k~V4m1~L5BzqP8s7;F&xFh;c`L0E0M" - "Ql+`c&xV5UbHC#4g(gu^u7D8^^Ks}pb{bM+_Yg~T^n@|1shnTC@SJ" - "G(_{*kQ3{Oj8@$FTjDbxNeNj9HDNisVo=l^Y|_kvq9XP?<&w#wWTC5P}&j" - ")8|E6rQT;Rg)}zfsB{h{Dm|5@ipnG3DpJbdX>C@%T4=U!{JO*C4RL|Z{QO+1n+vw_+ai" - "xg{1a%4IgRZPW@!S)jp59@W&qK8bYhWEdFI2@n{{;XK34KoW9GZf-&f9" + "j5dMQiOC09Uw-h(rI*%PNy^IOxmM;I*ZPxL+Sl*#tqI(giXQhj6kxrvU^&2$UhO1IH*x}ENzJLxWO|L&%HBm}jw&h5R~ulw" + "l!^!xxlNDm1i9?s5>(4+JiJx)*1lk^llP0!G?^c+1;FVKth61_}IIzg{EKlRlHId#Kp%9YpYjr9C" + "x`gyCdJm02wJml@&G^O|Gea)Q@oZ^3&em8tenYx+hA`z?J(-_sBD" + "BmG1_(=YTZ{YJm1*Z;`y=L||FV8&nI!OZ0!000000000000000001yq{7wJRzZQT)0002f#GVERv" + "-1J%JsEjA2ZU4)2)|Vfn)-Usq{=qm``cdtFjT}72P6#CEd}5Q(1(Q#@(+LRo4N%Dcj{Bm>EJMUUY" + "*iZHE|(b2?Sm8W5*V)IXI_UdpNYX(f5g<7@vl&Z2cq6glK->7$W7ot|7!bmlLc^wlpAA1FGj>VKIRll-e_bSnX}-Hvudf0A1QH~n9SsjvTmMgMp0BPJR3CHJHJccB-y^6#%4" + "nxE!J{wssc4kUXodk{;lmajAxtzA9rs{dWszc|x@WJ`aNNjS+$My$v_XWXMVff9f5VW!n?2$=#Mc=G-0Z<_=_@qd#cQ5o@2!sh*y@c8nf~Uvin&jpdTDR>$lh0VYreZT6T" + "6W2suS@1izKR-xy9YI=IZ3Hj8)bmvCz8G#Wl4Y`PwLu+98|#uV&D*cx2=l+Kk#`Bg5Ex!|{HqFHR" + "?|;wL-tIjZBYdV*RL#*!}|arL5zW$)g?=DB;bDqp^=NjyW_5OIB(k>J;tdL0SEM{kr*!tZ$8c)PD(=yCm=VETogr32hs)%lF^BMz__=m@64;YL?p;" + "r_Jl=qAx$@di0|$x0BBGT=iwt(g?fXyp`kDhb6vCRlO3(0OPM+?BX6BqW?_u8?4w*v3Ib5B_wNbN" + "1M|E+;i>oGiIhAJ>-&g7vTdUYK1ZNUVJX29x{8Z=67dd6MGUO?>kHXiDWv@rSeKi^}PO#-xA3eMXdhTeZw*DW8R}@fvR^$Rd1=A#P4pLQGhq;wXipV5x~3SULWf!)f?Zd-rrX+jdf7~%zXh" + "M#b&+^cu~H8w(owRj-&9gD?srSj7aErq+cH+Em6t=l*M=y^l_qS;{!E" + "!ehtt=Fu2<-h;^Ab1>I-hK3X`rn-RmeLW2hvVSZFW-~f2p6Y=EvII+>%LATUu=WZo0snVQ%q2JBI" + "cCNA^%xTE94G`1U8^=D3TV`o_17vJW)EwIuOvHhw3*sImNY{cv6Ee#-AOXR0NZ75OVU;X8*54)(p" + "a@Xm60UP#%l0!N1Sc0ugxkW16J#*MhFwGwGPp85Jcx<0u;yDHOSAROX7mO`e{i1ZZzTzmO9Xmc-LT|l>%" + "b{}575)8e50)M75CIH%rZd*7hvooNhG_+j!0Y}!Re5Ne|LRmmvVRZ&phlQX&q~?9J+(euAE=)`v<" + "hg7B%fgxbN>sdZ=I?%)km3vOzQ9pd_eoR>m5!Z?>_5)bN$}uv)o3F#0|MN_Av{#@tLk(ojRItO79" + ";4V0_vG9~AXEtKPq$XaovP0ImhyEGN&&+KM1Wfn`7c|IYKj7232;_zq|}F8JbeV!eHlM" + "jdH^{d%?DLL#2`#xmT4Z#>Lj~P~~qPf>lwv$!RX9{MyN|fSEr|cbH>b12*|8=@z)g1a3Bxv4>D?p" + "UAZLSw%eN_%yw~F{AdeGUQqxYNXvkSv1$mWr!^;jxf~ll4Y`Z1bpc7O6~_(eFZ6eg_psk5OyzxS*" + "|i6HKu)vbk%!V>I|K?d(6}_Z3$)#ILDNFRhy0|A-)FSb1K%`f@W`J&3R4CB=MQ}|5Jp6|5o0wIEL" + "1KcgbIu?N^`eV^{vxlaJrS%`SSk>h4#8G1sp tuple[array.array[int], bytes]: +def _unpack_tables() -> tuple[array.array[int], array.array[int]]: raw = zlib.decompress(base64.b85decode(_PACKED_B85)) s1_len = int.from_bytes(raw[:4], "little") s1 = array.array("H") s1.frombytes(raw[4 : 4 + s1_len]) + s2 = array.array("H") + s2.frombytes(raw[4 + s1_len :]) if sys.byteorder != "little": s1.byteswap() - return s1, raw[4 + s1_len :] + s2.byteswap() + return s1, s2 _STAGE1, _STAGE2 = _unpack_tables() def ucd_lookup(cp: int) -> int: - """Return packed 8-bit width and UAX #29 property entry for codepoint *cp*.""" + """Return packed 16-bit width and UAX #29 property word for codepoint *cp*.""" if 0 <= cp <= 0x10FFFF: return _STAGE2[(_STAGE1[cp >> 8] << 8) | (cp & 0xFF)] - return PROP_CONTROL << 2 + return GCB_CONTROL << 2 + + +def _pack_state( + gcb: int, + ri_odd: int, + ep_state: int, + incb_state: int, + vs_base: int, +) -> int: + return ( + _ACTIVE_BIT + | (gcb << 1) + | (ri_odd << 5) + | (ep_state << 6) + | (incb_state << 8) + | (vs_base << 10) + ) + + +def init_cluster_state(cp: int, *, mode_2027: bool = True) -> int: + """Return initial packed cluster state for base codepoint *cp*.""" + entry = ucd_lookup(cp) + gcb = (entry >> 2) & 0x0F + incb = (entry >> 6) & 0x03 + ep = 1 if (entry & EXT_PICT_BIT) else 0 + vs_b = 1 if (entry & EMOJI_VS_BASE_BIT) else 0 + ri_odd = 1 if (mode_2027 and gcb == GCB_REGIONAL_INDICATOR) else 0 + incb_st = 1 if incb == INCB_CONSONANT else 0 + return _pack_state(gcb, ri_odd, ep, incb_st, vs_b) def char_width(ch: str) -> int: @@ -113,67 +165,139 @@ def char_width(ch: str) -> int: def step_cluster( - prev_state: ClusterState, + prev_state: int, cp: int, *, mode_2027: bool, -) -> tuple[bool, ClusterState, int]: +) -> tuple[bool, int, int]: """Evaluate UAX #29 continuation between *prev_state* and codepoint *cp*. Returns ------- - tuple[bool, ClusterState, int] + tuple[bool, int, int] ``(extends_previous, next_state, width_override)`` where ``width_override`` is ``-1`` (keep current cluster width), ``1`` - (narrow via ``VS15``), or ``2`` (widen via ``VS16``, emoji modifier, - ZWJ pictographic, or Regional Indicator pair). + (narrow via ``VS15`` on an emoji variation base), or ``2`` (widen via + ``VS16`` on an emoji variation base, emoji modifier, ZWJ pictographic, + Regional Indicator pair, or wide glyph after ``Prepend``). """ entry = ucd_lookup(cp) - prop = (entry >> 2) & 0x0F - - if prev_state != ClusterState.NONE: - if prop == PROP_EXTEND: - return True, prev_state, -1 - if prop == PROP_VS16: - return True, prev_state, (2 if mode_2027 else -1) - if prop == PROP_VS15: - return True, prev_state, (1 if mode_2027 else -1) - if mode_2027: - if prop == PROP_SPACING_MARK: - next_st = ( - prev_state - if prev_state in (ClusterState.INCB_CONS, ClusterState.EXT_PICT) - else ClusterState.BASE - ) - return True, next_st, -1 - if prop == PROP_ZWJ: - next_st = ( - ClusterState.EXT_PICT_ZWJ - if prev_state == ClusterState.EXT_PICT - else ClusterState.BASE - ) - return True, next_st, -1 - if prop == PROP_EMOJI_MODIFIER and prev_state == ClusterState.EXT_PICT: - return True, ClusterState.EXT_PICT, 2 - if prev_state == ClusterState.EXT_PICT_ZWJ and (entry & EXT_PICT_BIT): - return True, ClusterState.EXT_PICT, 2 - if prop == PROP_REGIONAL_INDICATOR and prev_state == ClusterState.RI_ODD: - return True, ClusterState.BASE, 2 - if prop == PROP_INCB_LINKER and prev_state == ClusterState.INCB_CONS: - return True, ClusterState.INCB_LINKER, -1 - if prop == PROP_INCB_CONSONANT and prev_state == ClusterState.INCB_LINKER: - return True, ClusterState.INCB_CONS, -1 - - # Start of a new base cell (or dropped standalone zero-width character). - if prop == PROP_REGIONAL_INDICATOR and mode_2027: - return False, ClusterState.RI_ODD, -1 - if entry & EXT_PICT_BIT: - return False, ClusterState.EXT_PICT, -1 - if prop == PROP_INCB_CONSONANT: - return False, ClusterState.INCB_CONS, -1 - if (entry & 0b11) == 0: - return False, ClusterState.NONE, -1 - return False, ClusterState.BASE, -1 + gcb = (entry >> 2) & 0x0F + incb = (entry >> 6) & 0x03 + ep = bool(entry & EXT_PICT_BIT) + w = entry & 0b11 + + if prev_state & _ACTIVE_BIT: + prev_g = (prev_state >> 1) & 0x0F + ri_odd = (prev_state >> 5) & 0x01 + ep_state = (prev_state >> 6) & 0x03 + incb_state = (prev_state >> 8) & 0x03 + vs_base = (prev_state >> 10) & 0x01 + + if not mode_2027: + if gcb == GCB_EXTEND: + return True, _pack_state(gcb, 0, ep_state, incb_state, 0), -1 + if w == 0: + return False, CLUSTER_NONE, -1 + return False, init_cluster_state(cp, mode_2027=False), -1 + + joined = False + if prev_g == GCB_CR and gcb == GCB_LF: + joined = True + elif prev_g in (GCB_CR, GCB_LF, GCB_CONTROL) or gcb in ( + GCB_CR, + GCB_LF, + GCB_CONTROL, + ): + joined = False + elif ( + (prev_g == GCB_L and gcb in (GCB_L, GCB_V, GCB_LV, GCB_LVT)) + or (prev_g in (GCB_LV, GCB_V) and gcb in (GCB_V, GCB_T)) + or (prev_g in (GCB_LVT, GCB_T) and gcb == GCB_T) + or gcb in (GCB_EXTEND, GCB_ZWJ, GCB_SPACING_MARK) + or prev_g == GCB_PREPEND + or (incb_state == 2 and incb == INCB_CONSONANT) + or (ep_state == 2 and ep) + or (ri_odd == 1 and gcb == GCB_REGIONAL_INDICATOR) + ): + joined = True + + if joined: + w_override = -1 + if cp == 0xFE0F and vs_base: + w_override = 2 + elif cp == 0xFE0E and vs_base: + w_override = 1 + elif ( + ((entry & EMOJI_MOD_BIT) and ep_state == 1) + or (ep_state == 2 and ep) + or (ri_odd == 1 and gcb == GCB_REGIONAL_INDICATOR) + or (prev_g == GCB_PREPEND and w == 2) + ): + w_override = 2 + + next_ri = (ri_odd ^ 1) if gcb == GCB_REGIONAL_INDICATOR else 0 + if ep_state == 1 and gcb == GCB_EXTEND: + next_ep = 1 + elif ep_state == 1 and gcb == GCB_ZWJ: + next_ep = 2 + elif ep: + next_ep = 1 + else: + next_ep = 0 + + if incb == INCB_CONSONANT: + next_incb = 1 + elif incb_state in (1, 2) and incb == INCB_LINKER: + next_incb = 2 + elif incb_state in (1, 2) and incb == INCB_EXTEND: + next_incb = incb_state + else: + next_incb = 0 + + next_vs = ( + 1 if (prev_g == GCB_PREPEND and (entry & EMOJI_VS_BASE_BIT)) else 0 + ) + return ( + True, + _pack_state(gcb, next_ri, next_ep, next_incb, next_vs), + w_override, + ) + + if w == 0 and gcb in (GCB_CR, GCB_LF, GCB_CONTROL, GCB_EXTEND, GCB_ZWJ): + return False, CLUSTER_NONE, -1 + return False, init_cluster_state(cp, mode_2027=mode_2027), -1 + + +def segment_graphemes(text: str) -> list[str]: + """Segment *text* into Unicode 17.0.0 UAX #29 extended grapheme clusters.""" + if not text: + return [] + clusters: list[str] = [] + buf: list[str] = [text[0]] + state = init_cluster_state(ord(text[0]), mode_2027=True) + for ch in text[1:]: + cp = ord(ch) + entry = ucd_lookup(cp) + gcb = (entry >> 2) & 0x0F + prev_g = (state >> 1) & 0x0F + if prev_g in (GCB_CR, GCB_LF, GCB_CONTROL) and not ( + prev_g == GCB_CR and gcb == GCB_LF + ): + clusters.append("".join(buf)) + buf = [ch] + state = init_cluster_state(cp, mode_2027=True) + continue + extends, next_state, _ = step_cluster(state, cp, mode_2027=True) + if extends: + buf.append(ch) + state = next_state + else: + clusters.append("".join(buf)) + buf = [ch] + state = init_cluster_state(cp, mode_2027=True) + clusters.append("".join(buf)) + return clusters def display_width(text: str, *, mode_2027: bool = True) -> int: @@ -182,13 +306,12 @@ def display_width(text: str, *, mode_2027: bool = True) -> int: return sum(1 for ch in text if " " <= ch <= "~") total = 0 cur_w = 0 - state = ClusterState.NONE + state = CLUSTER_NONE for ch in text: cp = ord(ch) - if 0x20 <= cp <= 0x7E: - total += cur_w + if 0x20 <= cp <= 0x7E and state == CLUSTER_NONE: cur_w = 1 - state = ClusterState.BASE + state = init_cluster_state(cp, mode_2027=mode_2027) continue extends, state, w_override = step_cluster(state, cp, mode_2027=mode_2027) if extends: @@ -216,12 +339,14 @@ def sanitize_terminal_text(text: str) -> str: __all__ = [ "BIDI_SPOOF_BIT", + "CLUSTER_NONE", "UNICODE_VERSION", - "ClusterState", "WidthRole", "char_width", "display_width", + "init_cluster_state", "sanitize_terminal_text", + "segment_graphemes", "step_cluster", "ucd_lookup", ] diff --git a/src/libvt/config.py b/src/libvt/config.py index daf6fa0..cea9030 100644 --- a/src/libvt/config.py +++ b/src/libvt/config.py @@ -59,6 +59,9 @@ class Profile: pending_wrap_phantom_col: bool = False +_DEFAULT_OSC7_HOSTS: frozenset[str] = frozenset({"", "localhost"}) + + @dataclass(frozen=True, slots=True) class Policy: """Default-deny host security and strictness policy. @@ -84,9 +87,16 @@ class Policy: allow_unsafe_uris : bool Allow schemes outside ``http://``, ``https://``, and ``mailto:`` in HTML ```` output (default ``False``). - unwrap_tmux_passthrough : bool - Unwrap ``DCS tmux; ESC ESC ... ST`` passthrough envelopes and feed the - inner byte stream (default ``True``). + allow_passthrough : bool + Re-feed unwrapped ``DCS tmux; ESC ESC ... ST`` inner byte streams into + :class:`~libvt.terminal.Terminal` in addition to emitting + :class:`~libvt.events.Passthrough` (default ``False``, matching + ``tmux``'s ``allow-passthrough off``). + osc7_hosts : frozenset[str] + Lowercase hostnames in ``OSC 7`` ``file:///...`` URIs permitted + to update :attr:`~libvt.terminal.Terminal.cwd` (default + ``frozenset({"", "localhost"})``; :func:`~libvt.aio.open_pty` adds the + local machine hostname automatically). strict : bool Raise :exc:`~libvt.exc.ProtocolError` on unrecognized escape sequences instead of ignoring or recording :class:`~libvt.events.UnhandledSequence` @@ -100,7 +110,8 @@ class Policy: allow_color_queries: bool = True allow_program_status_query: bool = False allow_unsafe_uris: bool = False - unwrap_tmux_passthrough: bool = True + allow_passthrough: bool = False + osc7_hosts: frozenset[str] = _DEFAULT_OSC7_HOSTS strict: bool = False diff --git a/src/libvt/events.py b/src/libvt/events.py index a34aec8..2206ab6 100644 --- a/src/libvt/events.py +++ b/src/libvt/events.py @@ -297,6 +297,19 @@ class ScreenErased: active_is_alt: bool +@dataclass(frozen=True, slots=True) +class Passthrough: + """Emitted when a ``DCS tmux; ESC ESC ... ST`` passthrough envelope arrives. + + Attributes + ---------- + data : bytes + Payload bytes with one layer of ``ESC ESC`` un-doubled. + """ + + data: bytes + + @dataclass(frozen=True, slots=True) class UnhandledSequence: """Recorded when an unrecognized control sequence arrives and ``strict=False``. @@ -326,6 +339,7 @@ class UnhandledSequence: | SixelGraphic | KittyGraphic | ScreenErased + | Passthrough | UnhandledSequence ) @@ -338,6 +352,7 @@ class UnhandledSequence: "InBandResize", "KittyCommand", "KittyGraphic", + "Passthrough", "ProgramStatusChanged", "PromptKind", "PromptZone", diff --git a/src/libvt/parser.py b/src/libvt/parser.py index b474bb7..4ad3ea7 100644 --- a/src/libvt/parser.py +++ b/src/libvt/parser.py @@ -1,8 +1,9 @@ -"""Clean-room 14-state VT500 streaming byte parser and SGR parameter decoder. +"""Clean-room VT500 streaming byte parser and SGR parameter decoder. State transitions follow Paul Flo Williams' public DEC ANSI parser state -diagram (ECMA-48 / DEC STD 070) with UTF-8 multi-byte decoding, 7-bit C1 -isolation, and bounded parameter and string buffers. +diagram (ECMA-48 / DEC STD 070) with UTF-8 multi-byte decoding, 7-bit string +escape isolation via :attr:`ParserState.STRING_ESC`, optional legacy Latin-1 +8-bit ``C1`` wire parsing, and bounded parameter and string buffers. """ from __future__ import annotations @@ -30,6 +31,9 @@ _MEMO_LIMIT = 256 _CTRL_RE = re.compile(rb"[\x00-\x1f\x7f]") _CSI_FAST_RE = re.compile(rb"([\x3c-\x3f]?)([0-9;:]{0,256})([\x40-\x7e])") +_C1_CHAR_RE = re.compile(r"[\x80-\x9f]") + +type ParserEncoding = t.Literal["utf-8", "latin-1"] class ParserState(enum.IntEnum): @@ -49,6 +53,7 @@ class ParserState(enum.IntEnum): DCS_IGNORE = 11 OSC_STRING = 12 SOS_PM_APC_STRING = 13 + STRING_ESC = 14 @dataclass(frozen=True, slots=True) @@ -182,7 +187,8 @@ class OscDispatch: Raw payload bytes following the first ``;`` (or the full body when no ``;`` is present). terminator : bytes - Wire terminator that closed the command (``b"\x07"`` or ``b"\x1b\\"``). + Wire terminator that closed the command (``b"\x07"``, ``b"\x1b\\"``, or + ``b"\x9c"`` in Latin-1 8-bit mode). """ code: int @@ -550,10 +556,9 @@ def parse_sgr( class Parser: - """Streaming 14-state VT500 / ANSI escape-sequence byte parser.""" + """Streaming VT500 / ANSI escape-sequence byte parser.""" __slots__ = ( - "_c1_controls", "_csi_colon_mask", "_csi_cur", "_csi_has_digit", @@ -563,15 +568,18 @@ class Parser: "_csi_prefix", "_csi_vals", "_dcs_final", - "_dcs_intermediates", "_dcs_params", + "_encoding", "_intermediates", + "_latin1", "_limits", - "_return_from_esc_st", "_state", "_str_buf", + "_str_esc_origin", "_str_kind", "_str_overflow", + "_tmux_dcs_state", + "_tmux_passthrough", "_utf8", "_utf8_pending", ) @@ -579,10 +587,16 @@ class Parser: def __init__( self, *, - c1_controls: bool = False, + encoding: ParserEncoding = "utf-8", + tmux_passthrough: bool = True, limits: Limits = DEFAULT_LIMITS, ) -> None: - self._c1_controls = c1_controls + if encoding not in ("utf-8", "latin-1"): + msg = f"unsupported parser encoding: {encoding!r}" + raise ValueError(msg) + self._encoding: ParserEncoding = encoding + self._latin1: bool = encoding == "latin-1" + self._tmux_passthrough: bool = tmux_passthrough self._limits = limits self._state: ParserState = ParserState.GROUND self._utf8 = codecs.getincrementaldecoder("utf-8")("replace") @@ -596,14 +610,19 @@ def __init__( self._csi_has_digit: bool = False self._csi_is_colon: bool = False self._dcs_params: CsiParams = EMPTY_PARAMS - self._dcs_intermediates: bytes = b"" self._dcs_final: int = 0 self._str_buf = bytearray() self._str_overflow: bool = False self._str_kind: int = 0 - self._return_from_esc_st: ParserState | None = None + self._str_esc_origin: ParserState | None = None + self._tmux_dcs_state: int = 0 self._csi_memo: dict[bytes, CsiParams] = {} + @property + def encoding(self) -> ParserEncoding: + """Return wire character encoding (``"utf-8"`` or ``"latin-1"``).""" + return self._encoding + @property def state(self) -> ParserState: """Return the current :class:`ParserState`.""" @@ -621,10 +640,7 @@ def reset(self) -> None: self._utf8_pending = False self._intermediates.clear() self._reset_csi() - self._str_buf.clear() - self._str_overflow = False - self._str_kind = 0 - self._return_from_esc_st = None + self._abort_string() def _reset_csi(self) -> None: self._csi_prefix = 0 @@ -636,6 +652,14 @@ def _reset_csi(self) -> None: self._csi_is_colon = False self._intermediates.clear() + def _abort_string(self) -> None: + self._str_buf.clear() + self._str_overflow = False + self._str_kind = 0 + self._str_esc_origin = None + self._tmux_dcs_state = 0 + self._reset_csi() + def _push_param(self, *, next_is_colon: bool) -> None: idx = len(self._csi_vals) if idx < self._limits.max_csi_params: @@ -671,15 +695,16 @@ def _decode_utf8_bytes(self, raw: bytes | memoryview, sink: ActionSink) -> None: decoded = self._utf8.decode(chunk, final=False) self._utf8_pending = bool(self._utf8.getstate()[0]) if decoded: - sink.on_print(decoded) + cleaned = _C1_CHAR_RE.sub("", decoded) + if cleaned: + sink.on_print(cleaned) def _dispatch_osc(self, sink: ActionSink, terminator: bytes) -> None: if self._str_overflow: - self._str_buf.clear() - self._str_overflow = False + self._abort_string() return raw = bytes(self._str_buf) - self._str_buf.clear() + self._abort_string() semi = raw.find(b";") if semi == -1: code = int(raw) if raw.isdigit() else -1 @@ -694,21 +719,51 @@ def _dispatch_dcs(self, sink: ActionSink) -> None: sink.on_dcs( self._csi_prefix, self._dcs_params, - self._dcs_intermediates, + bytes(self._intermediates), self._dcs_final, bytes(self._str_buf), ) - self._str_buf.clear() - self._str_overflow = False - self._dcs_intermediates = b"" - self._reset_csi() + self._abort_string() def _dispatch_apc(self, sink: ActionSink) -> None: if self._str_kind == 0x5F and not self._str_overflow: sink.on_apc(bytes(self._str_buf)) + self._abort_string() + + def _enter_dcs_passthrough(self, final_byte: int) -> None: + self._dcs_params = self._finalize_params() + self._dcs_final = final_byte self._str_buf.clear() self._str_overflow = False - self._str_kind = 0 + self._tmux_dcs_state = ( + 1 + if ( + self._tmux_passthrough + and self._csi_prefix == 0 + and not self._intermediates + and not self._dcs_params.values + and final_byte == 0x74 + ) + else 0 + ) + self._state = ParserState.DCS_PASSTHROUGH + + def _handle_c1_anywhere(self, b: int, sink: ActionSink) -> None: + self._abort_string() + if b == 0x9B: # CSI + self._state = ParserState.CSI_ENTRY + elif b == 0x9D: # OSC + self._state = ParserState.OSC_STRING + elif b == 0x90: # DCS + self._state = ParserState.DCS_ENTRY + elif b in (0x98, 0x9E, 0x9F): # SOS, PM, APC + self._str_kind = b - 0x40 + self._state = ParserState.SOS_PM_APC_STRING + elif b == 0x9C: # ST + self._state = ParserState.GROUND + else: + self._state = ParserState.GROUND + sink.on_esc(b"", b - 0x40) def _cached_csi_params(self, pbytes: bytes) -> CsiParams: if not pbytes: @@ -736,7 +791,7 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None: mv = memoryview(data).cast("B") n = len(mv) pos = 0 - c1 = self._c1_controls + latin1 = self._latin1 max_osc = self._limits.max_osc_bytes max_dcs = self._limits.max_dcs_bytes max_apc = self._limits.max_apc_bytes @@ -745,42 +800,19 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None: state = self._state if state == ParserState.GROUND: - if c1: - if not self._utf8_pending and 0x80 <= mv[pos] <= 0x9F: - b_c1 = mv[pos] - pos += 1 - if b_c1 == 0x9B: - self._reset_csi() - self._state = ParserState.CSI_ENTRY - elif b_c1 == 0x9D: - self._str_buf.clear() - self._str_overflow = False - self._state = ParserState.OSC_STRING - elif b_c1 == 0x90: - self._reset_csi() - self._str_buf.clear() - self._str_overflow = False - self._state = ParserState.DCS_ENTRY - elif b_c1 in (0x98, 0x9E, 0x9F): - self._str_buf.clear() - self._str_overflow = False - self._str_kind = b_c1 - 0x40 - self._state = ParserState.SOS_PM_APC_STRING - elif b_c1 != 0x9C: - sink.on_esc(b"", b_c1 - 0x40) - continue + if latin1: end = pos - while end < n and 0x20 <= mv[end] <= 0x7E: + while end < n and (0x20 <= mv[end] <= 0x7E or mv[end] >= 0xA0): end += 1 - if end > pos and not self._utf8_pending: - sink.on_print(bytes(mv[pos:end]).decode("ascii")) + if end > pos: + sink.on_print(bytes(mv[pos:end]).decode("latin-1")) pos = end if pos >= n: break - continue - if mv[pos] >= 0x80: - self._decode_utf8_bytes(mv[pos : pos + 1], sink) + b_lat = mv[pos] + if 0x80 <= b_lat <= 0x9F: pos += 1 + self._handle_c1_anywhere(b_lat, sink) continue else: match = _CTRL_RE.search(mv, pos) @@ -819,22 +851,21 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None: pos = csi_m.end() continue self._intermediates.clear() - self._return_from_esc_st = None self._state = ParserState.ESCAPE elif b == 0x7F: pass else: - # Flush incomplete UTF-8 BEFORE executing any C0 control! self._flush_incomplete_utf8(sink) sink.on_execute(b) continue - # String states: bulk-scan up to ESC / BEL / CAN / SUB (or 0x9C if c1). if state == ParserState.OSC_STRING: start = pos while pos < n: b_scan = mv[pos] - if b_scan in (0x07, 0x18, 0x1A, 0x1B) or (c1 and b_scan == 0x9C): + if b_scan in (0x07, 0x18, 0x1A, 0x1B) or ( + latin1 and 0x80 <= b_scan <= 0x9F + ): break pos += 1 if pos > start and not self._str_overflow: @@ -851,16 +882,16 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None: if b == 0x07: self._dispatch_osc(sink, b"\x07") self._state = ParserState.GROUND - elif c1 and b == 0x9C: + elif latin1 and b == 0x9C: self._dispatch_osc(sink, b"\x9c") self._state = ParserState.GROUND + elif latin1 and 0x80 <= b <= 0x9F: + self._handle_c1_anywhere(b, sink) elif b == 0x1B: - self._return_from_esc_st = ParserState.OSC_STRING - self._intermediates.clear() - self._state = ParserState.ESCAPE - else: # CAN (0x18) or SUB (0x1A) - self._str_buf.clear() - self._str_overflow = False + self._str_esc_origin = ParserState.OSC_STRING + self._state = ParserState.STRING_ESC + else: + self._abort_string() self._state = ParserState.GROUND continue @@ -868,13 +899,19 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None: start = pos while pos < n: b_scan = mv[pos] - if b_scan in (0x18, 0x1A, 0x1B, 0x7F) or (c1 and b_scan == 0x9C): + if b_scan in (0x18, 0x1A, 0x1B, 0x7F) or ( + latin1 and 0x80 <= b_scan <= 0x9F + ): break pos += 1 if pos > start and not self._str_overflow: chunk_len = pos - start if len(self._str_buf) + chunk_len <= max_dcs: self._str_buf.extend(mv[start:pos]) + if self._tmux_dcs_state == 1 and len(self._str_buf) >= 4: + self._tmux_dcs_state = ( + 2 if self._str_buf[:4] == b"mux;" else -1 + ) else: self._str_buf.clear() self._str_overflow = True @@ -884,17 +921,16 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None: pos += 1 if b == 0x7F: continue - if c1 and b == 0x9C: + if latin1 and b == 0x9C: self._dispatch_dcs(sink) self._state = ParserState.GROUND + elif latin1 and 0x80 <= b <= 0x9F: + self._handle_c1_anywhere(b, sink) elif b == 0x1B: - self._return_from_esc_st = ParserState.DCS_PASSTHROUGH - self._intermediates.clear() - self._state = ParserState.ESCAPE + self._str_esc_origin = ParserState.DCS_PASSTHROUGH + self._state = ParserState.STRING_ESC else: - self._str_buf.clear() - self._str_overflow = False - self._reset_csi() + self._abort_string() self._state = ParserState.GROUND continue @@ -902,7 +938,9 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None: start = pos while pos < n: b_scan = mv[pos] - if b_scan in (0x18, 0x1A, 0x1B) or (c1 and b_scan == 0x9C): + if b_scan in (0x18, 0x1A, 0x1B) or ( + latin1 and 0x80 <= b_scan <= 0x9F + ): break pos += 1 if pos > start and self._str_kind == 0x5F and not self._str_overflow: @@ -916,31 +954,38 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None: break b = mv[pos] pos += 1 - if c1 and b == 0x9C: + if latin1 and b == 0x9C: self._dispatch_apc(sink) self._state = ParserState.GROUND + elif latin1 and 0x80 <= b <= 0x9F: + self._handle_c1_anywhere(b, sink) elif b == 0x1B: - self._return_from_esc_st = ParserState.SOS_PM_APC_STRING - self._intermediates.clear() - self._state = ParserState.ESCAPE + self._str_esc_origin = ParserState.SOS_PM_APC_STRING + self._state = ParserState.STRING_ESC else: - self._str_buf.clear() - self._str_overflow = False - self._str_kind = 0 + self._abort_string() self._state = ParserState.GROUND continue - b = mv[pos] - pos += 1 - - if b == 0x1B: + if state == ParserState.STRING_ESC: + b = mv[pos] + pos += 1 + origin = self._str_esc_origin + if b == 0x5C: # 'ESC \' -> 7-bit ST + if origin == ParserState.OSC_STRING: + self._dispatch_osc(sink, b"\x1b\\") + elif origin == ParserState.DCS_PASSTHROUGH: + self._dispatch_dcs(sink) + elif origin == ParserState.SOS_PM_APC_STRING: + self._dispatch_apc(sink) + else: + self._abort_string() + self._state = ParserState.GROUND + continue if ( - state == ParserState.ESCAPE - and self._return_from_esc_st == ParserState.DCS_PASSTHROUGH - and self._dcs_final == 0x74 - and self._csi_prefix == 0 - and not self._dcs_intermediates - and self._str_buf.startswith(b"mux;") + b == 0x1B + and origin == ParserState.DCS_PASSTHROUGH + and self._tmux_dcs_state == 2 ): if not self._str_overflow: if len(self._str_buf) + 1 <= max_dcs: @@ -948,33 +993,34 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None: else: self._str_buf.clear() self._str_overflow = True - self._return_from_esc_st = None + self._str_esc_origin = None self._state = ParserState.DCS_PASSTHROUGH continue - # Double-ESC inside a non-passthrough string aborts it cleanly. - if self._return_from_esc_st is not None: - self._str_buf.clear() - self._str_overflow = False - self._str_kind = 0 - self._dcs_intermediates = b"" - self._return_from_esc_st = None - self._intermediates.clear() + # Any other byte aborts the unclosed string per DEC STD 070 §5.1.2.3 + # and re-evaluates b starting from ESCAPE. + self._abort_string() + self._state = ParserState.ESCAPE + pos -= 1 + continue + + b = mv[pos] + pos += 1 + + if latin1 and 0x80 <= b <= 0x9F: + self._handle_c1_anywhere(b, sink) + continue + + if b == 0x1B: + self._abort_string() self._state = ParserState.ESCAPE continue if b in (0x18, 0x1A): - self._str_buf.clear() - self._str_overflow = False - self._str_kind = 0 - self._return_from_esc_st = None - self._reset_csi() + self._abort_string() self._state = ParserState.GROUND continue if state == ParserState.DCS_IGNORE: - if c1 and b == 0x9C: - self._reset_csi() - self._state = ParserState.GROUND continue if b < 0x20: @@ -984,22 +1030,6 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None: continue if state == ParserState.ESCAPE: - prev_str = self._return_from_esc_st - self._return_from_esc_st = None - if prev_str is not None and b == 0x5C: # 'ESC \' -> 7-bit ST - if prev_str == ParserState.OSC_STRING: - self._dispatch_osc(sink, b"\x1b\\") - elif prev_str == ParserState.DCS_PASSTHROUGH: - self._dispatch_dcs(sink) - elif prev_str == ParserState.SOS_PM_APC_STRING: - self._dispatch_apc(sink) - self._state = ParserState.GROUND - continue - if prev_str is not None: - self._str_buf.clear() - self._str_overflow = False - self._str_kind = 0 - if 0x20 <= b <= 0x2F: self._intermediates.append(b) self._state = ParserState.ESCAPE_INTERMEDIATE @@ -1111,12 +1141,7 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None: self._intermediates.append(b) self._state = ParserState.DCS_INTERMEDIATE elif 0x40 <= b <= 0x7E: - self._dcs_params = self._finalize_params() - self._dcs_intermediates = bytes(self._intermediates) - self._dcs_final = b - self._str_buf.clear() - self._str_overflow = False - self._state = ParserState.DCS_PASSTHROUGH + self._enter_dcs_passthrough(b) else: self._state = ParserState.DCS_IGNORE @@ -1125,12 +1150,7 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None: if len(self._intermediates) < MAX_INTERMEDIATES: self._intermediates.append(b) elif 0x40 <= b <= 0x7E: - self._dcs_params = self._finalize_params() - self._dcs_intermediates = bytes(self._intermediates) - self._dcs_final = b - self._str_buf.clear() - self._str_overflow = False - self._state = ParserState.DCS_PASSTHROUGH + self._enter_dcs_passthrough(b) else: self._state = ParserState.DCS_IGNORE @@ -1147,6 +1167,7 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None: "Execute", "OscDispatch", "Parser", + "ParserEncoding", "ParserState", "Print", "parse_sgr", diff --git a/src/libvt/screen.py b/src/libvt/screen.py index 6c5b6d6..b4808d9 100644 --- a/src/libvt/screen.py +++ b/src/libvt/screen.py @@ -526,6 +526,35 @@ def clear_history(self) -> None: """Clear all sealed scrollback rows (``ED 3``).""" self._history.clear() + def _clear_row_spacer_head(self, row_obj: _Row) -> None: + if not row_obj.has_wide or row_obj.attrs is None: + return + last = self._cols - 1 + if raw_width_bits(row_obj.attrs[last]) == int(WidthRole.SPACER_HEAD): + row_obj.chars[last] = " " + row_obj.attrs[last] &= _WIDTH_CLEAR_MASK + while ( + row_obj.used > 0 + and row_obj.chars[row_obj.used - 1] == " " + and row_obj.attr_at(row_obj.used - 1) == 0 + and row_obj.ext_at(row_obj.used - 1) is None + ): + row_obj.used -= 1 + + def heal_wrapped_spacer_head(self, row: int) -> None: + """Clear a preceding row's ``SPACER_HEAD`` when ``(row, 0)`` splits.""" + if row <= 0 or row > len(self._rows): + return + prev = self._rows[row - 1] + if not prev.has_wide or prev.attrs is None: + return + if row == len(self._rows) or not prev.wrapped: + self._clear_row_spacer_head(prev) + return + cur = self._rows[row] + if raw_width_bits(cur.attr_at(0)) != int(WidthRole.WIDE): + self._clear_row_spacer_head(prev) + @property def lines(self) -> tuple[str, ...]: """Return right-trimmed text for every visible row.""" @@ -577,6 +606,12 @@ def scroll_up( full_width = left == 0 and r_col == self._cols - 1 if full_width: + if t_row > 0: + self._rows[t_row - 1].wrapped = False + self._clear_row_spacer_head(self._rows[t_row - 1]) + if b_row < len(self._rows) - 1: + self._rows[b_row].wrapped = False + self._clear_row_spacer_head(self._rows[b_row]) can_save = ( save_history and t_row == 0 @@ -598,6 +633,10 @@ def scroll_up( for dst_r in range(t_row, b_row - shift + 1): src_row = self._rows[dst_r + shift] dst_row = self._rows[dst_r] + dst_row.wrapped = False + self._clear_row_spacer_head(dst_row) + if dst_r > 0 and left <= 1: + self._clear_row_spacer_head(self._rows[dst_r - 1]) dst_row._heal_wide_boundary(left) dst_row._heal_wide_boundary(r_col) src_row._heal_wide_boundary(left) @@ -610,6 +649,10 @@ def scroll_up( dst_row.used = max(dst_row.used, min(src_row.used, r_col + 1)) for clr_r in range(b_row - shift + 1, b_row + 1): + self._rows[clr_r].wrapped = False + self._clear_row_spacer_head(self._rows[clr_r]) + if clr_r > 0 and left <= 1: + self._clear_row_spacer_head(self._rows[clr_r - 1]) self._rows[clr_r].clear_range(left, r_col + 1, bce_word, bce_ext) def scroll_down( @@ -633,16 +676,26 @@ def scroll_down( full_width = left == 0 and r_col == self._cols - 1 if full_width: + if t_row > 0: + self._rows[t_row - 1].wrapped = False + self._clear_row_spacer_head(self._rows[t_row - 1]) recycled = self._rows[b_row - shift + 1 : b_row + 1] del self._rows[b_row - shift + 1 : b_row + 1] for row_ev in recycled: row_ev.reset_blank(self._cols, bce_word, bce_ext) self._rows[t_row:t_row] = recycled + if b_row < len(self._rows) - 1: + self._rows[b_row].wrapped = False + self._clear_row_spacer_head(self._rows[b_row]) return for dst_r in range(b_row, t_row + shift - 1, -1): src_row = self._rows[dst_r - shift] dst_row = self._rows[dst_r] + dst_row.wrapped = False + self._clear_row_spacer_head(dst_row) + if dst_r > 0 and left <= 1: + self._clear_row_spacer_head(self._rows[dst_r - 1]) dst_row._heal_wide_boundary(left) dst_row._heal_wide_boundary(r_col) src_row._heal_wide_boundary(left) @@ -655,6 +708,10 @@ def scroll_down( dst_row.used = max(dst_row.used, min(src_row.used, r_col + 1)) for clr_r in range(t_row, t_row + shift): + self._rows[clr_r].wrapped = False + self._clear_row_spacer_head(self._rows[clr_r]) + if clr_r > 0 and left <= 1: + self._clear_row_spacer_head(self._rows[clr_r - 1]) self._rows[clr_r].clear_range(left, r_col + 1, bce_word, bce_ext) def push_scrollback_and_clear( diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py index 6c95eb9..f1831d2 100644 --- a/src/libvt/terminal.py +++ b/src/libvt/terminal.py @@ -23,9 +23,10 @@ unpack_style, ) from libvt._ucd import ( - ClusterState, + CLUSTER_NONE, WidthRole, char_width, + init_cluster_state, sanitize_terminal_text, step_cluster, ) @@ -46,6 +47,7 @@ InBandResize, KittyCommand, KittyGraphic, + Passthrough, ProgramStatusChanged, PromptKind, PromptMark, @@ -68,7 +70,7 @@ Mode, ModeState, ) -from libvt.parser import CsiParams, Parser, ParserState, parse_sgr +from libvt.parser import CsiParams, Parser, ParserEncoding, ParserState, parse_sgr from libvt.screen import ( Cell, Cursor, @@ -257,6 +259,7 @@ class Snapshot: "active_is_alt", "cursor", "cwd", + "cwd_uri", "generation", "modes", "program_status", @@ -274,6 +277,7 @@ def __init__( cursor: Cursor, title: str, cwd: str, + cwd_uri: str = "", modes: frozenset[Mode], active_is_alt: bool, prompt_zones: tuple[PromptZone, ...], @@ -287,6 +291,7 @@ def __init__( self.cursor = cursor self.title = title self.cwd = cwd + self.cwd_uri = cwd_uri self.modes = modes self.active_is_alt = active_is_alt self.prompt_zones = prompt_zones @@ -364,6 +369,7 @@ def to_dict(self) -> dict[str, t.Any]: }, "title": self.title, "cwd": self.cwd, + "cwd_uri": self.cwd_uri, "active_is_alt": self.active_is_alt, "modes": sorted(m.name for m in self.modes if m.name is not None), "program_status": ( @@ -624,11 +630,12 @@ def __init__( on_pty_write: collections.abc.Callable[[bytes], None] | None = None, record_events: bool = False, recorder: FlightRecorder | None = None, - c1_controls: bool = False, + encoding: ParserEncoding = "utf-8", ) -> None: self._profile = profile self._policy = policy self._limits = limits + self._encoding: ParserEncoding = encoding self._on_event = on_event self._on_pty_write = on_pty_write self._record_events = record_events @@ -643,7 +650,7 @@ def __init__( keyboard_stack_depth=limits.max_keyboard_stack, ) self._modes = ModeState() - self._parser = Parser(c1_controls=c1_controls, limits=limits) + self._parser = Parser(encoding=encoding, limits=limits) self._sink = _TerminalSink(self) self._sgr_memo: dict[tuple[Style, CsiParams], Style] = {} self._style: Style = DEFAULT_STYLE @@ -658,11 +665,12 @@ def __init__( self._saved_alt = _SavedCursor() self._last_printed: str = "" self._last_printed_pos: tuple[int, int] | None = None - self._cluster_state: ClusterState = ClusterState.NONE + self._cluster_state: int = CLUSTER_NONE self._cluster_len: int = 0 self._title: str = "" self._title_stack: list[str] = [] self._cwd: str = "" + self._cwd_uri: str = "" self._prompt_zones: collections.deque[PromptZone] = collections.deque( maxlen=limits.max_prompt_zones, ) @@ -760,9 +768,14 @@ def title(self) -> str: @property def cwd(self) -> str: - """Return working directory path reported by ``OSC 7`` / ``OSC 9;9``.""" + """Return local working directory path accepted under ``Policy.osc7_hosts``.""" return self._cwd + @property + def cwd_uri(self) -> str: + """Return raw ``OSC 7`` / ``OSC 9;9`` working directory URI.""" + return self._cwd_uri + @property def modes(self) -> ModeState: """Return current :class:`~libvt.modes.ModeState`.""" @@ -847,6 +860,7 @@ def snapshot(self) -> Snapshot: cursor=scr.cursor, title=self._title, cwd=self._cwd, + cwd_uri=self._cwd_uri, modes=self._modes.enabled_modes(), active_is_alt=self._screens.active_is_alt, prompt_zones=self.prompt_zones, @@ -956,7 +970,7 @@ def _emit_reply(self, payload: bytes) -> None: def _clear_cluster_anchor(self) -> None: self._last_printed_pos = None - self._cluster_state = ClusterState.NONE + self._cluster_state = CLUSTER_NONE self._cluster_len = 0 def _sync_pen_cache(self) -> None: @@ -1044,6 +1058,7 @@ def reset(self, *, soft: bool = False) -> None: self._title = "" self._title_stack.clear() self._cwd = "" + self._cwd_uri = "" self._prompt_zones.clear() self._status_store.reset() self._notify_erase( @@ -1223,9 +1238,10 @@ def _handle_print(self, text: str) -> None: scr = self._screens.active autowrap = self._modes.is_set(Mode.DECAWM) insert_mode = self._modes.is_set(Mode.IRM) - _, _, left, right = self._effective_margins(scr) + _, bottom, left, right = self._effective_margins(scr) if text.isascii() and not insert_mode: + mode_2027_ascii = self._modes.is_set(Mode.GRAPHEME_CLUSTERING) pos = 0 total = len(text) while pos < total: @@ -1233,7 +1249,11 @@ def _handle_print(self, text: str) -> None: max_col = right if c_col <= right else scr.cols - 1 min_col = left if c_col >= left else 0 if scr._pending_wrap and autowrap: - scr._rows[scr._cur_row].wrapped = True + can_advance = scr._cur_row < scr.rows - 1 or ( + scr._cur_row == bottom and left <= c_col <= right + ) + if can_advance and min_col == 0 and max_col == scr.cols - 1: + scr._rows[scr._cur_row].wrapped = True self._linefeed(scr) self._set_cursor(scr, scr._cur_row, min_col, pending_wrap=False) c_col = scr._cur_col @@ -1246,6 +1266,8 @@ def _handle_print(self, text: str) -> None: self._pen_word, self._cell_ext, ) + if c_col <= 1: + scr.heal_wrapped_spacer_head(scr._cur_row) pos += seg_len end_col = c_col + seg_len - 1 if c_col + seg_len > max_col: @@ -1266,7 +1288,10 @@ def _handle_print(self, text: str) -> None: ) self._last_printed = seg[-1] self._last_printed_pos = (scr._cur_row, end_col) - self._cluster_state = ClusterState.BASE + self._cluster_state = init_cluster_state( + ord(seg[-1]), + mode_2027=mode_2027_ascii, + ) self._cluster_len = 1 return @@ -1292,17 +1317,24 @@ def _handle_print(self, text: str) -> None: # Right-margin VS16 / Regional Indicator widening wrap! eff_right = right if pc <= right else scr.cols - 1 eff_left = left if pc >= left else 0 + can_wrap_row = pr < scr.rows - 1 or ( + pr == bottom and left <= pc <= right + ) if ( w_override == 2 and cur_role == int(WidthRole.NARROW) and pc == eff_right and autowrap + and can_wrap_row and eff_right - eff_left >= 1 ): combined = row_obj.chars[pc] + ch bce_w, bce_e = self._bce_pair() - row_obj.write_spacer_head(pc, bce_w, bce_e) - row_obj.wrapped = True + if eff_left == 0 and eff_right == scr.cols - 1: + row_obj.write_spacer_head(pc, bce_w, bce_e) + row_obj.wrapped = True + else: + row_obj.write_narrow(pc, " ", bce_w, bce_e) self._linefeed(scr) nr = scr._cur_row scr._rows[nr].write_wide( @@ -1339,6 +1371,8 @@ def _handle_print(self, text: str) -> None: pen_word=self._pen_word, cell_ext=self._cell_ext, ) + if pc == 0 and w_override == 1: + scr.heal_wrapped_spacer_head(pr) self._cluster_len += 1 self._last_printed = row_obj.chars[pc] if ( @@ -1378,7 +1412,7 @@ def _handle_print(self, text: str) -> None: continue else: _, next_state, _ = step_cluster( - ClusterState.NONE, + CLUSTER_NONE, cp, mode_2027=mode_2027, ) @@ -1391,19 +1425,31 @@ def _handle_print(self, text: str) -> None: c_col = scr._cur_col max_col = right if c_col <= right else scr.cols - 1 min_col = left if c_col >= left else 0 + just_wrapped_wide = False if scr._pending_wrap and autowrap: - scr._rows[c_row].wrapped = True + can_advance = c_row < scr.rows - 1 or ( + c_row == bottom and left <= c_col <= right + ) + if can_advance and min_col == 0 and max_col == scr.cols - 1: + scr._rows[c_row].wrapped = True self._linefeed(scr) self._set_cursor(scr, scr._cur_row, min_col, pending_wrap=False) c_row = scr._cur_row c_col = scr._cur_col if width == 2 and c_col == max_col: - if autowrap and max_col - min_col >= 1: + can_advance = c_row < scr.rows - 1 or ( + c_row == bottom and left <= c_col <= right + ) + if autowrap and can_advance and max_col - min_col >= 1: bce_w, bce_e = self._bce_pair() - scr._rows[c_row].write_spacer_head(c_col, bce_w, bce_e) - scr._rows[c_row].wrapped = True + if min_col == 0 and max_col == scr.cols - 1: + scr._rows[c_row].write_spacer_head(c_col, bce_w, bce_e) + scr._rows[c_row].wrapped = True + just_wrapped_wide = True + else: + scr._rows[c_row].write_narrow(c_col, " ", bce_w, bce_e) self._linefeed(scr) self._set_cursor(scr, scr._cur_row, min_col, pending_wrap=False) c_row = scr._cur_row @@ -1473,6 +1519,9 @@ def _handle_print(self, text: str) -> None: clear_cluster=False, ) + if c_col <= 1 and not just_wrapped_wide: + scr.heal_wrapped_spacer_head(c_row) + self._last_printed = ch self._last_printed_pos = (c_row, placed_col) self._cluster_state = next_state @@ -1736,6 +1785,9 @@ def _erase_display( bce_e, selective=selective, ) + if c_col <= 1: + scr.heal_wrapped_spacer_head(c_row) + scr._rows[c_row].wrapped = False for r in range(c_row + 1, scr.rows): scr._rows[r].clear_range(0, scr.cols, bce_w, bce_e, selective=selective) self._notify_erase(Rect(c_row, c_col, 1, scr.cols - c_col), cause) @@ -1754,6 +1806,9 @@ def _erase_display( bce_e, selective=selective, ) + scr.heal_wrapped_spacer_head(c_row) + if c_row + 1 < scr.rows: + scr.heal_wrapped_spacer_head(c_row + 1) if c_row > 0: self._notify_erase(Rect(0, 0, c_row, scr.cols), cause) self._notify_erase(Rect(c_row, 0, 1, c_col + 1), cause) @@ -1792,6 +1847,9 @@ def _erase_line( bce_e, selective=selective, ) + if c_col <= 1: + scr.heal_wrapped_spacer_head(c_row) + scr._rows[c_row].wrapped = False self._notify_erase(Rect(c_row, c_col, 1, scr.cols - c_col), cause) elif mode == 1: scr._rows[c_row].clear_range( @@ -1801,6 +1859,9 @@ def _erase_line( bce_e, selective=selective, ) + scr.heal_wrapped_spacer_head(c_row) + if c_col + 1 >= scr.cols: + scr._rows[c_row].wrapped = False self._notify_erase(Rect(c_row, 0, 1, c_col + 1), cause) elif mode == 2: scr._rows[c_row].clear_range( @@ -1810,6 +1871,7 @@ def _erase_line( bce_e, selective=selective, ) + scr.heal_wrapped_spacer_head(c_row) self._notify_erase(Rect(c_row, 0, 1, scr.cols), cause) self._set_cursor(scr, c_row, c_col, pending_wrap=False) @@ -2034,6 +2096,10 @@ def _handle_csi( n = min(scr.cols - c_col, params.get(0, 1)) bce_w, bce_e = self._bce_pair() scr._rows[c_row].clear_range(c_col, c_col + n, bce_w, bce_e) + if c_col <= 1: + scr.heal_wrapped_spacer_head(c_row) + if c_col + n >= scr.cols: + scr._rows[c_row].wrapped = False self._notify_erase(Rect(c_row, c_col, 1, n), EraseCause.ECH) self._set_cursor(scr, c_row, c_col, pending_wrap=False) elif ch_final == "@": # ICH @@ -2048,6 +2114,8 @@ def _handle_csi( bce_word=bce_w, bce_ext=bce_e, ) + if c_col <= 1: + scr.heal_wrapped_spacer_head(c_row) self._set_cursor(scr, c_row, c_col, pending_wrap=False) elif ch_final == "P": # DCH self._before_mutate() @@ -2061,6 +2129,10 @@ def _handle_csi( bce_word=bce_w, bce_ext=bce_e, ) + if c_col <= 1: + scr.heal_wrapped_spacer_head(c_row) + if right == scr.cols - 1: + scr._rows[c_row].wrapped = False self._set_cursor(scr, c_row, c_col, pending_wrap=False) elif ch_final == "L": # IL if top <= c_row <= bottom and left <= c_col <= right: @@ -2243,17 +2315,22 @@ def _handle_csi( def _update_cwd(self, raw_uri: str) -> None: cleaned = sanitize_terminal_text(raw_uri.strip()) + if not cleaned: + self._cwd = "" + self._cwd_uri = "" + self._emit_event(WorkingDirectoryChanged(uri="", path="")) + return + self._cwd_uri = cleaned if cleaned.startswith("file://"): parsed = urllib.parse.urlsplit(cleaned) - host = parsed.hostname or "" - local_host = os.uname().nodename if hasattr(os, "uname") else "" - if host not in ("", "localhost", local_host): - return + host = (parsed.hostname or "").lower() path = urllib.parse.unquote(parsed.path) - else: - path = cleaned - self._cwd = path - self._emit_event(WorkingDirectoryChanged(uri=cleaned, path=path)) + if host in self._policy.osc7_hosts: + self._cwd = path + self._emit_event(WorkingDirectoryChanged(uri=cleaned, path=path)) + return + self._cwd = cleaned + self._emit_event(WorkingDirectoryChanged(uri=cleaned, path=cleaned)) def _handle_osc(self, code: int, data: bytes, terminator: bytes) -> None: scr = self._screens.active @@ -2443,20 +2520,25 @@ def _handle_dcs( # tmux passthrough: DCS tmux; ESC ESC ... ST (final='t', data=b"mux;...") if ( - self._policy.unwrap_tmux_passthrough - and self._passthrough_depth < 2 - and prefix == 0 + prefix == 0 and not intermediates + and not params.values and final == ord("t") and data.startswith(b"mux;") ): - unwrapped = memoryview(data)[4:] - inner_parser = Parser(limits=self._limits) - self._passthrough_depth += 1 - try: - inner_parser.feed_to(unwrapped, self._sink) - finally: - self._passthrough_depth -= 1 + unwrapped = bytes(memoryview(data)[4:]) + if self._record_events or self._on_event is not None: + self._emit_event(Passthrough(data=unwrapped)) + if self._policy.allow_passthrough and self._passthrough_depth < 2: + inner_parser = Parser( + encoding=self._encoding, + limits=self._limits, + ) + self._passthrough_depth += 1 + try: + inner_parser.feed_to(unwrapped, self._sink) + finally: + self._passthrough_depth -= 1 return # SIXEL: DCS Ps... q ST diff --git a/tests/fixtures/GraphemeBreakTest-17.0.0.txt b/tests/fixtures/GraphemeBreakTest-17.0.0.txt new file mode 100644 index 0000000..e121554 --- /dev/null +++ b/tests/fixtures/GraphemeBreakTest-17.0.0.txt @@ -0,0 +1,796 @@ +# GraphemeBreakTest-17.0.0.txt +# Date: 2025-03-24, 14:45:55 GMT +# © 2025 Unicode®, Inc. +# Unicode and the Unicode Logo are registered trademarks of Unicode, Inc. in the U.S. and other countries. +# For terms of use and license, see https://www.unicode.org/terms_of_use.html +# +# Unicode Character Database +# For documentation, see https://www.unicode.org/reports/tr44/ +# +# Default Grapheme_Cluster_Break Test +# +# Format: +# (# )? +# contains hex Unicode code points, with +# ÷ wherever there is a break opportunity, and +# × wherever there is not. +# the format can change, but currently it shows: +# - the sample character name +# - (x) the Grapheme_Cluster_Break property value for the sample character and +# any other properties relevant to the algorithm, as described in +# GraphemeBreakTest.html +# - [x] the rule that determines whether there is a break or not, +# as listed in the Rules section of GraphemeBreakTest.html +# +# These samples may be extended or changed in the future. +# +÷ 000D ÷ 000D ÷ # ÷ [0.2] (CR) ÷ [4.0] (CR) ÷ [0.3] +÷ 000D ÷ 0308 ÷ 000D ÷ # ÷ [0.2] (CR) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (CR) ÷ [0.3] +÷ 000D × 000A ÷ # ÷ [0.2] (CR) × [3.0] (LF) ÷ [0.3] +÷ 000D ÷ 0308 ÷ 000A ÷ # ÷ [0.2] (CR) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (LF) ÷ [0.3] +÷ 000D ÷ 0000 ÷ # ÷ [0.2] (CR) ÷ [4.0] (Control) ÷ [0.3] +÷ 000D ÷ 0308 ÷ 0000 ÷ # ÷ [0.2] (CR) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (Control) ÷ [0.3] +÷ 000D ÷ 094D ÷ # ÷ [0.2] (CR) ÷ [4.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 000D ÷ 0308 × 094D ÷ # ÷ [0.2] (CR) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 000D ÷ 0300 ÷ # ÷ [0.2] (CR) ÷ [4.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 000D ÷ 0308 × 0300 ÷ # ÷ [0.2] (CR) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 000D ÷ 200C ÷ # ÷ [0.2] (CR) ÷ [4.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 000D ÷ 0308 × 200C ÷ # ÷ [0.2] (CR) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 000D ÷ 200D ÷ # ÷ [0.2] (CR) ÷ [4.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 000D ÷ 0308 × 200D ÷ # ÷ [0.2] (CR) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 000D ÷ 1F1E6 ÷ # ÷ [0.2] (CR) ÷ [4.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 000D ÷ 0308 ÷ 1F1E6 ÷ # ÷ [0.2] (CR) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 000D ÷ 06DD ÷ # ÷ [0.2] (CR) ÷ [4.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 000D ÷ 0308 ÷ 06DD ÷ # ÷ [0.2] (CR) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 000D ÷ 0903 ÷ # ÷ [0.2] (CR) ÷ [4.0] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 000D ÷ 0308 × 0903 ÷ # ÷ [0.2] (CR) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 000D ÷ 1100 ÷ # ÷ [0.2] (CR) ÷ [4.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 000D ÷ 0308 ÷ 1100 ÷ # ÷ [0.2] (CR) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 000D ÷ 1160 ÷ # ÷ [0.2] (CR) ÷ [4.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 000D ÷ 0308 ÷ 1160 ÷ # ÷ [0.2] (CR) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 000D ÷ 11A8 ÷ # ÷ [0.2] (CR) ÷ [4.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 000D ÷ 0308 ÷ 11A8 ÷ # ÷ [0.2] (CR) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 000D ÷ AC00 ÷ # ÷ [0.2] (CR) ÷ [4.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 000D ÷ 0308 ÷ AC00 ÷ # ÷ [0.2] (CR) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 000D ÷ AC01 ÷ # ÷ [0.2] (CR) ÷ [4.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 000D ÷ 0308 ÷ AC01 ÷ # ÷ [0.2] (CR) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 000D ÷ 0915 ÷ # ÷ [0.2] (CR) ÷ [4.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 000D ÷ 0308 ÷ 0915 ÷ # ÷ [0.2] (CR) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 000D ÷ 00A9 ÷ # ÷ [0.2] (CR) ÷ [4.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 000D ÷ 0308 ÷ 00A9 ÷ # ÷ [0.2] (CR) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 000D ÷ 0020 ÷ # ÷ [0.2] (CR) ÷ [4.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 000D ÷ 0308 ÷ 0020 ÷ # ÷ [0.2] (CR) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 000D ÷ 0378 ÷ # ÷ [0.2] (CR) ÷ [4.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 000D ÷ 0308 ÷ 0378 ÷ # ÷ [0.2] (CR) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 000A ÷ 000D ÷ # ÷ [0.2] (LF) ÷ [4.0] (CR) ÷ [0.3] +÷ 000A ÷ 0308 ÷ 000D ÷ # ÷ [0.2] (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (CR) ÷ [0.3] +÷ 000A ÷ 000A ÷ # ÷ [0.2] (LF) ÷ [4.0] (LF) ÷ [0.3] +÷ 000A ÷ 0308 ÷ 000A ÷ # ÷ [0.2] (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (LF) ÷ [0.3] +÷ 000A ÷ 0000 ÷ # ÷ [0.2] (LF) ÷ [4.0] (Control) ÷ [0.3] +÷ 000A ÷ 0308 ÷ 0000 ÷ # ÷ [0.2] (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (Control) ÷ [0.3] +÷ 000A ÷ 094D ÷ # ÷ [0.2] (LF) ÷ [4.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 000A ÷ 0308 × 094D ÷ # ÷ [0.2] (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 000A ÷ 0300 ÷ # ÷ [0.2] (LF) ÷ [4.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 000A ÷ 0308 × 0300 ÷ # ÷ [0.2] (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 000A ÷ 200C ÷ # ÷ [0.2] (LF) ÷ [4.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 000A ÷ 0308 × 200C ÷ # ÷ [0.2] (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 000A ÷ 200D ÷ # ÷ [0.2] (LF) ÷ [4.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 000A ÷ 0308 × 200D ÷ # ÷ [0.2] (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 000A ÷ 1F1E6 ÷ # ÷ [0.2] (LF) ÷ [4.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 000A ÷ 0308 ÷ 1F1E6 ÷ # ÷ [0.2] (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 000A ÷ 06DD ÷ # ÷ [0.2] (LF) ÷ [4.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 000A ÷ 0308 ÷ 06DD ÷ # ÷ [0.2] (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 000A ÷ 0903 ÷ # ÷ [0.2] (LF) ÷ [4.0] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 000A ÷ 0308 × 0903 ÷ # ÷ [0.2] (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 000A ÷ 1100 ÷ # ÷ [0.2] (LF) ÷ [4.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 000A ÷ 0308 ÷ 1100 ÷ # ÷ [0.2] (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 000A ÷ 1160 ÷ # ÷ [0.2] (LF) ÷ [4.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 000A ÷ 0308 ÷ 1160 ÷ # ÷ [0.2] (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 000A ÷ 11A8 ÷ # ÷ [0.2] (LF) ÷ [4.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 000A ÷ 0308 ÷ 11A8 ÷ # ÷ [0.2] (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 000A ÷ AC00 ÷ # ÷ [0.2] (LF) ÷ [4.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 000A ÷ 0308 ÷ AC00 ÷ # ÷ [0.2] (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 000A ÷ AC01 ÷ # ÷ [0.2] (LF) ÷ [4.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 000A ÷ 0308 ÷ AC01 ÷ # ÷ [0.2] (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 000A ÷ 0915 ÷ # ÷ [0.2] (LF) ÷ [4.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 000A ÷ 0308 ÷ 0915 ÷ # ÷ [0.2] (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 000A ÷ 00A9 ÷ # ÷ [0.2] (LF) ÷ [4.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 000A ÷ 0308 ÷ 00A9 ÷ # ÷ [0.2] (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 000A ÷ 0020 ÷ # ÷ [0.2] (LF) ÷ [4.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 000A ÷ 0308 ÷ 0020 ÷ # ÷ [0.2] (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 000A ÷ 0378 ÷ # ÷ [0.2] (LF) ÷ [4.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 000A ÷ 0308 ÷ 0378 ÷ # ÷ [0.2] (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0000 ÷ 000D ÷ # ÷ [0.2] (Control) ÷ [4.0] (CR) ÷ [0.3] +÷ 0000 ÷ 0308 ÷ 000D ÷ # ÷ [0.2] (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (CR) ÷ [0.3] +÷ 0000 ÷ 000A ÷ # ÷ [0.2] (Control) ÷ [4.0] (LF) ÷ [0.3] +÷ 0000 ÷ 0308 ÷ 000A ÷ # ÷ [0.2] (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (LF) ÷ [0.3] +÷ 0000 ÷ 0000 ÷ # ÷ [0.2] (Control) ÷ [4.0] (Control) ÷ [0.3] +÷ 0000 ÷ 0308 ÷ 0000 ÷ # ÷ [0.2] (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (Control) ÷ [0.3] +÷ 0000 ÷ 094D ÷ # ÷ [0.2] (Control) ÷ [4.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 0000 ÷ 0308 × 094D ÷ # ÷ [0.2] (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 0000 ÷ 0300 ÷ # ÷ [0.2] (Control) ÷ [4.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 0000 ÷ 0308 × 0300 ÷ # ÷ [0.2] (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 0000 ÷ 200C ÷ # ÷ [0.2] (Control) ÷ [4.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 0000 ÷ 0308 × 200C ÷ # ÷ [0.2] (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 0000 ÷ 200D ÷ # ÷ [0.2] (Control) ÷ [4.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 0000 ÷ 0308 × 200D ÷ # ÷ [0.2] (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 0000 ÷ 1F1E6 ÷ # ÷ [0.2] (Control) ÷ [4.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 0000 ÷ 0308 ÷ 1F1E6 ÷ # ÷ [0.2] (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 0000 ÷ 06DD ÷ # ÷ [0.2] (Control) ÷ [4.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 0000 ÷ 0308 ÷ 06DD ÷ # ÷ [0.2] (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 0000 ÷ 0903 ÷ # ÷ [0.2] (Control) ÷ [4.0] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 0000 ÷ 0308 × 0903 ÷ # ÷ [0.2] (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 0000 ÷ 1100 ÷ # ÷ [0.2] (Control) ÷ [4.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 0000 ÷ 0308 ÷ 1100 ÷ # ÷ [0.2] (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 0000 ÷ 1160 ÷ # ÷ [0.2] (Control) ÷ [4.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 0000 ÷ 0308 ÷ 1160 ÷ # ÷ [0.2] (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 0000 ÷ 11A8 ÷ # ÷ [0.2] (Control) ÷ [4.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 0000 ÷ 0308 ÷ 11A8 ÷ # ÷ [0.2] (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 0000 ÷ AC00 ÷ # ÷ [0.2] (Control) ÷ [4.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 0000 ÷ 0308 ÷ AC00 ÷ # ÷ [0.2] (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 0000 ÷ AC01 ÷ # ÷ [0.2] (Control) ÷ [4.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 0000 ÷ 0308 ÷ AC01 ÷ # ÷ [0.2] (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 0000 ÷ 0915 ÷ # ÷ [0.2] (Control) ÷ [4.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 0000 ÷ 0308 ÷ 0915 ÷ # ÷ [0.2] (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 0000 ÷ 00A9 ÷ # ÷ [0.2] (Control) ÷ [4.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 0000 ÷ 0308 ÷ 00A9 ÷ # ÷ [0.2] (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 0000 ÷ 0020 ÷ # ÷ [0.2] (Control) ÷ [4.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0000 ÷ 0308 ÷ 0020 ÷ # ÷ [0.2] (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0000 ÷ 0378 ÷ # ÷ [0.2] (Control) ÷ [4.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0000 ÷ 0308 ÷ 0378 ÷ # ÷ [0.2] (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 094D ÷ 000D ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [5.0] (CR) ÷ [0.3] +÷ 094D × 0308 ÷ 000D ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (CR) ÷ [0.3] +÷ 094D ÷ 000A ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [5.0] (LF) ÷ [0.3] +÷ 094D × 0308 ÷ 000A ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (LF) ÷ [0.3] +÷ 094D ÷ 0000 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [5.0] (Control) ÷ [0.3] +÷ 094D × 0308 ÷ 0000 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (Control) ÷ [0.3] +÷ 094D × 094D ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 094D × 0308 × 094D ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 094D × 0300 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 094D × 0308 × 0300 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 094D × 200C ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 094D × 0308 × 200C ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 094D × 200D ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 094D × 0308 × 200D ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 094D ÷ 1F1E6 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 094D × 0308 ÷ 1F1E6 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 094D ÷ 06DD ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 094D × 0308 ÷ 06DD ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 094D × 0903 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 094D × 0308 × 0903 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 094D ÷ 1100 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 094D × 0308 ÷ 1100 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 094D ÷ 1160 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 094D × 0308 ÷ 1160 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 094D ÷ 11A8 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 094D × 0308 ÷ 11A8 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 094D ÷ AC00 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 094D × 0308 ÷ AC00 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 094D ÷ AC01 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 094D × 0308 ÷ AC01 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 094D ÷ 0915 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 094D × 0308 ÷ 0915 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 094D ÷ 00A9 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 094D × 0308 ÷ 00A9 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 094D ÷ 0020 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 094D × 0308 ÷ 0020 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 094D ÷ 0378 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 094D × 0308 ÷ 0378 ÷ # ÷ [0.2] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0300 ÷ 000D ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (CR) ÷ [0.3] +÷ 0300 × 0308 ÷ 000D ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (CR) ÷ [0.3] +÷ 0300 ÷ 000A ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (LF) ÷ [0.3] +÷ 0300 × 0308 ÷ 000A ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (LF) ÷ [0.3] +÷ 0300 ÷ 0000 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (Control) ÷ [0.3] +÷ 0300 × 0308 ÷ 0000 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (Control) ÷ [0.3] +÷ 0300 × 094D ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 0300 × 0308 × 094D ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 0300 × 0300 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 0300 × 0308 × 0300 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 0300 × 200C ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 0300 × 0308 × 200C ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 0300 × 200D ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 0300 × 0308 × 200D ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 0300 ÷ 1F1E6 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 0300 × 0308 ÷ 1F1E6 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 0300 ÷ 06DD ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 0300 × 0308 ÷ 06DD ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 0300 × 0903 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 0300 × 0308 × 0903 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 0300 ÷ 1100 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 0300 × 0308 ÷ 1100 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 0300 ÷ 1160 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 0300 × 0308 ÷ 1160 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 0300 ÷ 11A8 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 0300 × 0308 ÷ 11A8 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 0300 ÷ AC00 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 0300 × 0308 ÷ AC00 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 0300 ÷ AC01 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 0300 × 0308 ÷ AC01 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 0300 ÷ 0915 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 0300 × 0308 ÷ 0915 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 0300 ÷ 00A9 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 0300 × 0308 ÷ 00A9 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 0300 ÷ 0020 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0300 × 0308 ÷ 0020 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0300 ÷ 0378 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0300 × 0308 ÷ 0378 ÷ # ÷ [0.2] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 200C ÷ 000D ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [5.0] (CR) ÷ [0.3] +÷ 200C × 0308 ÷ 000D ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (CR) ÷ [0.3] +÷ 200C ÷ 000A ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [5.0] (LF) ÷ [0.3] +÷ 200C × 0308 ÷ 000A ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (LF) ÷ [0.3] +÷ 200C ÷ 0000 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [5.0] (Control) ÷ [0.3] +÷ 200C × 0308 ÷ 0000 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (Control) ÷ [0.3] +÷ 200C × 094D ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 200C × 0308 × 094D ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 200C × 0300 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 200C × 0308 × 0300 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 200C × 200C ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 200C × 0308 × 200C ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 200C × 200D ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 200C × 0308 × 200D ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 200C ÷ 1F1E6 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 200C × 0308 ÷ 1F1E6 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 200C ÷ 06DD ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 200C × 0308 ÷ 06DD ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 200C × 0903 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 200C × 0308 × 0903 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 200C ÷ 1100 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 200C × 0308 ÷ 1100 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 200C ÷ 1160 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 200C × 0308 ÷ 1160 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 200C ÷ 11A8 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 200C × 0308 ÷ 11A8 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 200C ÷ AC00 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 200C × 0308 ÷ AC00 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 200C ÷ AC01 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 200C × 0308 ÷ AC01 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 200C ÷ 0915 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 200C × 0308 ÷ 0915 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 200C ÷ 00A9 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 200C × 0308 ÷ 00A9 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 200C ÷ 0020 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 200C × 0308 ÷ 0020 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 200C ÷ 0378 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 200C × 0308 ÷ 0378 ÷ # ÷ [0.2] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 200D ÷ 000D ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) ÷ [5.0] (CR) ÷ [0.3] +÷ 200D × 0308 ÷ 000D ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (CR) ÷ [0.3] +÷ 200D ÷ 000A ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) ÷ [5.0] (LF) ÷ [0.3] +÷ 200D × 0308 ÷ 000A ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (LF) ÷ [0.3] +÷ 200D ÷ 0000 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) ÷ [5.0] (Control) ÷ [0.3] +÷ 200D × 0308 ÷ 0000 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (Control) ÷ [0.3] +÷ 200D × 094D ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 200D × 0308 × 094D ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 200D × 0300 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 200D × 0308 × 0300 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 200D × 200C ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 200D × 0308 × 200C ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 200D × 200D ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 200D × 0308 × 200D ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 200D ÷ 1F1E6 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 200D × 0308 ÷ 1F1E6 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 200D ÷ 06DD ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 200D × 0308 ÷ 06DD ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 200D × 0903 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 200D × 0308 × 0903 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 200D ÷ 1100 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 200D × 0308 ÷ 1100 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 200D ÷ 1160 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 200D × 0308 ÷ 1160 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 200D ÷ 11A8 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 200D × 0308 ÷ 11A8 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 200D ÷ AC00 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 200D × 0308 ÷ AC00 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 200D ÷ AC01 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 200D × 0308 ÷ AC01 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 200D ÷ 0915 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 200D × 0308 ÷ 0915 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 200D ÷ 00A9 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 200D × 0308 ÷ 00A9 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 200D ÷ 0020 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 200D × 0308 ÷ 0020 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 200D ÷ 0378 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 200D × 0308 ÷ 0378 ÷ # ÷ [0.2] ZERO WIDTH JOINER (ZWJ) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 1F1E6 ÷ 000D ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [5.0] (CR) ÷ [0.3] +÷ 1F1E6 × 0308 ÷ 000D ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (CR) ÷ [0.3] +÷ 1F1E6 ÷ 000A ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [5.0] (LF) ÷ [0.3] +÷ 1F1E6 × 0308 ÷ 000A ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (LF) ÷ [0.3] +÷ 1F1E6 ÷ 0000 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [5.0] (Control) ÷ [0.3] +÷ 1F1E6 × 0308 ÷ 0000 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (Control) ÷ [0.3] +÷ 1F1E6 × 094D ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 1F1E6 × 0308 × 094D ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 1F1E6 × 0300 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 1F1E6 × 0308 × 0300 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 1F1E6 × 200C ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 1F1E6 × 0308 × 200C ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 1F1E6 × 200D ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 1F1E6 × 0308 × 200D ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 1F1E6 × 1F1E6 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [12.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 1F1E6 × 0308 ÷ 1F1E6 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 1F1E6 ÷ 06DD ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 1F1E6 × 0308 ÷ 06DD ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 1F1E6 × 0903 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 1F1E6 × 0308 × 0903 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 1F1E6 ÷ 1100 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 1F1E6 × 0308 ÷ 1100 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 1F1E6 ÷ 1160 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 1F1E6 × 0308 ÷ 1160 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 1F1E6 ÷ 11A8 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 1F1E6 × 0308 ÷ 11A8 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 1F1E6 ÷ AC00 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 1F1E6 × 0308 ÷ AC00 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 1F1E6 ÷ AC01 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 1F1E6 × 0308 ÷ AC01 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 1F1E6 ÷ 0915 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 1F1E6 × 0308 ÷ 0915 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 1F1E6 ÷ 00A9 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 1F1E6 × 0308 ÷ 00A9 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 1F1E6 ÷ 0020 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 1F1E6 × 0308 ÷ 0020 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 1F1E6 ÷ 0378 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 1F1E6 × 0308 ÷ 0378 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 06DD ÷ 000D ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) ÷ [5.0] (CR) ÷ [0.3] +÷ 06DD × 0308 ÷ 000D ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (CR) ÷ [0.3] +÷ 06DD ÷ 000A ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) ÷ [5.0] (LF) ÷ [0.3] +÷ 06DD × 0308 ÷ 000A ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (LF) ÷ [0.3] +÷ 06DD ÷ 0000 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) ÷ [5.0] (Control) ÷ [0.3] +÷ 06DD × 0308 ÷ 0000 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (Control) ÷ [0.3] +÷ 06DD × 094D ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 06DD × 0308 × 094D ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 06DD × 0300 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 06DD × 0308 × 0300 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 06DD × 200C ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 06DD × 0308 × 200C ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 06DD × 200D ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 06DD × 0308 × 200D ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 06DD × 1F1E6 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 06DD × 0308 ÷ 1F1E6 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 06DD × 06DD ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.2] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 06DD × 0308 ÷ 06DD ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 06DD × 0903 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 06DD × 0308 × 0903 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 06DD × 1100 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.2] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 06DD × 0308 ÷ 1100 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 06DD × 1160 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.2] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 06DD × 0308 ÷ 1160 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 06DD × 11A8 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.2] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 06DD × 0308 ÷ 11A8 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 06DD × AC00 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.2] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 06DD × 0308 ÷ AC00 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 06DD × AC01 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.2] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 06DD × 0308 ÷ AC01 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 06DD × 0915 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.2] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 06DD × 0308 ÷ 0915 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 06DD × 00A9 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.2] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 06DD × 0308 ÷ 00A9 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 06DD × 0020 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.2] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 06DD × 0308 ÷ 0020 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 06DD × 0378 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.2] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 06DD × 0308 ÷ 0378 ÷ # ÷ [0.2] ARABIC END OF AYAH (Prepend) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0903 ÷ 000D ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [5.0] (CR) ÷ [0.3] +÷ 0903 × 0308 ÷ 000D ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (CR) ÷ [0.3] +÷ 0903 ÷ 000A ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [5.0] (LF) ÷ [0.3] +÷ 0903 × 0308 ÷ 000A ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (LF) ÷ [0.3] +÷ 0903 ÷ 0000 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [5.0] (Control) ÷ [0.3] +÷ 0903 × 0308 ÷ 0000 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (Control) ÷ [0.3] +÷ 0903 × 094D ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 0903 × 0308 × 094D ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 0903 × 0300 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 0903 × 0308 × 0300 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 0903 × 200C ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 0903 × 0308 × 200C ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 0903 × 200D ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 0903 × 0308 × 200D ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 0903 ÷ 1F1E6 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 0903 × 0308 ÷ 1F1E6 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 0903 ÷ 06DD ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 0903 × 0308 ÷ 06DD ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 0903 × 0903 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 0903 × 0308 × 0903 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 0903 ÷ 1100 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 0903 × 0308 ÷ 1100 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 0903 ÷ 1160 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 0903 × 0308 ÷ 1160 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 0903 ÷ 11A8 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 0903 × 0308 ÷ 11A8 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 0903 ÷ AC00 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 0903 × 0308 ÷ AC00 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 0903 ÷ AC01 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 0903 × 0308 ÷ AC01 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 0903 ÷ 0915 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 0903 × 0308 ÷ 0915 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 0903 ÷ 00A9 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 0903 × 0308 ÷ 00A9 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 0903 ÷ 0020 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0903 × 0308 ÷ 0020 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0903 ÷ 0378 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0903 × 0308 ÷ 0378 ÷ # ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 1100 ÷ 000D ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [5.0] (CR) ÷ [0.3] +÷ 1100 × 0308 ÷ 000D ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (CR) ÷ [0.3] +÷ 1100 ÷ 000A ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [5.0] (LF) ÷ [0.3] +÷ 1100 × 0308 ÷ 000A ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (LF) ÷ [0.3] +÷ 1100 ÷ 0000 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [5.0] (Control) ÷ [0.3] +÷ 1100 × 0308 ÷ 0000 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (Control) ÷ [0.3] +÷ 1100 × 094D ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 1100 × 0308 × 094D ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 1100 × 0300 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 1100 × 0308 × 0300 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 1100 × 200C ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 1100 × 0308 × 200C ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 1100 × 200D ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 1100 × 0308 × 200D ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 1100 ÷ 1F1E6 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 1100 × 0308 ÷ 1F1E6 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 1100 ÷ 06DD ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 1100 × 0308 ÷ 06DD ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 1100 × 0903 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 1100 × 0308 × 0903 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 1100 × 1100 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [6.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 1100 × 0308 ÷ 1100 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 1100 × 1160 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [6.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 1100 × 0308 ÷ 1160 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 1100 ÷ 11A8 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 1100 × 0308 ÷ 11A8 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 1100 × AC00 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [6.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 1100 × 0308 ÷ AC00 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 1100 × AC01 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [6.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 1100 × 0308 ÷ AC01 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 1100 ÷ 0915 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 1100 × 0308 ÷ 0915 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 1100 ÷ 00A9 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 1100 × 0308 ÷ 00A9 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 1100 ÷ 0020 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 1100 × 0308 ÷ 0020 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 1100 ÷ 0378 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 1100 × 0308 ÷ 0378 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 1160 ÷ 000D ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) ÷ [5.0] (CR) ÷ [0.3] +÷ 1160 × 0308 ÷ 000D ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (CR) ÷ [0.3] +÷ 1160 ÷ 000A ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) ÷ [5.0] (LF) ÷ [0.3] +÷ 1160 × 0308 ÷ 000A ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (LF) ÷ [0.3] +÷ 1160 ÷ 0000 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) ÷ [5.0] (Control) ÷ [0.3] +÷ 1160 × 0308 ÷ 0000 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (Control) ÷ [0.3] +÷ 1160 × 094D ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 1160 × 0308 × 094D ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 1160 × 0300 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 1160 × 0308 × 0300 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 1160 × 200C ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 1160 × 0308 × 200C ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 1160 × 200D ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 1160 × 0308 × 200D ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 1160 ÷ 1F1E6 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 1160 × 0308 ÷ 1F1E6 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 1160 ÷ 06DD ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 1160 × 0308 ÷ 06DD ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 1160 × 0903 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 1160 × 0308 × 0903 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 1160 ÷ 1100 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 1160 × 0308 ÷ 1100 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 1160 × 1160 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [7.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 1160 × 0308 ÷ 1160 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 1160 × 11A8 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [7.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 1160 × 0308 ÷ 11A8 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 1160 ÷ AC00 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 1160 × 0308 ÷ AC00 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 1160 ÷ AC01 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 1160 × 0308 ÷ AC01 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 1160 ÷ 0915 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 1160 × 0308 ÷ 0915 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 1160 ÷ 00A9 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 1160 × 0308 ÷ 00A9 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 1160 ÷ 0020 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 1160 × 0308 ÷ 0020 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 1160 ÷ 0378 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 1160 × 0308 ÷ 0378 ÷ # ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 11A8 ÷ 000D ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) ÷ [5.0] (CR) ÷ [0.3] +÷ 11A8 × 0308 ÷ 000D ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (CR) ÷ [0.3] +÷ 11A8 ÷ 000A ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) ÷ [5.0] (LF) ÷ [0.3] +÷ 11A8 × 0308 ÷ 000A ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (LF) ÷ [0.3] +÷ 11A8 ÷ 0000 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) ÷ [5.0] (Control) ÷ [0.3] +÷ 11A8 × 0308 ÷ 0000 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (Control) ÷ [0.3] +÷ 11A8 × 094D ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 11A8 × 0308 × 094D ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 11A8 × 0300 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 11A8 × 0308 × 0300 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 11A8 × 200C ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 11A8 × 0308 × 200C ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 11A8 × 200D ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 11A8 × 0308 × 200D ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 11A8 ÷ 1F1E6 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 11A8 × 0308 ÷ 1F1E6 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 11A8 ÷ 06DD ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 11A8 × 0308 ÷ 06DD ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 11A8 × 0903 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 11A8 × 0308 × 0903 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 11A8 ÷ 1100 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 11A8 × 0308 ÷ 1100 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 11A8 ÷ 1160 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 11A8 × 0308 ÷ 1160 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 11A8 × 11A8 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) × [8.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 11A8 × 0308 ÷ 11A8 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 11A8 ÷ AC00 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 11A8 × 0308 ÷ AC00 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 11A8 ÷ AC01 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 11A8 × 0308 ÷ AC01 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 11A8 ÷ 0915 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 11A8 × 0308 ÷ 0915 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 11A8 ÷ 00A9 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 11A8 × 0308 ÷ 00A9 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 11A8 ÷ 0020 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 11A8 × 0308 ÷ 0020 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 11A8 ÷ 0378 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 11A8 × 0308 ÷ 0378 ÷ # ÷ [0.2] HANGUL JONGSEONG KIYEOK (T) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ AC00 ÷ 000D ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) ÷ [5.0] (CR) ÷ [0.3] +÷ AC00 × 0308 ÷ 000D ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (CR) ÷ [0.3] +÷ AC00 ÷ 000A ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) ÷ [5.0] (LF) ÷ [0.3] +÷ AC00 × 0308 ÷ 000A ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (LF) ÷ [0.3] +÷ AC00 ÷ 0000 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) ÷ [5.0] (Control) ÷ [0.3] +÷ AC00 × 0308 ÷ 0000 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (Control) ÷ [0.3] +÷ AC00 × 094D ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ AC00 × 0308 × 094D ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ AC00 × 0300 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ AC00 × 0308 × 0300 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ AC00 × 200C ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ AC00 × 0308 × 200C ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ AC00 × 200D ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ AC00 × 0308 × 200D ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ AC00 ÷ 1F1E6 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ AC00 × 0308 ÷ 1F1E6 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ AC00 ÷ 06DD ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ AC00 × 0308 ÷ 06DD ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ AC00 × 0903 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ AC00 × 0308 × 0903 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ AC00 ÷ 1100 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ AC00 × 0308 ÷ 1100 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ AC00 × 1160 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [7.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ AC00 × 0308 ÷ 1160 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ AC00 × 11A8 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [7.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ AC00 × 0308 ÷ 11A8 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ AC00 ÷ AC00 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ AC00 × 0308 ÷ AC00 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ AC00 ÷ AC01 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ AC00 × 0308 ÷ AC01 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ AC00 ÷ 0915 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ AC00 × 0308 ÷ 0915 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ AC00 ÷ 00A9 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ AC00 × 0308 ÷ 00A9 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ AC00 ÷ 0020 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ AC00 × 0308 ÷ 0020 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ AC00 ÷ 0378 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ AC00 × 0308 ÷ 0378 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ AC01 ÷ 000D ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) ÷ [5.0] (CR) ÷ [0.3] +÷ AC01 × 0308 ÷ 000D ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (CR) ÷ [0.3] +÷ AC01 ÷ 000A ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) ÷ [5.0] (LF) ÷ [0.3] +÷ AC01 × 0308 ÷ 000A ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (LF) ÷ [0.3] +÷ AC01 ÷ 0000 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) ÷ [5.0] (Control) ÷ [0.3] +÷ AC01 × 0308 ÷ 0000 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (Control) ÷ [0.3] +÷ AC01 × 094D ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ AC01 × 0308 × 094D ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ AC01 × 0300 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ AC01 × 0308 × 0300 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ AC01 × 200C ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ AC01 × 0308 × 200C ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ AC01 × 200D ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ AC01 × 0308 × 200D ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ AC01 ÷ 1F1E6 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ AC01 × 0308 ÷ 1F1E6 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ AC01 ÷ 06DD ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ AC01 × 0308 ÷ 06DD ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ AC01 × 0903 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ AC01 × 0308 × 0903 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ AC01 ÷ 1100 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ AC01 × 0308 ÷ 1100 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ AC01 ÷ 1160 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ AC01 × 0308 ÷ 1160 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ AC01 × 11A8 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [8.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ AC01 × 0308 ÷ 11A8 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ AC01 ÷ AC00 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ AC01 × 0308 ÷ AC00 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ AC01 ÷ AC01 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ AC01 × 0308 ÷ AC01 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ AC01 ÷ 0915 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ AC01 × 0308 ÷ 0915 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ AC01 ÷ 00A9 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ AC01 × 0308 ÷ 00A9 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ AC01 ÷ 0020 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ AC01 × 0308 ÷ 0020 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ AC01 ÷ 0378 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ AC01 × 0308 ÷ 0378 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0915 ÷ 000D ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [5.0] (CR) ÷ [0.3] +÷ 0915 × 0308 ÷ 000D ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (CR) ÷ [0.3] +÷ 0915 ÷ 000A ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [5.0] (LF) ÷ [0.3] +÷ 0915 × 0308 ÷ 000A ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (LF) ÷ [0.3] +÷ 0915 ÷ 0000 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [5.0] (Control) ÷ [0.3] +÷ 0915 × 0308 ÷ 0000 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (Control) ÷ [0.3] +÷ 0915 × 094D ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 0915 × 0308 × 094D ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 0915 × 0300 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 0915 × 0308 × 0300 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 0915 × 200C ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 0915 × 0308 × 200C ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 0915 × 200D ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 0915 × 0308 × 200D ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 0915 ÷ 1F1E6 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 0915 × 0308 ÷ 1F1E6 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 0915 ÷ 06DD ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 0915 × 0308 ÷ 06DD ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 0915 × 0903 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 0915 × 0308 × 0903 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 0915 ÷ 1100 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 0915 × 0308 ÷ 1100 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 0915 ÷ 1160 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 0915 × 0308 ÷ 1160 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 0915 ÷ 11A8 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 0915 × 0308 ÷ 11A8 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 0915 ÷ AC00 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 0915 × 0308 ÷ AC00 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 0915 ÷ AC01 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 0915 × 0308 ÷ AC01 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 0915 ÷ 0915 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 0915 × 0308 ÷ 0915 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 0915 ÷ 00A9 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 0915 × 0308 ÷ 00A9 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 0915 ÷ 0020 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0915 × 0308 ÷ 0020 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0915 ÷ 0378 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0915 × 0308 ÷ 0378 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 00A9 ÷ 000D ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) ÷ [5.0] (CR) ÷ [0.3] +÷ 00A9 × 0308 ÷ 000D ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (CR) ÷ [0.3] +÷ 00A9 ÷ 000A ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) ÷ [5.0] (LF) ÷ [0.3] +÷ 00A9 × 0308 ÷ 000A ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (LF) ÷ [0.3] +÷ 00A9 ÷ 0000 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) ÷ [5.0] (Control) ÷ [0.3] +÷ 00A9 × 0308 ÷ 0000 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (Control) ÷ [0.3] +÷ 00A9 × 094D ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 00A9 × 0308 × 094D ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 00A9 × 0300 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 00A9 × 0308 × 0300 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 00A9 × 200C ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 00A9 × 0308 × 200C ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 00A9 × 200D ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 00A9 × 0308 × 200D ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 00A9 ÷ 1F1E6 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 00A9 × 0308 ÷ 1F1E6 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 00A9 ÷ 06DD ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 00A9 × 0308 ÷ 06DD ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 00A9 × 0903 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 00A9 × 0308 × 0903 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 00A9 ÷ 1100 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 00A9 × 0308 ÷ 1100 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 00A9 ÷ 1160 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 00A9 × 0308 ÷ 1160 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 00A9 ÷ 11A8 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 00A9 × 0308 ÷ 11A8 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 00A9 ÷ AC00 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 00A9 × 0308 ÷ AC00 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 00A9 ÷ AC01 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 00A9 × 0308 ÷ AC01 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 00A9 ÷ 0915 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 00A9 × 0308 ÷ 0915 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 00A9 ÷ 00A9 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 00A9 × 0308 ÷ 00A9 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 00A9 ÷ 0020 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 00A9 × 0308 ÷ 0020 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 00A9 ÷ 0378 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 00A9 × 0308 ÷ 0378 ÷ # ÷ [0.2] COPYRIGHT SIGN (ExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0020 ÷ 000D ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) ÷ [5.0] (CR) ÷ [0.3] +÷ 0020 × 0308 ÷ 000D ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (CR) ÷ [0.3] +÷ 0020 ÷ 000A ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) ÷ [5.0] (LF) ÷ [0.3] +÷ 0020 × 0308 ÷ 000A ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (LF) ÷ [0.3] +÷ 0020 ÷ 0000 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) ÷ [5.0] (Control) ÷ [0.3] +÷ 0020 × 0308 ÷ 0000 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (Control) ÷ [0.3] +÷ 0020 × 094D ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 0020 × 0308 × 094D ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 0020 × 0300 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 0020 × 0308 × 0300 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 0020 × 200C ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 0020 × 0308 × 200C ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 0020 × 200D ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 0020 × 0308 × 200D ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 0020 ÷ 1F1E6 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 0020 × 0308 ÷ 1F1E6 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 0020 ÷ 06DD ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 0020 × 0308 ÷ 06DD ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 0020 × 0903 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 0020 × 0308 × 0903 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 0020 ÷ 1100 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 0020 × 0308 ÷ 1100 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 0020 ÷ 1160 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 0020 × 0308 ÷ 1160 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 0020 ÷ 11A8 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 0020 × 0308 ÷ 11A8 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 0020 ÷ AC00 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 0020 × 0308 ÷ AC00 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 0020 ÷ AC01 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 0020 × 0308 ÷ AC01 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 0020 ÷ 0915 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 0020 × 0308 ÷ 0915 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 0020 ÷ 00A9 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 0020 × 0308 ÷ 00A9 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 0020 ÷ 0020 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0020 × 0308 ÷ 0020 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0020 ÷ 0378 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0020 × 0308 ÷ 0378 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0378 ÷ 000D ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) ÷ [5.0] (CR) ÷ [0.3] +÷ 0378 × 0308 ÷ 000D ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (CR) ÷ [0.3] +÷ 0378 ÷ 000A ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) ÷ [5.0] (LF) ÷ [0.3] +÷ 0378 × 0308 ÷ 000A ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (LF) ÷ [0.3] +÷ 0378 ÷ 0000 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) ÷ [5.0] (Control) ÷ [0.3] +÷ 0378 × 0308 ÷ 0000 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [5.0] (Control) ÷ [0.3] +÷ 0378 × 094D ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 0378 × 0308 × 094D ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [0.3] +÷ 0378 × 0300 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 0378 × 0308 × 0300 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING GRAVE ACCENT (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 0378 × 200C ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 0378 × 0308 × 200C ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH NON-JOINER (ExtendmConjunctLinkermConjunctExtender) ÷ [0.3] +÷ 0378 × 200D ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 0378 × 0308 × 200D ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 0378 ÷ 1F1E6 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 0378 × 0308 ÷ 1F1E6 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] +÷ 0378 ÷ 06DD ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 0378 × 0308 ÷ 06DD ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] ARABIC END OF AYAH (Prepend) ÷ [0.3] +÷ 0378 × 0903 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 0378 × 0308 × 0903 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] +÷ 0378 ÷ 1100 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 0378 × 0308 ÷ 1100 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 0378 ÷ 1160 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 0378 × 0308 ÷ 1160 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] +÷ 0378 ÷ 11A8 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 0378 × 0308 ÷ 11A8 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] +÷ 0378 ÷ AC00 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 0378 × 0308 ÷ AC00 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] +÷ 0378 ÷ AC01 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 0378 × 0308 ÷ AC01 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] +÷ 0378 ÷ 0915 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 0378 × 0308 ÷ 0915 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 0378 ÷ 00A9 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 0378 × 0308 ÷ 00A9 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] COPYRIGHT SIGN (ExtPict) ÷ [0.3] +÷ 0378 ÷ 0020 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0378 × 0308 ÷ 0020 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0378 ÷ 0378 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0378 × 0308 ÷ 0378 ÷ # ÷ [0.2] (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 000D × 000A ÷ 0061 ÷ 000A ÷ 0308 ÷ # ÷ [0.2] (CR) × [3.0] (LF) ÷ [4.0] LATIN SMALL LETTER A (XXmLinkingConsonantmExtPict) ÷ [5.0] (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 0061 × 0308 ÷ # ÷ [0.2] LATIN SMALL LETTER A (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 0020 × 200D ÷ 0646 ÷ # ÷ [0.2] SPACE (XXmLinkingConsonantmExtPict) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [999.0] ARABIC LETTER NOON (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0646 × 200D ÷ 0020 ÷ # ÷ [0.2] ARABIC LETTER NOON (XXmLinkingConsonantmExtPict) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [999.0] SPACE (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 1100 × 1100 ÷ # ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [6.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ AC00 × 11A8 ÷ 1100 ÷ # ÷ [0.2] HANGUL SYLLABLE GA (LV) × [7.0] HANGUL JONGSEONG KIYEOK (T) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ AC01 × 11A8 ÷ 1100 ÷ # ÷ [0.2] HANGUL SYLLABLE GAG (LVT) × [8.0] HANGUL JONGSEONG KIYEOK (T) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] +÷ 1F1E6 × 1F1E7 ÷ 1F1E8 ÷ 0062 ÷ # ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [12.0] REGIONAL INDICATOR SYMBOL LETTER B (RI) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER C (RI) ÷ [999.0] LATIN SMALL LETTER B (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0061 ÷ 1F1E6 × 1F1E7 ÷ 1F1E8 ÷ 0062 ÷ # ÷ [0.2] LATIN SMALL LETTER A (XXmLinkingConsonantmExtPict) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [13.0] REGIONAL INDICATOR SYMBOL LETTER B (RI) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER C (RI) ÷ [999.0] LATIN SMALL LETTER B (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0061 ÷ 1F1E6 × 1F1E7 × 200D ÷ 1F1E8 ÷ 0062 ÷ # ÷ [0.2] LATIN SMALL LETTER A (XXmLinkingConsonantmExtPict) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [13.0] REGIONAL INDICATOR SYMBOL LETTER B (RI) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER C (RI) ÷ [999.0] LATIN SMALL LETTER B (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0061 ÷ 1F1E6 × 200D ÷ 1F1E7 × 1F1E8 ÷ 0062 ÷ # ÷ [0.2] LATIN SMALL LETTER A (XXmLinkingConsonantmExtPict) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER B (RI) × [13.0] REGIONAL INDICATOR SYMBOL LETTER C (RI) ÷ [999.0] LATIN SMALL LETTER B (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0061 ÷ 1F1E6 × 1F1E7 ÷ 1F1E8 × 1F1E9 ÷ 0062 ÷ # ÷ [0.2] LATIN SMALL LETTER A (XXmLinkingConsonantmExtPict) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [13.0] REGIONAL INDICATOR SYMBOL LETTER B (RI) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER C (RI) × [13.0] REGIONAL INDICATOR SYMBOL LETTER D (RI) ÷ [999.0] LATIN SMALL LETTER B (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0061 × 200D ÷ # ÷ [0.2] LATIN SMALL LETTER A (XXmLinkingConsonantmExtPict) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [0.3] +÷ 0061 × 0308 ÷ 0062 ÷ # ÷ [0.2] LATIN SMALL LETTER A (XXmLinkingConsonantmExtPict) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] LATIN SMALL LETTER B (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0061 × 0903 ÷ 0062 ÷ # ÷ [0.2] LATIN SMALL LETTER A (XXmLinkingConsonantmExtPict) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [999.0] LATIN SMALL LETTER B (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0061 ÷ 0600 × 0062 ÷ # ÷ [0.2] LATIN SMALL LETTER A (XXmLinkingConsonantmExtPict) ÷ [999.0] ARABIC NUMBER SIGN (Prepend) × [9.2] LATIN SMALL LETTER B (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 1F476 × 1F3FF ÷ 1F476 ÷ # ÷ [0.2] BABY (ExtPict) × [9.0] EMOJI MODIFIER FITZPATRICK TYPE-6 (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] BABY (ExtPict) ÷ [0.3] +÷ 0061 × 1F3FF ÷ 1F476 ÷ # ÷ [0.2] LATIN SMALL LETTER A (XXmLinkingConsonantmExtPict) × [9.0] EMOJI MODIFIER FITZPATRICK TYPE-6 (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] BABY (ExtPict) ÷ [0.3] +÷ 0061 × 1F3FF ÷ 1F476 × 200D × 1F6D1 ÷ # ÷ [0.2] LATIN SMALL LETTER A (XXmLinkingConsonantmExtPict) × [9.0] EMOJI MODIFIER FITZPATRICK TYPE-6 (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] BABY (ExtPict) × [9.0] ZERO WIDTH JOINER (ZWJ) × [11.0] OCTAGONAL SIGN (ExtPict) ÷ [0.3] +÷ 1F476 × 1F3FF × 0308 × 200D × 1F476 × 1F3FF ÷ # ÷ [0.2] BABY (ExtPict) × [9.0] EMOJI MODIFIER FITZPATRICK TYPE-6 (Extend_ConjunctExtendermConjunctLinker) × [9.0] COMBINING DIAERESIS (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH JOINER (ZWJ) × [11.0] BABY (ExtPict) × [9.0] EMOJI MODIFIER FITZPATRICK TYPE-6 (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 1F6D1 × 200D × 1F6D1 ÷ # ÷ [0.2] OCTAGONAL SIGN (ExtPict) × [9.0] ZERO WIDTH JOINER (ZWJ) × [11.0] OCTAGONAL SIGN (ExtPict) ÷ [0.3] +÷ 0061 × 200D ÷ 1F6D1 ÷ # ÷ [0.2] LATIN SMALL LETTER A (XXmLinkingConsonantmExtPict) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [999.0] OCTAGONAL SIGN (ExtPict) ÷ [0.3] +÷ 2701 × 200D ÷ 2701 ÷ # ÷ [0.2] UPPER BLADE SCISSORS (XXmLinkingConsonantmExtPict) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [999.0] UPPER BLADE SCISSORS (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0061 × 200D ÷ 2701 ÷ # ÷ [0.2] LATIN SMALL LETTER A (XXmLinkingConsonantmExtPict) × [9.0] ZERO WIDTH JOINER (ZWJ) ÷ [999.0] UPPER BLADE SCISSORS (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0915 ÷ 0924 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) ÷ [999.0] DEVANAGARI LETTER TA (LinkingConsonant) ÷ [0.3] +÷ 0915 × 094D × 0924 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.3] DEVANAGARI LETTER TA (LinkingConsonant) ÷ [0.3] +÷ 0915 × 094D × 094D × 0924 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.3] DEVANAGARI LETTER TA (LinkingConsonant) ÷ [0.3] +÷ 0915 × 094D × 200D × 0924 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] ZERO WIDTH JOINER (ZWJ) × [9.3] DEVANAGARI LETTER TA (LinkingConsonant) ÷ [0.3] +÷ 0915 × 093C × 200D × 094D × 0924 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] DEVANAGARI SIGN NUKTA (Extend_ConjunctExtendermConjunctLinker) × [9.0] ZERO WIDTH JOINER (ZWJ) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.3] DEVANAGARI LETTER TA (LinkingConsonant) ÷ [0.3] +÷ 0915 × 093C × 094D × 200D × 0924 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] DEVANAGARI SIGN NUKTA (Extend_ConjunctExtendermConjunctLinker) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] ZERO WIDTH JOINER (ZWJ) × [9.3] DEVANAGARI LETTER TA (LinkingConsonant) ÷ [0.3] +÷ 0915 × 094D × 0924 × 094D × 092F ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.3] DEVANAGARI LETTER TA (LinkingConsonant) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.3] DEVANAGARI LETTER YA (LinkingConsonant) ÷ [0.3] +÷ 0915 × 094D ÷ 0061 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [999.0] LATIN SMALL LETTER A (XXmLinkingConsonantmExtPict) ÷ [0.3] +÷ 0061 × 094D ÷ 0924 ÷ # ÷ [0.2] LATIN SMALL LETTER A (XXmLinkingConsonantmExtPict) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [999.0] DEVANAGARI LETTER TA (LinkingConsonant) ÷ [0.3] +÷ 003F × 094D ÷ 0924 ÷ # ÷ [0.2] QUESTION MARK (XXmLinkingConsonantmExtPict) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) ÷ [999.0] DEVANAGARI LETTER TA (LinkingConsonant) ÷ [0.3] +÷ 0915 × 094D × 094D × 0924 ÷ # ÷ [0.2] DEVANAGARI LETTER KA (LinkingConsonant) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.0] DEVANAGARI SIGN VIRAMA (Extend_ConjunctLinker) × [9.3] DEVANAGARI LETTER TA (LinkingConsonant) ÷ [0.3] +÷ 0AB8 × 0AFB × 0ACD × 0AB8 × 0AFB ÷ # ÷ [0.2] GUJARATI LETTER SA (LinkingConsonant) × [9.0] GUJARATI SIGN SHADDA (Extend_ConjunctExtendermConjunctLinker) × [9.0] GUJARATI SIGN VIRAMA (Extend_ConjunctLinker) × [9.3] GUJARATI LETTER SA (LinkingConsonant) × [9.0] GUJARATI SIGN SHADDA (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 1019 × 1039 × 1018 ÷ 102C × 1037 ÷ # ÷ [0.2] MYANMAR LETTER MA (LinkingConsonant) × [9.0] MYANMAR SIGN VIRAMA (Extend_ConjunctLinker) × [9.3] MYANMAR LETTER BHA (LinkingConsonant) ÷ [999.0] MYANMAR VOWEL SIGN AA (XXmLinkingConsonantmExtPict) × [9.0] MYANMAR SIGN DOT BELOW (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 1004 × 103A × 1039 × 1011 × 1039 × 1011 ÷ # ÷ [0.2] MYANMAR LETTER NGA (LinkingConsonant) × [9.0] MYANMAR SIGN ASAT (Extend_ConjunctExtendermConjunctLinker) × [9.0] MYANMAR SIGN VIRAMA (Extend_ConjunctLinker) × [9.3] MYANMAR LETTER THA (LinkingConsonant) × [9.0] MYANMAR SIGN VIRAMA (Extend_ConjunctLinker) × [9.3] MYANMAR LETTER THA (LinkingConsonant) ÷ [0.3] +÷ 1B12 × 1B01 ÷ 1B32 × 1B44 × 1B2F ÷ 1B32 × 1B44 × 1B22 × 1B44 × 1B2C ÷ 1B32 × 1B44 × 1B22 × 1B38 ÷ # ÷ [0.2] BALINESE LETTER OKARA TEDUNG (XXmLinkingConsonantmExtPict) × [9.0] BALINESE SIGN ULU CANDRA (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] BALINESE LETTER SA (LinkingConsonant) × [9.0] BALINESE ADEG ADEG (Extend_ConjunctLinker) × [9.3] BALINESE LETTER WA (LinkingConsonant) ÷ [999.0] BALINESE LETTER SA (LinkingConsonant) × [9.0] BALINESE ADEG ADEG (Extend_ConjunctLinker) × [9.3] BALINESE LETTER TA (LinkingConsonant) × [9.0] BALINESE ADEG ADEG (Extend_ConjunctLinker) × [9.3] BALINESE LETTER YA (LinkingConsonant) ÷ [999.0] BALINESE LETTER SA (LinkingConsonant) × [9.0] BALINESE ADEG ADEG (Extend_ConjunctLinker) × [9.3] BALINESE LETTER TA (LinkingConsonant) × [9.0] BALINESE VOWEL SIGN SUKU (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 179F × 17D2 × 178F × 17D2 × 179A × 17B8 ÷ # ÷ [0.2] KHMER LETTER SA (LinkingConsonant) × [9.0] KHMER SIGN COENG (Extend_ConjunctLinker) × [9.3] KHMER LETTER TA (LinkingConsonant) × [9.0] KHMER SIGN COENG (Extend_ConjunctLinker) × [9.3] KHMER LETTER RO (LinkingConsonant) × [9.0] KHMER VOWEL SIGN II (Extend_ConjunctExtendermConjunctLinker) ÷ [0.3] +÷ 1B26 ÷ 1B17 × 1B44 × 1B13 ÷ # ÷ [0.2] BALINESE LETTER NA (LinkingConsonant) ÷ [999.0] BALINESE LETTER NGA (LinkingConsonant) × [9.0] BALINESE ADEG ADEG (Extend_ConjunctLinker) × [9.3] BALINESE LETTER KA (LinkingConsonant) ÷ [0.3] +÷ 1B27 ÷ 1B13 × 1B44 × 1B0B ÷ 1B0B × 1B04 ÷ # ÷ [0.2] BALINESE LETTER PA (LinkingConsonant) ÷ [999.0] BALINESE LETTER KA (LinkingConsonant) × [9.0] BALINESE ADEG ADEG (Extend_ConjunctLinker) × [9.3] BALINESE LETTER RA REPA (LinkingConsonant) ÷ [999.0] BALINESE LETTER RA REPA (LinkingConsonant) × [9.1] BALINESE SIGN BISAH (SpacingMark) ÷ [0.3] +÷ 1795 × 17D2 × 17AF ÷ 1798 ÷ # ÷ [0.2] KHMER LETTER PHA (LinkingConsonant) × [9.0] KHMER SIGN COENG (Extend_ConjunctLinker) × [9.3] KHMER INDEPENDENT VOWEL QE (LinkingConsonant) ÷ [999.0] KHMER LETTER MO (LinkingConsonant) ÷ [0.3] +÷ 17A0 × 17D2 × 17AB ÷ 1791 × 17D0 ÷ 1799 ÷ # ÷ [0.2] KHMER LETTER HA (LinkingConsonant) × [9.0] KHMER SIGN COENG (Extend_ConjunctLinker) × [9.3] KHMER INDEPENDENT VOWEL RY (LinkingConsonant) ÷ [999.0] KHMER LETTER TO (LinkingConsonant) × [9.0] KHMER SIGN SAMYOK SANNYA (Extend_ConjunctExtendermConjunctLinker) ÷ [999.0] KHMER LETTER YO (LinkingConsonant) ÷ [0.3] +# +# Lines: 766 +# +# EOF diff --git a/tests/test_parser.py b/tests/test_parser.py index 04c5524..6d9ae63 100644 --- a/tests/test_parser.py +++ b/tests/test_parser.py @@ -1,7 +1,11 @@ -"""Streaming VT500 parser, SGR subparameter, UTF-8, and C1 isolation tests.""" +"""Streaming VT500 parser, SGR subparameter, STRING_ESC, and encoding tests.""" from __future__ import annotations +import typing as t + +import pytest + import libvt from libvt.config import Limits from libvt.parser import ( @@ -9,6 +13,7 @@ ApcDispatch, CsiDispatch, DcsDispatch, + EscDispatch, OscDispatch, Parser, ParserState, @@ -82,8 +87,8 @@ def test_sgr_colon_subparameters_and_indexed_vs_ansi() -> None: assert cell_c.style == libvt.Style() -def test_utf8_0x9c_inside_osc_dcs_apc_does_not_break_out() -> None: - """UTF-8 ``0x9C`` continuation bytes never terminate string control payloads.""" +def test_utf8_c1_isolation_and_latin1_wire_mode() -> None: + """UTF-8 isolates ``0x80..0x9F`` and ``U+009B``; ``latin-1`` parses 8-bit ``C1``.""" title = "Build “日本” Ü 😜" assert 0x9C in title.encode("utf-8") @@ -92,6 +97,11 @@ def test_utf8_0x9c_inside_osc_dcs_apc_does_not_break_out() -> None: assert term.title == title assert term.text == "ok" + # UTF-8 encoded U+009B (0xC2 0x9B) never smuggles CSI into UTF-8 streams! + smuggled = Parser(encoding="utf-8").feed(b"\xc2\x9b31mSAFE") + assert _coalesce_prints(smuggled) == [Print("31mSAFE")] + assert libvt.strip(b"\xc2\x9b31mSAFE") == "31mSAFE" + parser = Parser() actions = parser.feed( b"\x1bPq" + title.encode("utf-8") + b"\x1b\\" @@ -103,13 +113,18 @@ def test_utf8_0x9c_inside_osc_dcs_apc_does_not_break_out() -> None: assert isinstance(actions[1], ApcDispatch) assert actions[1].data == title.encode("utf-8") - # Explicit 8-bit C1 opt-in handles single-byte CSI (0x9B) and OSC/ST (0x9D/0x9C). - c1_actions = Parser(c1_controls=True).feed(b"\x9b12;34H\x9d2;ascii\x9c") - assert len(c1_actions) == 2 - assert isinstance(c1_actions[0], CsiDispatch) - assert c1_actions[0].params.values == (12, 34) - assert c1_actions[0].final == ord("H") - assert c1_actions[1] == OscDispatch(2, b"ascii", b"\x9c") + # Legacy 8-bit Latin-1 mode handles C1 anywhere transitions and 0xA0..0xFF glyphs. + lat_parser = Parser(encoding="latin-1") + lat_actions = lat_parser.feed(b"\x1b[12\x9b3;4H\x9d2;caf\xe9\x9c\x8d\xe9") + assert lat_actions == [ + CsiDispatch(0, libvt.CsiParams((3, 4), 0, 0), b"", ord("H")), + OscDispatch(2, b"caf\xe9", b"\x9c"), + EscDispatch(b"", ord("M")), + Print("é"), + ] + + with pytest.raises(ValueError, match="unsupported parser encoding"): + Parser(encoding=t.cast("t.Any", "ebcdic")) def test_incomplete_utf8_flushed_before_c0_control() -> None: @@ -121,13 +136,36 @@ def test_incomplete_utf8_flushed_before_c0_control() -> None: assert term[1].text == " X" -def test_double_esc_st_and_oversized_payload_recovery() -> None: - """Double ``ESC`` aborts cleanly and oversized strings resynchronize.""" +def test_string_esc_abort_and_oversized_payload_recovery() -> None: + r"""``STRING_ESC`` aborts non-``\`` escapes cleanly and preserves DCS headers.""" + p = Parser() + p.feed(b"\x1b]2;pending\x1b") + assert p.state == ParserState.STRING_ESC + # Non-'\' byte ('c' -> RIS) discards unclosed OSC and dispatches ESC c! + acts = p.feed(b"c") + assert acts == [EscDispatch(b"", ord("c"))] + assert p.state == ParserState.GROUND + + # Ubiquitty OSC-G4 on Terminal: unclosed OSC 2 followed by ESC [ 31 m drops title. term = libvt.Terminal(rows=4, cols=20, limits=Limits(max_osc_bytes=16)) - # First ESC enters OSC_ESC; second ESC cancels OSC and begins ESC \ ST no-op. + term.feed(b"\x1b]2;unterminated\x1b[32mok") + assert term.title == "" + assert term.text == "ok" + assert term[0, 0].style.fg == AnsiColor.GREEN + + # Double ESC inside OSC cancels OSC and treats second ESC \ as standalone ST no-op. + term.reset() term.feed(b"\x1b]2;short\x1b\x1b\\after") + assert term.title == "" assert term.text == "after" + # Disabling tmux_passthrough on Parser aborts DCS tmux; on ESC ESC. + strict_dcs = Parser(tmux_passthrough=False).feed(b"\x1bPtmux;\x1b\x1b\\hi") + assert _coalesce_prints([a for a in strict_dcs if isinstance(a, Print)]) == [ + Print("hi"), + ] + assert not any(isinstance(a, DcsDispatch) for a in strict_dcs) + term.reset() term.feed(b"\x1b]2;" + (b"x" * 64) + b"\x07clean") assert term.title == "" diff --git a/tests/test_protocols_and_input.py b/tests/test_protocols_and_input.py index f98b7ee..461f946 100644 --- a/tests/test_protocols_and_input.py +++ b/tests/test_protocols_and_input.py @@ -11,6 +11,7 @@ from libvt.events import ( ClipboardWrite, ColorSchemeQueried, + Passthrough, ProgramStatusChanged, WorkingDirectoryChanged, ) @@ -31,11 +32,9 @@ def test_osc_7501_rex_grammar_hierarchy_urgency_and_queries() -> None: """Rex ``OSC 7501`` enforces grammar, hierarchy, urgency, and pruning.""" silent_term = libvt.Terminal(rows=4, cols=30) - # Query is silent by default when neither policy nor event consumer is attached. silent_term.feed(b"\x1b]7501;?\x07") assert silent_term.drain_replies() == b"" - # Attaching an event consumer enables capability replies mirroring BEL vs ST. term = libvt.Terminal(rows=6, cols=40, record_events=True) term.feed(b"\x1b]7501;?\x07") assert term.drain_replies().endswith(b"\x07") @@ -44,34 +43,28 @@ def test_osc_7501_rex_grammar_hierarchy_urgency_and_queries() -> None: assert reply_st.startswith(b"\x1b]7501;?:") assert reply_st.endswith(b"\x1b\\") - # OSC 9;4 fallback populates root status until native 7501 arrives. term.feed(b"\x1b]9;4;1;35\x07") assert term.program_status is not None assert term.program_status.state == StatusState.WORKING assert term.program_status.progress == 35 - # Native 7501 hierarchical tasks with base64 title/msg and ancestor app inheritance. b64_title = base64.b64encode("Compiling 日本".encode()).decode("ascii") term.feed( f"\x1b]7501;state=working:id=build:app=cargo:progress=50:title={b64_title}\x1b\\".encode(), ) term.feed(b"\x1b]7501;state=blocked:id=build/sign:kind=auth\x1b\\") - # ConEmu 9;4 is ignored once native 7501 has been observed. term.feed(b"\x1b]9;4;0\x07") child = term.program_statuses["build/sign"] assert child.effective_app == "cargo" assert child.kind == BlockKind.AUTH assert term.program_statuses["build"].title == "Compiling 日本" - # Priority: blocked outranks working! assert term.program_status == child - # Base64 title containing BiDi or C0 spoofing is rejected. spoof_b64 = base64.b64encode("ok\u202eevil".encode()).decode("ascii") term.feed(f"\x1b]7501;state=error:id=spoof:title={spoof_b64}\x1b\\".encode()) assert "spoof" not in term.program_statuses - # Secondary prompt OSC 133;A;k=s keeps active status; primary OSC 133;A clears root. term.feed(b"\x1b]7501;state=working\x1b\\") assert "" in term.program_statuses term.feed(b"\x1b]133;A;k=s\x07") @@ -79,7 +72,6 @@ def test_osc_7501_rex_grammar_hierarchy_urgency_and_queries() -> None: term.feed(b"\x1b]133;A\x07") assert "" not in term.program_statuses - # Process exit prunes working/blocked tasks while preserving terminal done/error. term.feed(b"\x1b]7501;state=done:id=lint\x1b\\") term.notify_process_exit() assert "lint" in term.program_statuses @@ -95,7 +87,7 @@ def test_osc_7501_rex_grammar_hierarchy_urgency_and_queries() -> None: def test_osc_133_abs_row_osc_7_osc_52_and_tmux_passthrough() -> None: - """``OSC 133`` ``abs_row``, ``OSC 7``/``52``, queries, and ``DCS tmux;`` unwrap.""" + """``OSC 133`` ``abs_row``, ``OSC 7`` ``cwd_uri``, and ``Passthrough`` policy.""" term = libvt.Terminal( rows=3, cols=20, @@ -114,21 +106,30 @@ def test_osc_133_abs_row_osc_7_osc_52_and_tmux_passthrough() -> None: assert [z.abs_row for z in zones] == sorted(z.abs_row for z in zones) assert zones[-1].exit_code == 0 - # OSC 7 file URI decoding (local host accepted, remote host ignored by default). + # OSC 7: localhost updates cwd & cwd_uri; remote updates cwd_uri only. term.feed(b"\x1b]7;file://localhost/tmp/my%20dir\x07") assert term.cwd == "/tmp/my dir" + assert term.cwd_uri == "file://localhost/tmp/my%20dir" term.feed(b"\x1b]7;file://remote-box.example/srv\x07") assert term.cwd == "/tmp/my dir" + assert term.cwd_uri == "file://remote-box.example/srv" + assert term.snapshot().cwd_uri == "file://remote-box.example/srv" + + # Empty OSC 7 clears both cwd and cwd_uri. + term.feed(b"\x1b]7;\x07") + assert term.cwd == "" + assert term.cwd_uri == "" - # OSC 52 write emits ClipboardWrite; '?' query is silent unless enabled. clip_b64 = base64.b64encode(b"copied").decode("ascii") term.feed(f"\x1b]52;c;{clip_b64}\x07\x1b]52;c;?\x07".encode("ascii")) assert term.drain_replies() == b"" events = term.drain_events() - assert any(isinstance(e, WorkingDirectoryChanged) for e in events) + assert ( + WorkingDirectoryChanged(uri="file://remote-box.example/srv", path="/srv") + in events + ) assert ClipboardWrite(selection="c", text="copied") in events - # XTVERSION, DECRQSS, XTGETTCAP, OSC 10/11, ?2031 / ?996n, and DCS tmux; unwrap. term.feed( b"\x1b[>q\x1bP$qm\x1b\\\x1bP+q544e\x1b\\\x1b]10;?\x07\x1b[?2031h\x1b[?996n", ) @@ -140,38 +141,46 @@ def test_osc_133_abs_row_osc_7_osc_52_and_tmux_passthrough() -> None: assert b"\x1b[?997;2n" in replies assert ColorSchemeQueried(scheme=libvt.ColorScheme.LIGHT) in term.drain_events() - # Unwrap 1-level (ST and BEL) and 2-level nested DCS tmux; passthrough. - term.feed(b"\x1bPtmux;\x1b\x1b]2;bel-title\x07\x1b\\") - assert term.title == "bel-title" - term.feed(b"\x1bPtmux;\x1b\x1b]7501;state=done:id=inner\x1b\x1b\\\x1b\\") - assert "inner" in term.program_statuses - term.feed( + # Default Policy(allow_passthrough=False) emits Passthrough without re-feeding. + term.feed(b"\x1bPtmux;\x1b\x1b]2;spoofed-title\x07\x1b\\") + assert term.title == "" + assert term.drain_events() == (Passthrough(data=b"\x1b]2;spoofed-title\x07"),) + + # Policy(allow_passthrough=True) emits Passthrough and evaluates nested payloads. + allow_term = libvt.Terminal( + rows=3, + cols=20, + policy=Policy(allow_passthrough=True), + record_events=True, + ) + allow_term.feed(b"\x1bPtmux;\x1b\x1b]2;bel-title\x07\x1b\\") + assert allow_term.title == "bel-title" + allow_term.feed(b"\x1bPtmux;\x1b\x1b]7501;state=done:id=inner\x1b\x1b\\\x1b\\") + assert "inner" in allow_term.program_statuses + allow_term.feed( b"\x1bPtmux;\x1b\x1bPtmux;" b"\x1b\x1b\x1b\x1b]7501;state=done:id=nested2\x1b\x1b\x1b\x1b\\" b"\x1b\x1b\\\x1b\\", ) - assert "nested2" in term.program_statuses + assert "nested2" in allow_term.program_statuses + assert any(isinstance(e, Passthrough) for e in allow_term.drain_events()) def test_kitty_keyboard_stack_and_input_encoding() -> None: """``KittyKeyboardStack`` isolates ``CSI u`` from ``SCORC`` and encodes input.""" term = libvt.Terminal(rows=4, cols=20) - # Save cursor at (1, 3), push Kitty DISAMBIGUATE, then restore cursor with CSI u. term.feed(b"\x1b[2;4H\x1b[s\x1b[>1u\x1b[1;1H\x1b[u\x1b[?u") assert term.cursor.row == 1 assert term.cursor.col == 3 assert term.kitty_keyboard_flags == KittyKeyboardFlags.DISAMBIGUATE assert term.drain_replies() == b"\x1b[?1u" - # Kitty CSI u key encoding vs DECCKM legacy encoding. assert term.encode(KeyEvent.parse("escape")) == b"\x1b[27u" assert term.encode(KeyEvent.parse("ctrl+a")) == b"\x1b[97;5u" - # Popping returns to legacy mode; DECCKM switches Up arrow from CSI A to SS3 A. term.feed(b"\x1b[<1u\x1b[?1h") assert term.encode(KeyEvent.parse("up")) == b"\x1bOA" - # Mouse SGR (?1006 + ?1000) and Focus (?1004). term.feed(b"\x1b[?1000;1006;1004h") click = MouseEvent( row=2, @@ -197,13 +206,11 @@ def test_paste_event_fail_closed_and_character_sanitize() -> None: term.feed(b"\x1b[?2004h") assert term.encode(PasteEvent("hello\nworld")) == b"\x1b[200~hello\nworld\x1b[201~" - # Classic .replace("\x1b[201~", "") smuggling vector fails closed! with pytest.raises(UnsafePasteError): term.encode(PasteEvent("safe\x1b[20\x1b[201~1~;evil\n")) - # Character-level sanitize strips ESC cleanly so no ESC [ 201 ~ can ever reassemble. sanitized = term.encode(PasteEvent("hi\x1b[20\x1b[201~1~", sanitize=True)) assert sanitized == b"\x1b[200~hi[20[201~1~\x1b[201~" - # Policy allow_clipboard_read remains default False. assert Policy().allow_clipboard_read is False + assert Policy().allow_passthrough is False diff --git a/tests/test_ucd_and_grid.py b/tests/test_ucd_and_grid.py index 2d41f63..a935b1a 100644 --- a/tests/test_ucd_and_grid.py +++ b/tests/test_ucd_and_grid.py @@ -2,18 +2,96 @@ from __future__ import annotations +import pathlib import random import time +import unicodedata import libvt -from libvt._ucd import WidthRole +from libvt._ucd import ( + EXT_PICT_BIT, + WidthRole, + display_width, + segment_graphemes, + ucd_lookup, +) from libvt.modes import Mode +def test_unicode_17_grapheme_break_test_vectors() -> None: + """All 766 official Unicode 17.0.0 ``GraphemeBreakTest.txt`` vectors pass.""" + fixture = ( + pathlib.Path(__file__).resolve().parent + / "fixtures" + / "GraphemeBreakTest-17.0.0.txt" + ) + count = 0 + for raw in fixture.read_text(encoding="utf-8").splitlines(): + line = raw.split("#", 1)[0].strip() + if not line: + continue + expected: list[str] = [] + for chunk in line.split("\u00f7"): + chunk = chunk.strip() + if not chunk: + continue + expected.append( + "".join(chr(int(tok, 16)) for tok in chunk.split("\u00d7")), + ) + text = "".join(expected) + assert segment_graphemes(text) == expected, raw + count += 1 + assert count == 766 + + +def test_unicode_17_stdlib_parity_when_available() -> None: + """Verify 0 property mismatches against Python 3.15+ Unicode 17 ``unicodedata``.""" + if unicodedata.unidata_version != "17.0.0" or not hasattr( + unicodedata, "grapheme_cluster_break" + ): + return + + gcb_names = ( + "Other", + "CR", + "LF", + "Control", + "Extend", + "ZWJ", + "Regional_Indicator", + "Prepend", + "SpacingMark", + "L", + "V", + "T", + "LV", + "LVT", + ) + incb_names = ("None", "Linker", "Consonant", "Extend") + gcb_fn = unicodedata.grapheme_cluster_break + incb_fn = unicodedata.indic_conjunct_break + ep_fn = unicodedata.extended_pictographic + + for cp in range(0x110000): + if 0xD800 <= cp <= 0xDFFF: + continue + ch = chr(cp) + word = ucd_lookup(cp) + assert gcb_names[(word >> 2) & 0x0F] == gcb_fn(ch), hex(cp) + assert incb_names[(word >> 6) & 0x03] == incb_fn(ch), hex(cp) + assert bool(word & EXT_PICT_BIT) == ep_fn(ch), hex(cp) + + def test_unicode_width_flags_zwj_incb_and_variation_selectors() -> None: """Flags, ZWJ emoji, Indic conjuncts, and VS15/VS16 obey ``?2027`` width rules.""" + # Non-emoji bases (ASCII 'a', CJK '日') ignore VS16/VS15 width overrides! + assert display_width("a\ufe0f") == 1 + assert display_width("日\ufe0e") == 2 + assert display_width("❤\ufe0f") == 2 + assert display_width("#\ufe0f\u20e3") == 2 + assert display_width("⌚\ufe0e") == 1 + term = libvt.Terminal(rows=4, cols=10) - # Two adjacent Regional Indicator flag pairs occupy 2 + 2 = 4 columns. term.feed("🇯🇵🇺🇸!".encode()) assert term.cursor.col == 5 assert term[0, 0].text == "🇯🇵" @@ -36,11 +114,21 @@ def test_unicode_width_flags_zwj_incb_and_variation_selectors() -> None: narrow_term.feed("abc❤️".encode()) assert narrow_term[0].text == "abc" assert narrow_term[0].wrapped is True + assert narrow_term[0, 3].width_role == WidthRole.SPACER_HEAD assert narrow_term[1, 0].text == "❤️" assert narrow_term[1, 0].width == 2 assert narrow_term.cursor.row == 1 assert narrow_term.cursor.col == 2 + # Overwriting (1, 0) with narrow 'Z' heals (0, 3) SPACER_HEAD and keeps wrapped. + narrow_term.feed(b"\x1b[2;1HZ") + assert narrow_term[0, 3].width_role == WidthRole.NARROW + assert narrow_term[0, 3].text == " " + assert narrow_term[0].wrapped is True + assert narrow_term[1, 0].text == "Z" + assert narrow_term[1, 1].text == " " + assert narrow_term[1, 1].width_role == WidthRole.NARROW + # Disabling ?2027 leaves narrow base + VS16 at width 1. legacy = libvt.Terminal(rows=2, cols=6) legacy.feed(b"\x1b[?2027l" + "❤\ufe0fX".encode()) @@ -57,7 +145,6 @@ def test_combining_mark_cap_and_cluster_anchor_invalidation() -> None: assert elapsed < 0.25 assert len(term[0, 0].text) == term.limits.max_grapheme_codepoints - # Moving cursor before sending a combining mark must NOT mutate the earlier cell. term.reset() term.feed(b"ab") term.feed(b"\x1b[1;1H" + "\u0301".encode()) @@ -71,49 +158,25 @@ def test_row_clear_range_ich_dch_wide_healing_and_frozen_rle() -> None: term.feed(b" \x1b[K") assert term.screen._rows[0].used == 3 - # ICH splitting wide cell at col=1 heals col=0 and clears wide head pushed to col=5. + # DCH clears pending_wrap and clears wrapped when shifting to right edge. + term.reset() + term.feed(b"12345678") + assert term[0].wrapped is True + term.feed(b"\x1b[1;6H!\x1b[P") + assert term.cursor.pending_wrap is False + assert term[0].wrapped is False + assert term[0].text == "12345" + term.reset() term.feed("日本語".encode()) term.feed(b"\x1b[1;2H\x1b[1@") - row0 = term.screen._rows[0] - for col in range(6): - role = ( - WidthRole((row0.attrs[col] >> 60) & 0b11) - if row0.attrs is not None - else WidthRole.NARROW - ) - if role == WidthRole.WIDE: - assert col + 1 < 6 - assert row0.attrs is not None - next_role = WidthRole((row0.attrs[col + 1] >> 60) & 0b11) - assert next_role == WidthRole.SPACER_TAIL - if role == WidthRole.SPACER_TAIL: - assert col > 0 - assert row0.attrs is not None - prev_role = WidthRole((row0.attrs[col - 1] >> 60) & 0b11) - assert prev_role == WidthRole.WIDE - - # DCH splitting wide pairs at col=1 heals col=0. + _assert_grid_invariants(term) + term.reset() term.feed("日本語".encode()) term.feed(b"\x1b[1;2H\x1b[2P") - row0 = term.screen._rows[0] - for col in range(6): - role = ( - WidthRole((row0.attrs[col] >> 60) & 0b11) - if row0.attrs is not None - else WidthRole.NARROW - ) - if role == WidthRole.WIDE: - assert row0.attrs is not None - assert ( - WidthRole((row0.attrs[col + 1] >> 60) & 0b11) == WidthRole.SPACER_TAIL - ) - if role == WidthRole.SPACER_TAIL: - assert row0.attrs is not None - assert WidthRole((row0.attrs[col - 1] >> 60) & 0b11) == WidthRole.WIDE + _assert_grid_invariants(term) - # Scroll styled + wide lines into FrozenRow RLE history and inspect runs/cells. term.reset() for idx in range(8): term.feed(f"\x1b[38;2;10;20;{idx * 20}m日{idx}\r\n".encode()) @@ -126,8 +189,9 @@ def test_row_clear_range_ich_dch_wide_healing_and_frozen_rle() -> None: def _assert_grid_invariants(term: libvt.Terminal) -> None: - """Assert cursor bounds and wide-cell head/tail pairing across active rows.""" + """Assert cursor bounds and wide-cell head/tail/spacer_head invariants.""" scr = term.screen + declrmm = term.modes.is_set(Mode.DECLRMM) assert 0 <= scr.cursor.row < scr.rows assert 0 <= scr.cursor.col < scr.cols for r_idx, raw_row in enumerate(scr._rows): @@ -145,6 +209,22 @@ def _assert_grid_invariants(term: libvt.Terminal) -> None: assert c_idx > 0, f"orphan SPACER_TAIL at ({r_idx}, 0)" head_role = WidthRole((raw_row.attrs[c_idx - 1] >> 60) & 0b11) assert head_role == WidthRole.WIDE + elif ( + role == WidthRole.SPACER_HEAD + and not declrmm + and c_idx == scr.cols - 1 + and r_idx + 1 < scr.rows + and raw_row.wrapped + ): + next_row = scr._rows[r_idx + 1] + next_role = ( + WidthRole((next_row.attrs[0] >> 60) & 0b11) + if next_row.attrs is not None + else WidthRole.NARROW + ) + assert next_role == WidthRole.WIDE, ( + f"stale SPACER_HEAD at ({r_idx}, {c_idx}) before {next_role}" + ) def test_randomized_invariants_400_trials() -> None: From 742256f89dccf2c3d7ba9bed61135f8a7cf467d4 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 21 Nov 2026 17:08:07 -0600 Subject: [PATCH 05/29] Aio(fix[pty]): Add TIOCSCTTY and boxed asserts why: Establish a real controlling terminal without preexec_fn and stop assert_screen() from stripping literal TUI box-drawing borders. what: - Acquire TIOCSCTTY, reset SIGPIPE, and propagate execvp OSError via an isolated -I -S child trampoline in open_pty() - Add tty_mode ("cooked"|"cbreak"|"raw") to open_pty() and vt_pty - Keep assert_screen() strictly literal and add assert_screen_box() --- README.md | 11 +-- conftest.py | 3 +- docs/quickstart.md | 18 ++++- src/libvt/aio.py | 131 +++++++++++++++++++++++++++++-- src/libvt/pytest_plugin.py | 13 +++- src/libvt/testing.py | 146 +++++++++++++++++++++++++++-------- tests/test_aio_and_pytest.py | 138 +++++++++++++++++++++++---------- 7 files changed, 369 insertions(+), 91 deletions(-) diff --git a/README.md b/README.md index 499546e..45307a3 100644 --- a/README.md +++ b/README.md @@ -21,11 +21,12 @@ zero-dependency, typed virtual terminal emulator and streaming VT parser `OSC 9;4` fallback), `OSC 133` semantic prompt zones, `OSC 7` working directory, `OSC 8` hyperlinks, `OSC 52` clipboard, `?2026` synchronized-output stepping, `DECRQM`, `DECRQSS`, `XTGETTCAP`, and - `DCS tmux;` passthrough unwrapping. + `DCS tmux;` passthrough events. - **Mode-aware input & testing**: Outbound key/mouse/focus/paste encoding (including Kitty `CSI u` and fail-closed bracketed paste), - `libvt.aio` stream and POSIX PTY helpers, `vt_*` pytest fixtures, and - boxed `assert_screen` diffs with `FlightRecorder` disassembly. + `libvt.aio` stream and controlling-TTY POSIX PTY helpers, `vt_*` + pytest fixtures, and `assert_screen` / `assert_screen_box` diffs with + `FlightRecorder` disassembly. ## Requirements @@ -81,10 +82,10 @@ Boxed visual assertions verify CJK wide-character alignment and cursor coordinates in tests: ```python ->>> from libvt.testing import assert_screen +>>> from libvt.testing import assert_screen_box >>> t = libvt.Terminal(rows=2, cols=8) >>> t.feed("日本ok\r\ndone".encode()) ->>> assert_screen( +>>> assert_screen_box( ... t, ... """ ... ┌────────┐ diff --git a/conftest.py b/conftest.py index 398742a..dd0026d 100644 --- a/conftest.py +++ b/conftest.py @@ -7,7 +7,7 @@ import pytest import libvt -from libvt.testing import assert_screen +from libvt.testing import assert_screen, assert_screen_box @pytest.fixture(autouse=True) @@ -17,3 +17,4 @@ def _seed_doctest_namespace(doctest_namespace: dict[str, t.Any]) -> None: doctest_namespace["Terminal"] = libvt.Terminal doctest_namespace["AnsiColor"] = libvt.AnsiColor doctest_namespace["assert_screen"] = assert_screen + doctest_namespace["assert_screen_box"] = assert_screen_box diff --git a/docs/quickstart.md b/docs/quickstart.md index 720399d..da82826 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -63,12 +63,24 @@ b'\x1b[200~line 1\nline 2\x1b[201~' ## Pytest assertions -{func}`libvt.testing.assert_screen` compares visible text and optional -cursor coordinates, accepting either plain lines or boxed diagrams: +{func}`libvt.testing.assert_screen` compares literal visible text (including +box-drawing borders) and optional cursor coordinates, while +{func}`libvt.testing.assert_screen_box` validates column-aligned `┌──┐` +diagrams and soft-wrap markers: ```python ->>> from libvt.testing import assert_screen +>>> from libvt.testing import assert_screen, assert_screen_box >>> term = libvt.Terminal(rows=2, cols=8) >>> term.feed("日本!\r\nok".encode()) >>> assert_screen(term, "日本!\nok", cursor=(1, 2)) +>>> assert_screen_box( +... term, +... """ +... ┌────────┐ +... │日本! │ +... │ok │ +... └────────┘ +... """, +... cursor=(1, 2), +... ) ``` diff --git a/src/libvt/aio.py b/src/libvt/aio.py index 78fc298..b53d163 100644 --- a/src/libvt/aio.py +++ b/src/libvt/aio.py @@ -5,7 +5,9 @@ import asyncio import collections.abc import contextlib +import dataclasses import os +import socket import struct import sys import time @@ -23,6 +25,67 @@ from libvt.input import InputEvent, KeyEvent, PasteEvent from libvt.terminal import FlightRecorder, Snapshot, Terminal +type TtyMode = t.Literal["cooked", "cbreak", "raw"] + +_PTY_TRAMPOLINE = ( + "import errno, fcntl, os, signal, sys, termios\n" + "err_fd = int(sys.argv[1])\n" + "try:\n" + " os.set_inheritable(err_fd, False)\n" + " if hasattr(termios, 'TIOCSCTTY'):\n" + " try:\n" + " fcntl.ioctl(0, termios.TIOCSCTTY, 0)\n" + " except OSError as exc:\n" + " if exc.errno not in (errno.EPERM, errno.EINVAL):\n" + " raise\n" + " signal.signal(signal.SIGPIPE, signal.SIG_DFL)\n" + " os.execvp(sys.argv[2], sys.argv[2:])\n" + "except BaseException as exc:\n" + " code = getattr(exc, 'errno', None)\n" + " if not isinstance(code, int):\n" + " code = errno.ENOEXEC\n" + " msg = getattr(exc, 'strerror', None) or str(exc)\n" + " os.write(err_fd, f'{code}:{msg}'.encode('utf-8', 'replace'))\n" + " os._exit(127)\n" +) + + +def _raise_exec_error(err_payload: bytes, cmd: str, default_errno: int) -> t.NoReturn: + code_s, _, err_msg = err_payload.decode("utf-8", "replace").partition(":") + err_no = int(code_s) if code_s.isdigit() else default_errno + raise OSError(err_no, err_msg or os.strerror(err_no), cmd) + + +async def _read_cloexec_pipe(loop: asyncio.AbstractEventLoop, fd: int) -> bytes: + """Read non-blocking *fd* until EOF without spawning executor threads.""" + chunks: list[bytes] = [] + done = loop.create_future() + + def _on_ready() -> None: + while True: + try: + data = os.read(fd, 4_096) + except BlockingIOError: + return + except OSError as exc: + loop.remove_reader(fd) + if not done.done(): + done.set_exception(exc) + return + if not data: + loop.remove_reader(fd) + if not done.done(): + done.set_result(b"".join(chunks)) + return + chunks.append(data) + + loop.add_reader(fd, _on_ready) + try: + return await done + finally: + with contextlib.suppress(Exception): + loop.remove_reader(fd) + class ReplyWriter(t.Protocol): """Structural writer protocol satisfied by :class:`asyncio.StreamWriter`.""" @@ -372,31 +435,56 @@ async def open_pty( scrollback: int = 2_000, env: collections.abc.Mapping[str, str] | None = None, cwd: str | os.PathLike[str] | None = None, + tty_mode: TtyMode = "cooked", profile: Profile = DEFAULT_PROFILE, policy: Policy = DEFAULT_POLICY, limits: Limits = DEFAULT_LIMITS, sync_timeout: float = 1.0, ) -> collections.abc.AsyncGenerator[PtySession]: - """Spawn *argv* on a POSIX pseudo-terminal driven by :class:`Terminal`.""" + """Spawn *argv* with a controlling POSIX PTY driven by :class:`Terminal`.""" if sys.platform == "win32": msg = "open_pty requires POSIX pty.openpty()" raise NotImplementedError(msg) - + if not argv: + msg = "argv must not be empty" + raise ValueError(msg) + if tty_mode not in ("cooked", "cbreak", "raw"): + msg = f"unsupported tty_mode: {tty_mode!r}" + raise ValueError(msg) + + import errno import fcntl import pty import termios + import tty + loop = asyncio.get_running_loop() master_fd, slave_fd = pty.openpty() + err_r, err_w = os.pipe() + slave_closed = False + err_w_closed = False + proc: asyncio.subprocess.Process | None = None try: fcntl.ioctl( slave_fd, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0), ) + if tty_mode == "cbreak": + tty.setcbreak(slave_fd) + elif tty_mode == "raw": + tty.setraw(slave_fd) os.set_blocking(master_fd, False) + os.set_blocking(err_r, False) child_env = dict(os.environ if env is None else env) child_env.setdefault("TERM", "xterm-256color") proc = await asyncio.create_subprocess_exec( + sys.executable, + "-I", + "-S", + "-c", + _PTY_TRAMPOLINE, + str(err_w), *argv, stdin=slave_fd, stdout=slave_fd, @@ -404,13 +492,44 @@ async def open_pty( cwd=cwd, env=child_env, start_new_session=True, + pass_fds=(err_w,), close_fds=True, ) + os.close(slave_fd) + slave_closed = True + os.close(err_w) + err_w_closed = True + + err_payload = await _read_cloexec_pipe(loop, err_r) + if err_payload: + await proc.wait() + _raise_exec_error(err_payload, argv[0], errno.ENOEXEC) except BaseException: - os.close(master_fd) + if proc is not None and proc.returncode is None: + with contextlib.suppress(ProcessLookupError): + proc.kill() + await proc.wait() + with contextlib.suppress(OSError): + os.close(master_fd) raise finally: - os.close(slave_fd) + if not slave_closed: + with contextlib.suppress(OSError): + os.close(slave_fd) + if not err_w_closed: + with contextlib.suppress(OSError): + os.close(err_w) + with contextlib.suppress(OSError): + os.close(err_r) + + eff_policy = policy + if policy == DEFAULT_POLICY: + fqdn = socket.gethostname().lower() + short = fqdn.partition(".")[0] + eff_policy = dataclasses.replace( + policy, + osc7_hosts=policy.osc7_hosts | frozenset({fqdn, short}), + ) recorder = FlightRecorder(max_bytes=limits.max_recorder_bytes) terminal = Terminal( @@ -418,7 +537,7 @@ async def open_pty( cols=cols, scrollback=scrollback, profile=profile, - policy=policy, + policy=eff_policy, limits=limits, recorder=recorder, ) @@ -428,7 +547,6 @@ async def open_pty( terminal=terminal, sync_timeout=sync_timeout, ) - loop = asyncio.get_running_loop() session._loop = loop loop.add_reader(master_fd, session._on_readable) try: @@ -441,5 +559,6 @@ async def open_pty( "AsyncTerminalStream", "PtySession", "ReplyWriter", + "TtyMode", "open_pty", ] diff --git a/src/libvt/pytest_plugin.py b/src/libvt/pytest_plugin.py index 8886b5f..042096c 100644 --- a/src/libvt/pytest_plugin.py +++ b/src/libvt/pytest_plugin.py @@ -11,7 +11,7 @@ import collections.abc import os - from libvt.aio import PtySession + from libvt.aio import PtySession, TtyMode from libvt.config import Limits, Policy, Profile from libvt.events import Event from libvt.parser import Parser @@ -48,6 +48,7 @@ def __call__( cols: int = 80, env: collections.abc.Mapping[str, str] | None = None, cwd: str | os.PathLike[str] | None = None, + tty_mode: TtyMode = "cooked", ) -> contextlib.AbstractAsyncContextManager[PtySession]: """Open a POSIX PTY subprocess session.""" @@ -128,8 +129,16 @@ def _spawn( cols: int = 80, env: collections.abc.Mapping[str, str] | None = None, cwd: str | os.PathLike[str] | None = None, + tty_mode: TtyMode = "cooked", ) -> contextlib.AbstractAsyncContextManager[PtySession]: - return open_pty(argv, rows=rows, cols=cols, env=env, cwd=cwd) + return open_pty( + argv, + rows=rows, + cols=cols, + env=env, + cwd=cwd, + tty_mode=tty_mode, + ) return _spawn diff --git a/src/libvt/testing.py b/src/libvt/testing.py index 8ed8da7..58656f3 100644 --- a/src/libvt/testing.py +++ b/src/libvt/testing.py @@ -114,13 +114,38 @@ def format_flight_recorder(target: Terminal) -> str: return "\n".join(lines) +def _raise_mismatch( + target: Terminal | Snapshot, + snap: Snapshot, + expected_box: str, + actual_box: str, + cursor: tuple[int, int] | None, +) -> None: + details = [ + "Screen state mismatch:", + f"cursor actual=({snap.cursor.row}, {snap.cursor.col})" + + (f" expected={cursor}" if cursor is not None else ""), + "Expected:", + expected_box, + "Actual:", + actual_box, + ] + if isinstance(target, Terminal): + details.append(format_flight_recorder(target)) + raise ScreenAssertionError("\n".join(details)) + + def assert_screen( target: Terminal | Snapshot, expected: str | collections.abc.Sequence[str], *, cursor: tuple[int, int] | None = None, ) -> None: - """Assert that *target*'s visible lines (and optional *cursor*) match *expected*. + """Assert that *target*'s literal visible text (and *cursor*) matches *expected*. + + Unlike :func:`assert_screen_box`, ``assert_screen`` never strips ``┌──┐`` + border glyphs, so applications drawing literal box-drawing borders match + verbatim. Parameters ---------- @@ -128,7 +153,7 @@ def assert_screen( Live terminal or immutable snapshot under test. expected : str | Sequence[str] Expected visible text (dedented when passed as a multi-line string) - or explicit sequence of row strings. + or explicit sequence of right-trimmed row strings. cursor : tuple[int, int] | None, optional Expected zero-based ``(row, col)`` cursor coordinates, if checked. @@ -140,25 +165,7 @@ def assert_screen( snap = target.snapshot() if isinstance(target, Terminal) else target if isinstance(expected, str): cleaned = textwrap.dedent(expected).removeprefix("\n").removesuffix("\n") - raw_lines = cleaned.split("\n") if cleaned else [] - if ( - len(raw_lines) >= 2 - and raw_lines[0].startswith("┌") - and raw_lines[0].endswith("┐") - and raw_lines[-1].startswith("└") - and raw_lines[-1].endswith("┘") - ): - unboxed: list[str] = [] - for box_ln in raw_lines[1:-1]: - body = box_ln.removeprefix("│") - body = body.removesuffix("W") - body = body.removesuffix("│").rstrip(" ") - unboxed.append(body) - while unboxed and unboxed[-1] == "": - unboxed.pop() - exp_lines = unboxed - else: - exp_lines = raw_lines + exp_lines = cleaned.split("\n") if cleaned else [] else: exp_lines = list(expected) @@ -181,24 +188,95 @@ def assert_screen( line = exp_lines[idx] if idx < len(exp_lines) else "" exp_box_lines.append(f"│{_pad_expected_line(line, preview_cols)}│") exp_box_lines.append(f"└{exp_border}┘") - expected_box = "\n".join(exp_box_lines) + _raise_mismatch(target, snap, "\n".join(exp_box_lines), actual_box, cursor) - details = [ - "Screen state mismatch:", - f"cursor actual=({snap.cursor.row}, {snap.cursor.col})" - + (f" expected={cursor}" if cursor is not None else ""), - "Expected:", - expected_box, - "Actual:", - actual_box, - ] - if isinstance(target, Terminal): - details.append(format_flight_recorder(target)) - raise ScreenAssertionError("\n".join(details)) + +def assert_screen_box( + target: Terminal | Snapshot, + expected: str, + *, + cursor: tuple[int, int] | None = None, +) -> None: + """Assert that *target* matches a ``┌──┐`` / ``│..│`` boxed diagram. + + Validates exact display-column width across every row, preserves interior + and trailing spaces as well as blank rows, and checks soft-wrap flags via + trailing ``│W`` markers outside the right pipe. + + Parameters + ---------- + target : Terminal | Snapshot + Live terminal or immutable snapshot under test. + expected : str + Boxed diagram matching :func:`format_screen_box` layout. + cursor : tuple[int, int] | None, optional + Expected zero-based ``(row, col)`` cursor coordinates, if checked. + + Raises + ------ + ValueError + When *expected* does not form a rectangular ``┌──┐`` / ``└──┘`` frame. + ScreenAssertionError + When screen dimensions, cell contents, soft-wrap flags, or cursor + coordinates differ from *expected*. + """ + cleaned = textwrap.dedent(expected).removeprefix("\n").removesuffix("\n") + raw_lines = cleaned.split("\n") if cleaned else [] + if len(raw_lines) < 3: + msg = "expected box must contain top border, >=1 row, and bottom border" + raise ValueError(msg) + + top = raw_lines[0] + bottom = raw_lines[-1] + if not (top.startswith("┌") and top.endswith("┐")): + msg = f"expected box top border must match '┌─...─┐', got {top!r}" + raise ValueError(msg) + top_bars = top[1:-1] + if not top_bars or any(ch != "─" for ch in top_bars): + msg = f"expected box top border must contain only '─', got {top!r}" + raise ValueError(msg) + box_cols = len(top_bars) + expected_bottom = f"└{'─' * box_cols}┘" + if bottom != expected_bottom: + msg = f"expected box bottom border {expected_bottom!r}, got {bottom!r}" + raise ValueError(msg) + + norm_lines = [top] + for r_idx, raw_row in enumerate(raw_lines[1:-1]): + if not raw_row.startswith("│"): + msg = f"box row {r_idx} missing leading '│': {raw_row!r}" + raise ValueError(msg) + if raw_row.endswith("│W"): + body = raw_row[1:-2] + wrap_suffix = "W" + elif raw_row.endswith("│"): + body = raw_row[1:-1] + wrap_suffix = "" + else: + msg = f"box row {r_idx} must end with '│' or '│W': {raw_row!r}" + raise ValueError(msg) + row_w = display_width(body) + if row_w != box_cols: + msg = ( + f"box row {r_idx} display width {row_w} != border width " + f"{box_cols}: {raw_row!r}" + ) + raise ValueError(msg) + norm_lines.append(f"│{sanitize_terminal_text(body)}│{wrap_suffix}") + norm_lines.append(bottom) + expected_box = "\n".join(norm_lines) + + snap = target.snapshot() if isinstance(target, Terminal) else target + actual_box = format_screen_box(snap) + cursor_ok = cursor is None or (snap.cursor.row, snap.cursor.col) == cursor + if actual_box == expected_box and cursor_ok: + return + _raise_mismatch(target, snap, expected_box, actual_box, cursor) __all__ = [ "assert_screen", + "assert_screen_box", "format_flight_recorder", "format_screen_box", ] diff --git a/tests/test_aio_and_pytest.py b/tests/test_aio_and_pytest.py index 8aeac53..fe71596 100644 --- a/tests/test_aio_and_pytest.py +++ b/tests/test_aio_and_pytest.py @@ -3,6 +3,9 @@ from __future__ import annotations import asyncio +import pathlib +import shutil +import socket import sys import pytest @@ -11,7 +14,7 @@ from libvt.aio import AsyncTerminalStream, open_pty from libvt.pytest_plugin import PtyFactory, TerminalFactory from libvt.terminal import FlightRecorder, Terminal -from libvt.testing import assert_screen +from libvt.testing import assert_screen, assert_screen_box class _MemoryWriter: @@ -46,13 +49,11 @@ async def test_async_terminal_stream_sync_coalescing_timeout_and_replies() -> No sync_timeout=0.05, ) - # Direct wait_for (without background start()) expires wedged ?2026h cleanly. reader.feed_data(b"base\x1b[?2026h\x1b[Hwedged\x1b[6n") snap = await stream.wait_for("wedged", timeout=0.5) assert snap[0].text == "wedged" assert bytes(writer.buffer) == b"\x1b[1;7R" - # Background pump task mode coalesces normal ?2026h ... ?2026l batches cleanly. async with AsyncTerminalStream( asyncio.StreamReader(), rows=4, @@ -65,77 +66,134 @@ async def test_async_terminal_stream_sync_coalescing_timeout_and_replies() -> No @pytest.mark.skipif(sys.platform == "win32", reason="POSIX pty required") -async def test_open_pty_and_vt_pty_live_posix_subprocess( +async def test_open_pty_controlling_tty_signals_tty_mode_and_errors( vt_pty: PtyFactory, ) -> None: - """``open_pty`` and ``vt_pty`` bridge live child processes and DSR replies.""" + """``open_pty`` sets ``TIOCSCTTY``, ``SIGWINCH``/``SIGINT``, and ``SIGPIPE``.""" + host = socket.gethostname() child_code = ( - "import sys, tty; " - "tty.setcbreak(sys.stdin.fileno()); " - "sys.stdout.write('\\x1b]7501;state=working:id=job\\x1b\\\\hello\\x1b[6n'); " - "sys.stdout.flush(); " - "reply = b''; " - "\nwhile not reply.endswith(b'R'):\n" + "import os, signal, sys\n" + "tty_fd = os.open('/dev/tty', os.O_RDWR)\n" + "os.close(tty_fd)\n" + "fg_ok = (os.tcgetpgrp(0) == os.getpid())\n" + "winch = False\n" + "def _on_winch(s, f):\n" + " global winch\n" + " winch = True\n" + "signal.signal(signal.SIGWINCH, _on_winch)\n" + f"sys.stdout.write('\\x1b]7;file://{host}/var/tmp\\x07')\n" + "sys.stdout.write('\\x1b]7501;state=working:id=job\\x1b\\\\')\n" + "sys.stdout.write(f'CTTY={fg_ok} \\x1b[6n')\n" + "sys.stdout.flush()\n" + "reply = b''\n" + "while not reply.endswith(b'R'):\n" " ch = sys.stdin.buffer.read(1)\n" " if not ch: break\n" " reply += ch\n" - "print(' DSR=' + repr(reply.decode('ascii', 'replace')), flush=True); " - "line = b''\n" - "while not line.endswith((b'\\r', b'\\n')):\n" - " b = sys.stdin.buffer.read(1)\n" - " if not b: break\n" - " line += b\n" - "print('ECHO=' + line.decode('utf-8').strip(), flush=True)" + "print('DSR=' + repr(reply.decode('ascii', 'replace')), flush=True)\n" + "while not winch:\n" + " signal.pause()\n" + "print('WINCH=1', flush=True)\n" + "try:\n" + " while True:\n" + " signal.pause()\n" + "except KeyboardInterrupt:\n" + " print('SIGINT=1', flush=True)\n" ) async with open_pty( (sys.executable, "-u", "-c", child_code), - rows=6, - cols=40, + rows=8, + cols=60, + tty_mode="cbreak", ) as pty_sess: - await pty_sess.wait_for("DSR='\\x1b[1;6R'", timeout=3.0) + await pty_sess.wait_for("DSR='\\x1b[1;11R'", timeout=3.0) + assert "CTTY=True" in pty_sess.terminal.text + assert pty_sess.terminal.cwd == "/var/tmp" assert "job" in pty_sess.terminal.program_statuses - pty_sess.resize(rows=8, cols=50) - pty_sess.send("ping") - pty_sess.send_key("enter") - snap = await pty_sess.wait_for("ECHO=ping", timeout=3.0) - assert "ECHO=ping" in snap.text - # After exit, active working status is pruned automatically. + pty_sess.resize(rows=10, cols=70) + await pty_sess.wait_for("WINCH=1", timeout=3.0) + pty_sess.send(b"\x03") + await pty_sess.wait_for("SIGINT=1", timeout=3.0) assert pty_sess.terminal.program_statuses == {} - async with vt_pty( - (sys.executable, "-c", "print('fixture-pty-ok')"), - rows=4, - cols=30, - ) as sess2: - await sess2.wait_for("fixture-pty-ok", timeout=3.0) + # Non-Python execvp targets inherit default SIGPIPE (not Python's SIG_IGN). + cat_bin = shutil.which("cat") + if cat_bin is not None and pathlib.Path("/proc/self/status").exists(): + async with vt_pty((cat_bin, "/proc/self/status"), rows=40, cols=80) as cat_sess: + snap = await cat_sess.wait_for("SigIgn:", timeout=3.0) + sig_ign_hex = next( + ln.split(":")[1].strip() for ln in snap.lines if ln.startswith("SigIgn:") + ) + sigpipe_bit = 1 << 12 # signal 13 (SIGPIPE) -> bit 12 + assert (int(sig_ign_hex, 16) & sigpipe_bit) == 0 + + # Missing executable raises FileNotFoundError in parent with zero PTY noise. + with pytest.raises(FileNotFoundError): + async with open_pty(("definitely-missing-libvt-command-xyz",)): + pass -def test_pytest_fixtures_and_assert_screen_diagnostics( +def test_assert_screen_literal_borders_and_assert_screen_box( vt_terminal: Terminal, vt_factory: TerminalFactory, vt_parser: libvt.Parser, vt_recorder: FlightRecorder, ) -> None: - """Fixtures construct clean instances and ``assert_screen`` escapes BiDi spoofs.""" + """``assert_screen`` keeps borders literal; ``assert_screen_box`` checks frames.""" assert vt_terminal.rows == 24 assert vt_terminal.cols == 80 assert vt_terminal.recorder is vt_recorder assert isinstance(vt_parser, libvt.Parser) - small = vt_factory(rows=2, cols=8) - small.feed("日本ok\r\nline2".encode()) + # Regression test: real DEC Special Graphics border passes assert_screen verbatim! + bordered = vt_factory(rows=3, cols=5) + bordered.feed(b"\x1b(0lqqqk\r\nx X x\r\nmqqqj\x1b(B") + assert bordered.text == "┌───┐\n│ X │\n└───┘" + assert_screen(bordered, bordered.text) assert_screen( + bordered, + """ + ┌───┐ + │ X │ + └───┘ + """, + ) + + # Boxed assertions verify column width, soft-wrap 'W', and literal 'W' inside cells. + small = vt_factory(rows=2, cols=8) + small.feed("日本ok\r\nline2 W".encode()) + assert_screen_box( small, - "┌────────┐\n│日本ok │\n│line2 │\n└────────┘", + """ + ┌────────┐ + │日本ok │ + │line2 W│ + └────────┘ + """, + ) + + wrapped = vt_factory(rows=2, cols=4) + wrapped.feed(b"abcdef") + assert_screen_box( + wrapped, + """ + ┌────┐ + │abcd│W + │ef │ + └────┘ + """, + cursor=(1, 2), ) - # BiDi spoofing in cells is escaped in failure diffs alongside FlightRecorder dump. + with pytest.raises(ValueError, match="display width"): + assert_screen_box(small, "┌────┐\n│short│\n└────┘") + spoof_term = vt_factory(rows=1, cols=10, recorder=vt_recorder) spoof_term.feed(b"\x1b[31mhi") spoof_term.screen._rows[0].chars[2] = "\u202e" spoof_term.screen._rows[0].used = 3 with pytest.raises(AssertionError) as exc_info: - assert_screen(spoof_term, "┌──────────┐\n│mismatch │\n└──────────┘") + assert_screen_box(spoof_term, "┌──────────┐\n│mismatch │\n└──────────┘") msg = str(exc_info.value) assert "\\u202e" in msg assert "Flight Recorder:" in msg From eadf3ac74516ac3a857d61a08e23b7dd5ea81809 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 21 Nov 2026 17:09:03 -0600 Subject: [PATCH 06/29] Docs(docs[adr]): Sync ADRs and changelog why: Keep ADR specifications, topic guides, and CHANGES aligned with the shipped public API and security policy defaults. what: - Update ADRs 0002, 0005, 0007, and 0010 for STRING_ESC, Passthrough, pinned Unicode 17.0.0 UCD, OSC 7 hosts, TIOCSCTTY, and boxed asserts - Update architecture, asyncio, and CHANGES entries --- CHANGES | 23 ++++++------ ...ns-io-layers-profiles-and-closed-events.md | 7 ++-- ...isolation-and-unicode-17-grapheme-width.md | 35 ++++++++++--------- ...501-program-status-and-semantic-prompts.md | 10 +++--- ...ly-asyncio-and-diagnostic-pytest-plugin.md | 34 ++++++++++-------- docs/topics/architecture.md | 8 ++--- docs/topics/sync-and-asyncio.md | 7 ++-- 7 files changed, 70 insertions(+), 54 deletions(-) diff --git a/CHANGES b/CHANGES index fb38220..715a406 100644 --- a/CHANGES +++ b/CHANGES @@ -24,11 +24,13 @@ subcommands. ITU T.416 SGR subparameters (`4:3`, `38:2::R:G:B`, `58:5:idx`), `G0`–`G3` character-set designations (`ESC ( 0` DEC Special Graphics, `SO`/`SI`, `SS2`/`SS3`), `CBT`/`CHT`, `DECSCA`/`DECSED`/`DECSEL`, `CSI 22 J`, and -`DCS tmux;` passthrough unwrapping while isolating UTF-8 `0x9C` bytes -from 8-bit `C1` string terminators. Bundled Unicode 17.0.0 two-stage -tables drive East Asian width and DEC `?2027` grapheme clustering across -ZWJ emoji, Regional Indicator flag pairs, Indic conjuncts, and `VS15` / -`VS16` variation selectors. See {doc}`topics/architecture` for details. +`DCS tmux;` passthrough framing while isolating UTF-8 `0x9C` and `U+009B` +bytes from 8-bit `C1` controls (with optional `encoding="latin-1"` 8-bit +wire mode). SHA-256-pinned Unicode 17.0.0 two-stage tables drive East +Asian width and DEC `?2027` UAX #29 grapheme clustering across ZWJ +emoji, Regional Indicator flag pairs, Indic conjuncts, Hangul jamo, and +`VS15` / `VS16` emoji variation sequences. See {doc}`topics/architecture` +for details. #### Synchronized output stepping, Rex `OSC 7501`, and host queries (#2) @@ -63,11 +65,12 @@ and `SGR-Pixel` mouse tracking (`?1006`, `?1016`), and fail-closed bracketed paste validation raising {exc}`~libvt.exc.UnsafePasteError`. {class}`~libvt.aio.AsyncTerminalStream` and {func}`~libvt.aio.open_pty` -connect sans-I/O terminals to `asyncio` streams and POSIX pseudo-terminals -without importing `asyncio` or `pty` on `import libvt`. The `pytest11` -plugin provides protocol-typed `vt_terminal`, `vt_factory`, `vt_parser`, -`vt_recorder`, and `vt_pty` fixtures alongside -{func}`~libvt.testing.assert_screen` and +connect sans-I/O terminals to `asyncio` streams and controlling POSIX +pseudo-terminals (`TIOCSCTTY` and `tty_mode`) without importing `asyncio` +or `pty` on `import libvt`. The `pytest11` plugin provides +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`, and {class}`~libvt.terminal.FlightRecorder` diagnostics. See {doc}`topics/sync-and-asyncio` for details. diff --git a/docs/project/adr/0002-sans-io-layers-profiles-and-closed-events.md b/docs/project/adr/0002-sans-io-layers-profiles-and-closed-events.md index 3f3b448..19cb319 100644 --- a/docs/project/adr/0002-sans-io-layers-profiles-and-closed-events.md +++ b/docs/project/adr/0002-sans-io-layers-profiles-and-closed-events.md @@ -61,9 +61,10 @@ security gates (`Policy`), resource bounds (`Limits`), outbound wire replies `DEFAULT_PROFILE` (`XTERM_PROFILE`) and `TMUX_PROFILE`. - `Policy`: Default-deny host security gates (`allow_title_report=False`, `allow_checksum_report=False`, `allow_clipboard_read=False`, - `allow_clipboard_write=False`, `allow_color_queries=True`, + `allow_clipboard_write=True`, `allow_color_queries=True`, `allow_program_status_query=False`, `allow_unsafe_uris=False`, - `unwrap_tmux_passthrough=True`, `strict=False`). + `allow_passthrough=False`, `osc7_hosts=frozenset({"", "localhost"})`, + `strict=False`). - `Limits`: Hard memory and CPU bounds (`max_grapheme_codepoints=32`, `max_csi_params=32`, `max_osc_bytes=131_072`, `max_dcs_bytes=4_194_304`, `max_apc_bytes=4_194_304`, `max_reply_bytes=65_536`, @@ -80,7 +81,7 @@ security gates (`Policy`), resource bounds (`Limits`), outbound wire replies - `type Event = Bell | TitleChanged | WorkingDirectoryChanged | ClipboardWrite | PromptMark | ProgramStatusChanged | RenderHoldChanged | ColorSchemeQueried | InBandResize | SixelGraphic | KittyGraphic | - ScreenErased | UnhandledSequence`. + ScreenErased | Passthrough | UnhandledSequence`. - Callers either pass `on_event: Callable[[Event], None]` (push) or set `record_events: bool = True` and call `term.drain_events() -> tuple[Event, ...]` (pull). When neither is enabled, `feed()` allocates diff --git a/docs/project/adr/0005-utf8-c1-isolation-and-unicode-17-grapheme-width.md b/docs/project/adr/0005-utf8-c1-isolation-and-unicode-17-grapheme-width.md index 46441bf..8bc6745 100644 --- a/docs/project/adr/0005-utf8-c1-isolation-and-unicode-17-grapheme-width.md +++ b/docs/project/adr/0005-utf8-c1-isolation-and-unicode-17-grapheme-width.md @@ -38,17 +38,19 @@ framing hazards in terminal emulators: ## Decision -1. **7-bit string termination by default in UTF-8 streams (`libvt.parser`)**: - - `Parser(c1_controls: bool = False)` ignores raw `0x80..0x9F` 8-bit `C1` - bytes as control introducers/terminators unless `c1_controls=True` is - explicitly requested for legacy 8-bit Latin-1 streams. `OSC` terminates on - `BEL` (`0x07`) or 7-bit `ESC \` (`0x1B 0x5C`), and `DCS`/`APC`/`SOS`/`PM` - terminate strictly on `ESC \`, matching `tmux` (`input.c`) and `Ghostty`. +1. **`STRING_ESC` 7-bit string termination and separated wire modes (`libvt.parser`)**: + - `Parser(encoding="utf-8")` ignores raw `0x80..0x9F` 8-bit `C1` bytes and + UTF-8-encoded `U+0080..U+009F` (`0xC2 0x80..0x9F`) as control introducers; + `Parser(encoding="latin-1")` provides complete 8-bit DEC `C1` `anywhere` + transitions for legacy Latin-1 byte streams. + - `OSC`, `DCS`, and `APC`/`SOS`/`PM` transition on `0x1B` into a dedicated + `ParserState.STRING_ESC` substate: `\` (`0x5C`) dispatches with `DCS` + header intermediates intact, `0x1B` inside a latched `DCS tmux;` envelope + collapses `ESC ESC` into one payload `ESC` byte, and any other byte aborts + and discards the unclosed payload per DEC STD 070 §5.1.2.3 before + re-evaluating that byte in `ESCAPE`. - Incomplete UTF-8 sequences flush `U+FFFD` *before* executing any C0 control (`< 0x20`), `ESC`, `CAN` (`0x18`), or `SUB` (`0x1A`). - - A second `ESC` inside `ESCAPE` when `_return_from_esc_st` is set aborts - the pending control string cleanly before entering `ESCAPE` so `ESC ESC \` - never dispatches a cancelled `OSC`. 2. **Strict `_last_printed_pos` invalidation and `O(1)` combining cap**: - Any cursor motion, C0 execution, erase, scroll, resize, reset, or screen switch clears `_last_printed_pos = None`. @@ -60,13 +62,14 @@ framing hazards in terminal emulators: soft-wraps to the next line, and writes the widened 2-column cluster at `left` (`col 0`). `VS15` (`\ufe0e`) narrows default-wide emoji to `1` column under `?2027`. -3. **Generated two-stage Unicode 17.0 block table (`libvt._ucd`)**: - - `scripts/generate_ucd.py` compiles Unicode 17.0 East Asian Width, - `General_Category`, `Extended_Pictographic`, `Regional_Indicator`, - variation selectors, and `InCB` (`Consonant`, `Linker`, `Extend`) into a - compact zlib-compressed base85 2-stage 256-codepoint block table in - `libvt._ucd` (`stage2[(stage1[cp >> 8] << 8) | (cp & 0xFF)]`, `~90 KiB` - unpacked `bytes` in RAM, zero runtime dependencies). +3. **SHA-256-pinned Unicode 17.0.0 two-stage block table (`libvt._ucd`)**: + - `scripts/generate_ucd.py` compiles official SHA-256-verified Unicode 17.0.0 + UCD and Emoji data (`GraphemeBreakProperty.txt`, `DerivedCoreProperties.txt`, + `EastAsianWidth.txt`, `DerivedGeneralCategory.txt`, `emoji-data.txt`, and + `emoji-variation-sequences.txt`) into a zlib-compressed base85 2-stage + 256-codepoint `u16` block table in `libvt._ucd` (`~70.5 KiB` unpacked, + zero runtime dependencies), validated in `pytest` against all official + `GraphemeBreakTest.txt` vectors. - Python 3.12, 3.13, 3.14, and 3.15 therefore compute identical cell widths and UAX #29 `?2027` cluster boundaries (`GB9`, `GB9a`, `GB9c` Indic conjuncts, `GB11` ZWJ pictographics, and `GB12`/`GB13` Regional Indicator diff --git a/docs/project/adr/0007-rex-osc-7501-program-status-and-semantic-prompts.md b/docs/project/adr/0007-rex-osc-7501-program-status-and-semantic-prompts.md index e65eeaf..cf36ef6 100644 --- a/docs/project/adr/0007-rex-osc-7501-program-status-and-semantic-prompts.md +++ b/docs/project/adr/0007-rex-osc-7501-program-status-and-semantic-prompts.md @@ -71,15 +71,17 @@ capability query: exit_code: int | None)` in a `collections.deque` bounded by `Limits.max_prompt_zones` (`1,024`), updating viewport `row` via `abs_row - scr.scrolled_total` so scrolling never desyncs prompt zones. - - Support `OSC 7` and `OSC 9;9` (`term.cwd` + `WorkingDirectoryChanged`), - `OSC 52` write (`ClipboardWrite` when `Policy.allow_clipboard_write` or - recorded as event; `OSC 52 ; c ; ?` denied unless + - Support `OSC 7` and `OSC 9;9` (`term.cwd_uri` for any URI, `term.cwd` + filtered by `Policy.osc7_hosts` without host syscalls, plus + `WorkingDirectoryChanged`), `OSC 52` write (`ClipboardWrite` when + `Policy.allow_clipboard_write`; `OSC 52 ; c ; ?` denied unless `Policy.allow_clipboard_read`), `XTVERSION` (`CSI > q` -> `DCS > | ... ST`), `DECRQSS` (`DCS $ q ... ST` for `m` SGR, `r` `DECSTBM`, `s` `DECSLRM`, ` q` `DECSCUSR`, `"q` `DECSCA`), `XTGETTCAP` (`DCS + q ST` for `TN`/`Co`/`RGB`/`Smulx`), `OSC 10;?` / `OSC 11;?` foreground/background queries, `?2031` + `CSI ? 996 n` color-scheme DSR, and `DCS tmux; ESC ESC - ... ST` passthrough unwrapping (gated by `Policy.unwrap_tmux_passthrough`). + ... ST` passthrough envelopes (emitting `Passthrough` and re-feeding inner + bytes only when `Policy.allow_passthrough=True`). ## Alternatives considered diff --git a/docs/project/adr/0010-transport-only-asyncio-and-diagnostic-pytest-plugin.md b/docs/project/adr/0010-transport-only-asyncio-and-diagnostic-pytest-plugin.md index 9b995b5..1042e77 100644 --- a/docs/project/adr/0010-transport-only-asyncio-and-diagnostic-pytest-plugin.md +++ b/docs/project/adr/0010-transport-only-asyncio-and-diagnostic-pytest-plugin.md @@ -42,13 +42,17 @@ empirical testing: pairs, flushing `drain_replies()` automatically and enforcing `sync_timeout` via `Terminal.expire_synchronized_output(sync_gen)` in both background-task (`async with`) and on-demand `wait_for()` modes. - - `open_pty(argv, *, rows=24, cols=80, env=None, cwd=None)` spawns a child - process attached to a stdlib `pty.openpty()` master/slave pair on POSIX, - sets `TIOCSWINSZ`, pumps output + `drain_replies()`, and exposes - `send()`, `send_key()`, `paste()`, `resize()`, and `wait_for()`. On - Windows (`sys.platform == "win32"`), `open_pty()` raises - `NotImplementedError` cleanly while the entire Sans-I/O core works - unchanged. + - `open_pty(argv, *, rows=24, cols=80, env=None, cwd=None, tty_mode="cooked")` + spawns a child process attached to a stdlib `pty.openpty()` master/slave + pair via an isolated `-I -S` child trampoline (`start_new_session=True`, + `TIOCSCTTY` controlling terminal acquisition, `SIGPIPE` reset to + `SIG_DFL`, and `CLOEXEC` `err_fd` exec-failure propagation without + `preexec_fn`), configures `TIOCSWINSZ` and optional `"cbreak"` / `"raw"` + termios modes, augments default `Policy.osc7_hosts` with the local + hostname, pumps output + `drain_replies()`, and exposes `send()`, + `send_key()`, `paste()`, `resize()`, and `wait_for()`. On Windows + (`sys.platform == "win32"`), `open_pty()` raises `NotImplementedError` + cleanly while the entire Sans-I/O core works unchanged. 3. **Strictly `vt_`-prefixed, `Protocol`-typed `pytest11` plugin (`libvt.pytest_plugin`)**: - Register `vt_terminal`, `vt_factory` (typed via `TerminalFactory` @@ -56,14 +60,16 @@ empirical testing: `vt_parser`, `vt_recorder` (`FlightRecorder`), and `vt_pty` (calling `pytest.skip("POSIX pty required")` on `win32`), with lazy imports inside fixture bodies. -4. **Column-exact, sanitized `assert_screen` and `FlightRecorder` +4. **Literal `assert_screen`, column-exact `assert_screen_box`, and `FlightRecorder` (`libvt.testing`)**: - - `format_screen_box` and `assert_screen` measure cells by terminal display - width (`WidthRole` / `display_width`), sanitize C0/C1 and BiDi overrides, - display `W` soft-wrap markers, and append `FlightRecorder` diagnostics - (cursor, active modes, `OSC 7501` status, `Parser.state`, and disassembled - recent raw bytes via `format_explain`) when a `FlightRecorder` is attached - to `Terminal`. + - `assert_screen` compares literal screen text without stripping `┌──┐` + borders rendered by applications, while `format_screen_box` and + `assert_screen_box` measure cells by terminal display width (`WidthRole` / + `display_width`), sanitize C0/C1 and BiDi overrides, validate outer `│W` + soft-wrap markers, and append `FlightRecorder` diagnostics (cursor, active + modes, `OSC 7501` status, `Parser.state`, and disassembled recent raw + bytes via `format_explain`) when a `FlightRecorder` is attached to + `Terminal`. - `Snapshot.to_dict()` returns a deterministic JSON-compatible dictionary for snapshot testing (`inline-snapshot` / `syrupy`). diff --git a/docs/topics/architecture.md b/docs/topics/architecture.md index 9e7ac49..9ffc258 100644 --- a/docs/topics/architecture.md +++ b/docs/topics/architecture.md @@ -5,10 +5,10 @@ `libvt` separates terminal emulation into four acyclic layers so callers import only the machinery they need: -1. **Streaming parser** ({mod}`libvt.parser`): 14-state VT500 byte - machine with colon-subparameter `CSI` bitmasks, incremental UTF-8 - decoding, 7-bit string termination, and `DCS tmux;` `ESC ESC` - collapsing. +1. **Streaming parser** ({mod}`libvt.parser`): VT500 byte state machine + with colon-subparameter `CSI` bitmasks, incremental UTF-8 decoding, + `STRING_ESC` 7-bit string termination, optional Latin-1 8-bit `C1` + wire parsing, and `DCS tmux;` `ESC ESC` collapsing. 2. **Grid and screen model** ({mod}`libvt.screen`): Zero-based `(row, col)` viewport with lazy 64-bit `array('Q')` attribute words, wide-spacer boundary healing, run-length-encoded scrollback rows, and diff --git a/docs/topics/sync-and-asyncio.md b/docs/topics/sync-and-asyncio.md index 7075964..5454653 100644 --- a/docs/topics/sync-and-asyncio.md +++ b/docs/topics/sync-and-asyncio.md @@ -52,7 +52,8 @@ and POSIX pseudo-terminals without adding background threads to the core: `asyncio.StreamReader`, flushes {meth}`~libvt.terminal.Terminal.drain_replies` to an optional writer, and coalesces `wait_for(...)` wakeups across `?2026` batches up to `sync_timeout`. -- {func}`~libvt.aio.open_pty` spawns a child process attached to - `pty.openpty()` with initial `TIOCSWINSZ` window dimensions, forwards - terminal query replies, and calls +- {func}`~libvt.aio.open_pty` spawns a child process attached to a + controlling `pty.openpty()` terminal (`TIOCSCTTY`, `TIOCSWINSZ`, + default `SIGPIPE`, and selectable `tty_mode`), forwards terminal query + replies, and calls {meth}`~libvt.terminal.Terminal.notify_process_exit` on teardown. From 743728ab045669bd46cd73eb09c20ad359b25464 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 21 Nov 2026 20:00:46 -0600 Subject: [PATCH 07/29] Core(fix[vt]): Harden UCD 17, grid, and PTY Widen ?2027 Indic conjunct and Mc spacing-mark clusters to 2 columns while giving conjoining Hangul V/T and Cf Prepend standalone width 0, validate VS15/VS16 against immediate predecessors, and pass Profile rules into display_width(). Repair cross-row SPACER_HEAD cells and clear predecessor wrapped flags before mutating continuation cells, separate _Row.text_used from BCE background fills, and anchor live RowView instances to Screen row coordinates across scroll recycling. Persist inner passthrough parser state across split DCS tmux; envelopes, raise max_dcs_bytes above max_apc_bytes, bound unread event bytes via max_event_bytes, emit UnhandledSequence on string overflow, consume ESC k window renames on TMUX_PROFILE, add OSC 10/11 and 110/111 dynamic color handling plus newline_mode, decouple OSC 7501;? replies from event recording, enforce RFC 8089 on OSC 7 cwd paths, and harden open_pty() with a pre-exec marker, strict TIOCSCTTY, python_executable, and killpg SIGHUP teardown. --- scripts/generate_ucd.py | 95 +++++++-- src/libvt/__init__.py | 6 + src/libvt/_grid.py | 61 +++++- src/libvt/_ucd.py | 164 ++++++++++------ src/libvt/aio.py | 137 ++++++++++--- src/libvt/config.py | 89 ++++++--- src/libvt/events.py | 15 ++ src/libvt/parser.py | 52 ++++- src/libvt/pytest_plugin.py | 3 + src/libvt/screen.py | 163 ++++++++++------ src/libvt/terminal.py | 315 +++++++++++++++++++++++------- tests/test_aio_and_pytest.py | 23 ++- tests/test_parser.py | 21 +- tests/test_protocols_and_input.py | 50 ++++- tests/test_ucd_and_grid.py | 71 ++++++- 15 files changed, 975 insertions(+), 290 deletions(-) diff --git a/scripts/generate_ucd.py b/scripts/generate_ucd.py index 0ede2c6..e3966fb 100644 --- a/scripts/generate_ucd.py +++ b/scripts/generate_ucd.py @@ -194,12 +194,16 @@ def build_tables(ucd_dir: pathlib.Path) -> tuple[bytes, bytes]: incb = INCB_IDS[incb_map.get(cp, "None")] gc = gc_map.get(cp, "Cn") eaw = eaw_map.get(cp, "N") - if 0xD800 <= cp <= 0xDFFF or cp < 0x20 or 0x7F <= cp < 0xA0: + if ( + 0xD800 <= cp <= 0xDFFF + or cp < 0x20 + or 0x7F <= cp < 0xA0 + or gc in ("Mn", "Me", "Cf", "Mc") + or gcb in (GCB_IDS["V"], GCB_IDS["T"]) + ): width = 0 elif cp == 0x00AD or 0x1F1E6 <= cp <= 0x1F1FF: width = 1 - elif gc in ("Mn", "Me", "Cf") and gcb != GCB_IDS["Prepend"]: - width = 0 elif eaw in ("W", "F"): width = 2 else: @@ -256,8 +260,12 @@ def render_module(stage1: bytes, stage2: bytes) -> str: import base64 import enum import sys +import typing as t import zlib +if t.TYPE_CHECKING: + from libvt.config import Profile + class WidthRole(enum.IntEnum): """Column occupancy role of a terminal grid cell.""" @@ -332,6 +340,8 @@ def _pack_state( ep_state: int, incb_state: int, vs_base: int, + has_spacing: int, + multi_scalar: int, ) -> int: return ( _ACTIVE_BIT @@ -340,19 +350,23 @@ def _pack_state( | (ep_state << 6) | (incb_state << 8) | (vs_base << 10) + | (has_spacing << 11) + | (multi_scalar << 12) ) def init_cluster_state(cp: int, *, mode_2027: bool = True) -> int: """Return initial packed cluster state for base codepoint *cp*.""" entry = ucd_lookup(cp) + w = entry & 0b11 gcb = (entry >> 2) & 0x0F incb = (entry >> 6) & 0x03 ep = 1 if (entry & EXT_PICT_BIT) else 0 vs_b = 1 if (entry & EMOJI_VS_BASE_BIT) else 0 ri_odd = 1 if (mode_2027 and gcb == GCB_REGIONAL_INDICATOR) else 0 incb_st = 1 if incb == INCB_CONSONANT else 0 - return _pack_state(gcb, ri_odd, ep, incb_st, vs_b) + has_sp = 1 if w >= 1 else 0 + return _pack_state(gcb, ri_odd, ep, incb_st, vs_b, has_sp, 0) def char_width(ch: str) -> int: @@ -368,6 +382,8 @@ def step_cluster( cp: int, *, mode_2027: bool, + vs15_narrows: bool = True, + vs16_always_wide: bool = False, ) -> tuple[bool, int, int]: """Evaluate UAX #29 continuation between *prev_state* and codepoint *cp*. @@ -376,9 +392,9 @@ def step_cluster( tuple[bool, int, int] ``(extends_previous, next_state, width_override)`` where ``width_override`` is ``-1`` (keep current cluster width), ``1`` - (narrow via ``VS15`` on an emoji variation base), or ``2`` (widen via - ``VS16`` on an emoji variation base, emoji modifier, ZWJ pictographic, - Regional Indicator pair, or wide glyph after ``Prepend``). + (narrow via ``VS15`` on an emoji variation base or first narrow glyph + after ``Prepend``), or ``2`` (widen via ``VS16``, spacing continuation, + emoji modifier, ZWJ pictographic, or Regional Indicator pair). """ entry = ucd_lookup(cp) gcb = (entry >> 2) & 0x0F @@ -392,10 +408,16 @@ def step_cluster( ep_state = (prev_state >> 6) & 0x03 incb_state = (prev_state >> 8) & 0x03 vs_base = (prev_state >> 10) & 0x01 + has_spacing = (prev_state >> 11) & 0x01 + multi_scalar = (prev_state >> 12) & 0x01 if not mode_2027: if gcb == GCB_EXTEND: - return True, _pack_state(gcb, 0, ep_state, incb_state, 0), -1 + return ( + True, + _pack_state(gcb, 0, ep_state, incb_state, 0, has_spacing, 1), + -1, + ) if w == 0: return False, CLUSTER_NONE, -1 return False, init_cluster_state(cp, mode_2027=False), -1 @@ -423,15 +445,18 @@ def step_cluster( if joined: w_override = -1 - if cp == 0xFE0F and vs_base: + if cp == 0xFE0F and (vs_base or (vs16_always_wide and has_spacing)): w_override = 2 - elif cp == 0xFE0E and vs_base: + elif cp == 0xFE0E and vs_base and vs15_narrows and not multi_scalar: w_override = 1 - elif ( - ((entry & EMOJI_MOD_BIT) and ep_state == 1) + elif not has_spacing and w >= 1: + w_override = w + elif has_spacing and ( + w >= 1 + or gcb == GCB_SPACING_MARK + or ((entry & EMOJI_MOD_BIT) and ep_state == 1) or (ep_state == 2 and ep) or (ri_odd == 1 and gcb == GCB_REGIONAL_INDICATOR) - or (prev_g == GCB_PREPEND and w == 2) ): w_override = 2 @@ -454,16 +479,35 @@ def step_cluster( else: next_incb = 0 - next_vs = ( - 1 if (prev_g == GCB_PREPEND and (entry & EMOJI_VS_BASE_BIT)) else 0 + next_vs = 1 if (entry & EMOJI_VS_BASE_BIT) else 0 + next_sp = ( + 1 if (has_spacing or w >= 1 or gcb == GCB_SPACING_MARK) else 0 ) + next_multi = 0 if (not has_spacing and w >= 1) else 1 return ( True, - _pack_state(gcb, next_ri, next_ep, next_incb, next_vs), + _pack_state( + gcb, + next_ri, + next_ep, + next_incb, + next_vs, + next_sp, + next_multi, + ), w_override, ) - if w == 0 and gcb in (GCB_CR, GCB_LF, GCB_CONTROL, GCB_EXTEND, GCB_ZWJ): + if w == 0 and gcb in ( + GCB_CR, + GCB_LF, + GCB_CONTROL, + GCB_EXTEND, + GCB_ZWJ, + GCB_SPACING_MARK, + GCB_V, + GCB_T, + ): return False, CLUSTER_NONE, -1 return False, init_cluster_state(cp, mode_2027=mode_2027), -1 @@ -499,10 +543,17 @@ def segment_graphemes(text: str) -> list[str]: return clusters -def display_width(text: str, *, mode_2027: bool = True) -> int: +def display_width( + text: str, + *, + mode_2027: bool = True, + profile: Profile | None = None, +) -> int: """Return rendered terminal column width of *text*.""" if text.isascii(): return sum(1 for ch in text if " " <= ch <= "~") + vs15_narrows = profile.vs15_narrows_wide_emoji if profile is not None else True + vs16_wide = profile.vs16_always_wide if profile is not None else False total = 0 cur_w = 0 state = CLUSTER_NONE @@ -512,7 +563,13 @@ def display_width(text: str, *, mode_2027: bool = True) -> int: cur_w = 1 state = init_cluster_state(cp, mode_2027=mode_2027) continue - extends, state, w_override = step_cluster(state, cp, mode_2027=mode_2027) + extends, state, w_override = step_cluster( + state, + cp, + mode_2027=mode_2027, + vs15_narrows=vs15_narrows, + vs16_always_wide=vs16_wide, + ) if extends: if w_override != -1: cur_w = w_override diff --git a/src/libvt/__init__.py b/src/libvt/__init__.py index d16517b..86b34fe 100644 --- a/src/libvt/__init__.py +++ b/src/libvt/__init__.py @@ -27,8 +27,10 @@ from libvt.codec import ExplainedSpan, explain, format_explain from libvt.config import ( DEFAULT_LIMITS, + DEFAULT_OSC7_HOSTS, DEFAULT_POLICY, DEFAULT_PROFILE, + TMUX_CAPTURE_POLICY, TMUX_PROFILE, XTERM_PROFILE, ColorScheme, @@ -57,6 +59,7 @@ SixelGraphic, TitleChanged, UnhandledSequence, + WindowRenamed, WorkingDirectoryChanged, ) from libvt.exc import ( @@ -123,9 +126,11 @@ __all__ = [ "BLANK_CELL", "DEFAULT_LIMITS", + "DEFAULT_OSC7_HOSTS", "DEFAULT_POLICY", "DEFAULT_PROFILE", "DEFAULT_STYLE", + "TMUX_CAPTURE_POLICY", "TMUX_PROFILE", "UNICODE_VERSION", "XTERM_PROFILE", @@ -203,6 +208,7 @@ "UnhandledSequence", "UnsafePasteError", "WidthRole", + "WindowRenamed", "WorkingDirectoryChanged", "__author__", "__copyright__", diff --git a/src/libvt/_grid.py b/src/libvt/_grid.py index 310086a..049e7a4 100644 --- a/src/libvt/_grid.py +++ b/src/libvt/_grid.py @@ -263,13 +263,25 @@ def thaw(self, target_cols: int | None = None) -> _Row: if self.exts: row.ext = {c: ce for c, ce in self.exts if c < width} row.used = limit + row.text_used = min( + len(self.cells) if self.cells is not None else len(self.text), width + ) return row class _Row: """Mutableviewport row with lazy 64-bit ``array('Q')`` promotion.""" - __slots__ = ("attrs", "chars", "ext", "has_wide", "uniform_attr", "used", "wrapped") + __slots__ = ( + "attrs", + "chars", + "ext", + "has_wide", + "text_used", + "uniform_attr", + "used", + "wrapped", + ) def __init__(self, cols: int) -> None: self.chars: list[str] = [" "] * cols @@ -278,6 +290,7 @@ def __init__(self, cols: int) -> None: self.has_wide: bool = False self.ext: dict[int, _CellExt] | None = None self.used: int = 0 + self.text_used: int = 0 self.wrapped: bool = False def _ensure_attrs(self) -> array.array[int]: @@ -323,6 +336,7 @@ def reset_blank( if self.ext is not None: self.ext.clear() self.used = cols if bce_word != 0 else 0 + self.text_used = 0 self.wrapped = False def _set_raw( @@ -360,18 +374,31 @@ def _heal_wide_boundary(self, col: int) -> None: if col < 0 or col >= cols: return role = raw_width_bits(self.attrs[col]) + healed_pair_end = -1 if role == int(WidthRole.WIDE): self.chars[col] = " " self.attrs[col] &= _WIDTH_CLEAR_MASK + healed_pair_end = col + 1 if col + 1 < cols: self.chars[col + 1] = " " self.attrs[col + 1] &= _WIDTH_CLEAR_MASK + healed_pair_end = col + 2 elif role == int(WidthRole.SPACER_TAIL): self.chars[col] = " " self.attrs[col] &= _WIDTH_CLEAR_MASK + healed_pair_end = col + 1 if col - 1 >= 0: self.chars[col - 1] = " " self.attrs[col - 1] &= _WIDTH_CLEAR_MASK + if healed_pair_end != -1 and self.text_used == healed_pair_end: + pair_lo = max(0, healed_pair_end - 2) + self.text_used = pair_lo + if ( + self.used == healed_pair_end + and self.attr_at(healed_pair_end - 1) == 0 + and self.ext_at(healed_pair_end - 1) is None + ): + self.used = pair_lo def write_narrow( self, @@ -384,6 +411,7 @@ def write_narrow( self._heal_wide_boundary(col) self._set_raw(col, ch, pen_word, WidthRole.NARROW, cell_ext) self.used = max(self.used, col + 1) + self.text_used = max(self.text_used, col + 1) def write_spacer_head( self, @@ -395,6 +423,7 @@ def write_spacer_head( self._heal_wide_boundary(col) self._set_raw(col, "", bce_word, WidthRole.SPACER_HEAD, bce_ext) self.used = max(self.used, col + 1) + self.text_used = max(self.text_used, col + 1) def write_ascii_slice( self, @@ -438,6 +467,7 @@ def write_ascii_slice( self.ext.pop(idx, None) self.used = max(self.used, end) + self.text_used = max(self.text_used, end) def write_wide( self, @@ -452,6 +482,7 @@ def write_wide( self._set_raw(col, ch, pen_word, WidthRole.WIDE, cell_ext) self._set_raw(col + 1, "", pen_word, WidthRole.SPACER_TAIL, cell_ext) self.used = max(self.used, col + 2) + self.text_used = max(self.text_used, col + 2) def append_grapheme( self, @@ -489,6 +520,7 @@ def append_grapheme( self.has_wide = True self._set_raw(target + 1, "", pen_word, WidthRole.SPACER_TAIL, cell_ext) self.used = max(self.used, target + 2) + self.text_used = max(self.text_used, target + 2) elif ( width_override == 1 and cur_role == int(WidthRole.WIDE) @@ -497,6 +529,10 @@ def append_grapheme( attrs = self._ensure_attrs() attrs[target] &= _WIDTH_CLEAR_MASK self._set_raw(target + 1, " ", pen_word, WidthRole.NARROW, cell_ext) + if self.text_used == target + 2: + self.text_used = target + 1 + if self.used == target + 2 and pen_word == 0 and cell_ext is None: + self.used = target + 1 def clear_range( self, @@ -530,6 +566,9 @@ def clear_range( and self.ext_at(self.used - 1) is None ): self.used -= 1 + if hi >= cols: + while self.text_used > lo and not self.is_protected(self.text_used - 1): + self.text_used -= 1 return if lo == 0 and hi == cols: @@ -565,6 +604,8 @@ def clear_range( elif hi >= cols: # Clamp used to lo without erasing explicit spaces printed left of lo! self.used = min(self.used, lo) + if hi >= cols: + self.text_used = min(self.text_used, lo) def insert_blanks( self, @@ -636,6 +677,8 @@ def insert_blanks( self._set_raw(c, " ", bce_word, WidthRole.NARROW, bce_ext) if bce_word != 0 or bce_ext is not None or self.used > col: self.used = min(right + 1, max(self.used + shift, col + shift)) + if self.text_used > col: + self.text_used = min(right + 1, self.text_used + shift) def delete_cells( self, @@ -701,6 +744,8 @@ def delete_cells( self.used = max(self.used, right + 1) elif self.used > col: self.used = max(col, self.used - shift) + if self.text_used > col: + self.text_used = max(col, self.text_used - shift) def resize(self, cols: int) -> None: """Resize row in place to *cols* columns (non-reflow path).""" @@ -720,6 +765,7 @@ def resize(self, cols: int) -> None: if self.attrs is not None: del self.attrs[cols:] self.used = min(self.used, cols) + self.text_used = min(self.text_used, cols) if self.ext: for k in [k for k in self.ext if k >= cols]: del self.ext[k] @@ -742,17 +788,18 @@ def clone(self) -> _Row: dup.has_wide = self.has_wide dup.ext = self.ext.copy() if self.ext else None dup.used = self.used + dup.text_used = self.text_used dup.wrapped = self.wrapped return dup def freeze(self) -> FrozenRow: """Seal this row into a compact run-length-encoded :class:`FrozenRow`.""" cols = len(self.chars) - used = self.used - text = "".join(self.chars[:used]) + t_used = self.text_used + text = "".join(self.chars[:t_used]) cells: tuple[str, ...] | None = None - if len(text) != used: - cells = tuple(self.chars[:used]) + if len(text) != t_used: + cells = tuple(self.chars[:t_used]) runs: tuple[tuple[int, int], ...] if self.attrs is None: @@ -780,8 +827,8 @@ def freeze(self) -> FrozenRow: ) def rstrip_text(self) -> str: - """Return row text up to ``used`` written columns.""" - return "".join(self.chars[: self.used]) + """Return row text up to ``text_used`` written columns.""" + return "".join(self.chars[: self.text_used]) type RowLike = _Row | FrozenRow diff --git a/src/libvt/_ucd.py b/src/libvt/_ucd.py index 330cd25..95a9d14 100644 --- a/src/libvt/_ucd.py +++ b/src/libvt/_ucd.py @@ -18,8 +18,12 @@ import base64 import enum import sys +import typing as t import zlib +if t.TYPE_CHECKING: + from libvt.config import Profile + class WidthRole(enum.IntEnum): """Column occupancy role of a terminal grid cell.""" @@ -61,46 +65,45 @@ class WidthRole(enum.IntEnum): UNICODE_VERSION = "17.0.0" _PACKED_B85 = ( - "c-rkbYhWEdFI2@n{{;XK34KoW9GZf-&f9" - "j5dMQiOC09Uw-h(rI*%PNy^IOxmM;I*ZPxL+Sl*#tqI(giXQhj6kxrvU^&2$UhO1IH*x}ENzJLxWO|L&%HBm}jw&h5R~ulw" - "l!^!xxlNDm1i9?s5>(4+JiJx)*1lk^llP0!G?^c+1;FVKth61_}IIzg{EKlRlHId#Kp%9YpYjr9C" - "x`gyCdJm02wJml@&G^O|Gea)Q@oZ^3&em8tenYx+hA`z?J(-_sBD" - "BmG1_(=YTZ{YJm1*Z;`y=L||FV8&nI!OZ0!000000000000000001yq{7wJRzZQT)0002f#GVERv" - "-1J%JsEjA2ZU4)2)|Vfn)-Usq{=qm``cdtFjT}72P6#CEd}5Q(1(Q#@(+LRo4N%Dcj{Bm>EJMUUY" - "*iZHE|(b2?Sm8W5*V)IXI_UdpNYX(f5g<7@vl&Z2cq6glK->7$W7ot|7!bmlLc^wlpAA1FGj>VKIRll-e_bSnX}-Hvudf0A1QH~n9SsjvTmMgMp0BPJR3CHJHJccB-y^6#%4" - "nxE!J{wssc4kUXodk{;lmajAxtzA9rs{dWszc|x@WJ`aNNjS+$My$v_XWXMVff9f5VW!n?2$=#Mc=G-0Z<_=_@qd#cQ5o@2!sh*y@c8nf~Uvin&jpdTDR>$lh0VYreZT6T" - "6W2suS@1izKR-xy9YI=IZ3Hj8)bmvCz8G#Wl4Y`PwLu+98|#uV&D*cx2=l+Kk#`Bg5Ex!|{HqFHR" - "?|;wL-tIjZBYdV*RL#*!}|arL5zW$)g?=DB;bDqp^=NjyW_5OIB(k>J;tdL0SEM{kr*!tZ$8c)PD(=yCm=VETogr32hs)%lF^BMz__=m@64;YL?p;" - "r_Jl=qAx$@di0|$x0BBGT=iwt(g?fXyp`kDhb6vCRlO3(0OPM+?BX6BqW?_u8?4w*v3Ib5B_wNbN" - "1M|E+;i>oGiIhAJ>-&g7vTdUYK1ZNUVJX29x{8Z=67dd6MGUO?>kHXiDWv@rSeKi^}PO#-xA3eMXdhTeZw*DW8R}@fvR^$Rd1=A#P4pLQGhq;wXipV5x~3SULWf!)f?Zd-rrX+jdf7~%zXh" - "M#b&+^cu~H8w(owRj-&9gD?srSj7aErq+cH+Em6t=l*M=y^l_qS;{!E" - "!ehtt=Fu2<-h;^Ab1>I-hK3X`rn-RmeLW2hvVSZFW-~f2p6Y=EvII+>%LATUu=WZo0snVQ%q2JBI" - "cCNA^%xTE94G`1U8^=D3TV`o_17vJW)EwIuOvHhw3*sImNY{cv6Ee#-AOXR0NZ75OVU;X8*54)(p" - "a@Xm60UP#%l0!N1Sc0ugxkW16J#*MhFwGwGPp85Jcx<0u;yDHOSAROX7mO`e{i1ZZzTzmO9Xmc-LT|l>%" - "b{}575)8e50)M75CIH%rZd*7hvooNhG_+j!0Y}!Re5Ne|LRmmvVRZ&phlQX&q~?9J+(euAE=)`v<" - "hg7B%fgxbN>sdZ=I?%)km3vOzQ9pd_eoR>m5!Z?>_5)bN$}uv)o3F#0|MN_Av{#@tLk(ojRItO79" - ";4V0_vG9~AXEtKPq$XaovP0ImhyEGN&&+KM1Wfn`7c|IYKj7232;_zq|}F8JbeV!eHlM" - "jdH^{d%?DLL#2`#xmT4Z#>Lj~P~~qPf>lwv$!RX9{MyN|fSEr|cbH>b12*|8=@z)g1a3Bxv4>D?p" - "UAZLSw%eN_%yw~F{AdeGUQqxYNXvkSv1$mWr!^;jxf~ll4Y`Z1bpc7O6~_(eFZ6eg_psk5OyzxS*" - "|i6HKu)vbk%!V>I|K?d(6}_Z3$)#ILDNFRhy0|A-)FSb1K%`f@W`J&3R4CB=MQ}|5Jp6|5o0wIEL" - "1KcgbIu?N^`eV^{vxlaJrS%`SSk>h4#8G1spJd{)sw??NpioGW^_Q8(d" + "Ef+o_vnbQM!Vzq^sx{T}{X7n$hFhB-hs^pA&RF-9R_eO>{Gzq+94#x{YoR_U{h5Q$ti4%hcYr`gJ" + "$mlics6`{;hf#RIGRgY*zROpnl`^cX!(PtcR}6g^GP(6jU$Jx?#toL;1tykmX2MoRtgO5w??^jdO" + "%J^8#*o1bseTLIGcb`sJ%^seE}dtUzEPd*>ehxC#1^keDwCrMsEO};;)&*_Wg`%C&tar-rWL*LSO" + "^gaDRKhjV1GyOupCeMFc;r9uYOu&vmK!b_%KLP*%00000000000001BwD^<$qQ4ygg#Z8m#)&-xc" + "31Zu<2xN`I6F$HJIe1OdY$`fFoepou(MwP&{v3&0~`jbmIBZN=t4tA=|{eIox7O?|J*0m&2B$vUL" + "Mj|C2^)bi4<81qsL~ADLAECyFYpHNrk8#YGl!6`nxvs)}?-|M%V6ZoLS?VhKTnH||7CgfD*?LR=3C0YNHu|<{HyxbSNz~XwB+jU-@rC{|Q9~gwuW(P7UUcjXQM*@3{V7D4HkFtt$U>I`EYLA@bi(A" + "ITJw>kRH)YGtjuz1$q}w3^4*duz(SyDaxP|MgQPq)(S}>2CMv)>nCJzP*u&ZSZ^13YM3N#v*w>m$" + "cfVQu=aVc`YK+*k}`Pe#x$cvo@kMWcgZ$Y)Vu1ehk{_*uZhTXE-r1481oT<5S($pxfe<2-XMGRsC" + "mf@o-B|XKu}#`a{L4#_ZNwSjW3Jsqz&{n}`YO1}^nwa>cIC<(ez~ozSX7<+j@Iu;>ijph2TVH&SZ" + "13x{^KwZBAXb!S_1+nSD`n@0fkKGrbxpN&K7I?mKf+~)YVEYVHnQb;8utFeV67tM2MA5RdHHPKy9" + "Qqh(v@)~--zU}PShoz3C7OfKS0Q0YX^x_^JqW^5`8=Tlru(zAR;gZ#OV@zoVDPH&bjETud2dQK&y" + "6y{@gmRao)>$!&9i=y>7C2PZ-6^B-cv%4zCpzOf84D`IN@Z~exRti%s?yA*Te&6VPW_ZgY^&" + "OL9Ar*zVm`a08d+8{lbe;-Up~P9jRnnWe%c;Z^4y$3XLj7pfwrZ{n^rcveFZP!cJw<74kaIguQ>m" + "v~buUqq75QY~Hff<&vx&6aFT;tMDizkyJF&T}a>(4i>c5?YP6YbZ!fDZOvs32#" + "`Z@CSeJ2Y>JffA9x?@CSeJ2Y-Uwy@Z;yKaBe0>-f~3V^jQ0JvDs)&VW@@n`qx2gP|5^=H8" + "pS0rLaLbo&hx|nH+QVyUjib2$aqPOYlGKEvt7rf)sKf7LyE}Z32w0`<2H_rTBzL}NS@Uss25%QD^" + ")2_txQr@mlcUrWTOIQAR2c?V~ccEX;(mYU3I+V{t6a&^Pd5*bu%Bx;BVK3B|YqMlkEC0On^C9!|K" + "jrgZ)$@P-&%DWenP^Z(6Wf}BD7}X~!6N6FexjhdQh-YBH{*ZEvJp8" + "uGLd%cJe2SCsu}!`0$}bo6QbN4HQHM!PtwIr<}?!=_v6OWT&OK9C" + "6Ck|ej;@|&3{urTpOpK$|ud)YKeJC`f^HyPT_$B_gPyQv+SQ0lDDfsk-m*C=zSf2`+D?$T*@|" + "r!HpKrbnPBfpIl_zmFb`-6p}5LjHi4+@(KXHz5MHP$31q?X?l8dv3DTv;~rnXFR;d53B*=s2LNr@" + "MRJQ3R04oLl+ixu2=D`F1IIVt>Nu79_ALIlv~mCo3&9+Cr$8MYlXq" + "M+yZl%=6*`pZKZ$oWA4fEr;mJu7+t_SpJxL!f&2kSZWlPp2$b#Zjj+Nez(_@T3a8KnJvc+dknG{O" + "+>;x7Y7o#^pC_MAWWphHcTf=4bj^b;a3yV;X+|fZ<6GY*5te;6G#lRG3apBb@w)EDXPWhI|4o^#i" + "fMA!gTDC}g|JeU-UzaV0DTtEYeXU=geJZcY8wy@-Y~)6#XAsv}E9WjYd" + "GUm$hSxNc!y=Gf=TA~Qz-cRJ?n|r;rnzuiDa`SdDWNfAEZWoHWvMl^-tMvImKjSht3f$ds8@~Qs2" + "q}O06C>-y4C" + "XOY~Q-{XKCBGEp8~9yUeYR_P4*og$viDFRYK7{2H+3dC>a}AO?>8i9-OR#y$Wz@IN@`B5(" ) @@ -133,6 +136,8 @@ def _pack_state( ep_state: int, incb_state: int, vs_base: int, + has_spacing: int, + multi_scalar: int, ) -> int: return ( _ACTIVE_BIT @@ -141,19 +146,23 @@ def _pack_state( | (ep_state << 6) | (incb_state << 8) | (vs_base << 10) + | (has_spacing << 11) + | (multi_scalar << 12) ) def init_cluster_state(cp: int, *, mode_2027: bool = True) -> int: """Return initial packed cluster state for base codepoint *cp*.""" entry = ucd_lookup(cp) + w = entry & 0b11 gcb = (entry >> 2) & 0x0F incb = (entry >> 6) & 0x03 ep = 1 if (entry & EXT_PICT_BIT) else 0 vs_b = 1 if (entry & EMOJI_VS_BASE_BIT) else 0 ri_odd = 1 if (mode_2027 and gcb == GCB_REGIONAL_INDICATOR) else 0 incb_st = 1 if incb == INCB_CONSONANT else 0 - return _pack_state(gcb, ri_odd, ep, incb_st, vs_b) + has_sp = 1 if w >= 1 else 0 + return _pack_state(gcb, ri_odd, ep, incb_st, vs_b, has_sp, 0) def char_width(ch: str) -> int: @@ -169,6 +178,8 @@ def step_cluster( cp: int, *, mode_2027: bool, + vs15_narrows: bool = True, + vs16_always_wide: bool = False, ) -> tuple[bool, int, int]: """Evaluate UAX #29 continuation between *prev_state* and codepoint *cp*. @@ -177,9 +188,9 @@ def step_cluster( tuple[bool, int, int] ``(extends_previous, next_state, width_override)`` where ``width_override`` is ``-1`` (keep current cluster width), ``1`` - (narrow via ``VS15`` on an emoji variation base), or ``2`` (widen via - ``VS16`` on an emoji variation base, emoji modifier, ZWJ pictographic, - Regional Indicator pair, or wide glyph after ``Prepend``). + (narrow via ``VS15`` on an emoji variation base or first narrow glyph + after ``Prepend``), or ``2`` (widen via ``VS16``, spacing continuation, + emoji modifier, ZWJ pictographic, or Regional Indicator pair). """ entry = ucd_lookup(cp) gcb = (entry >> 2) & 0x0F @@ -193,10 +204,16 @@ def step_cluster( ep_state = (prev_state >> 6) & 0x03 incb_state = (prev_state >> 8) & 0x03 vs_base = (prev_state >> 10) & 0x01 + has_spacing = (prev_state >> 11) & 0x01 + multi_scalar = (prev_state >> 12) & 0x01 if not mode_2027: if gcb == GCB_EXTEND: - return True, _pack_state(gcb, 0, ep_state, incb_state, 0), -1 + return ( + True, + _pack_state(gcb, 0, ep_state, incb_state, 0, has_spacing, 1), + -1, + ) if w == 0: return False, CLUSTER_NONE, -1 return False, init_cluster_state(cp, mode_2027=False), -1 @@ -224,15 +241,18 @@ def step_cluster( if joined: w_override = -1 - if cp == 0xFE0F and vs_base: + if cp == 0xFE0F and (vs_base or (vs16_always_wide and has_spacing)): w_override = 2 - elif cp == 0xFE0E and vs_base: + elif cp == 0xFE0E and vs_base and vs15_narrows and not multi_scalar: w_override = 1 - elif ( - ((entry & EMOJI_MOD_BIT) and ep_state == 1) + elif not has_spacing and w >= 1: + w_override = w + elif has_spacing and ( + w >= 1 + or gcb == GCB_SPACING_MARK + or ((entry & EMOJI_MOD_BIT) and ep_state == 1) or (ep_state == 2 and ep) or (ri_odd == 1 and gcb == GCB_REGIONAL_INDICATOR) - or (prev_g == GCB_PREPEND and w == 2) ): w_override = 2 @@ -255,16 +275,33 @@ def step_cluster( else: next_incb = 0 - next_vs = ( - 1 if (prev_g == GCB_PREPEND and (entry & EMOJI_VS_BASE_BIT)) else 0 - ) + next_vs = 1 if (entry & EMOJI_VS_BASE_BIT) else 0 + next_sp = 1 if (has_spacing or w >= 1 or gcb == GCB_SPACING_MARK) else 0 + next_multi = 0 if (not has_spacing and w >= 1) else 1 return ( True, - _pack_state(gcb, next_ri, next_ep, next_incb, next_vs), + _pack_state( + gcb, + next_ri, + next_ep, + next_incb, + next_vs, + next_sp, + next_multi, + ), w_override, ) - if w == 0 and gcb in (GCB_CR, GCB_LF, GCB_CONTROL, GCB_EXTEND, GCB_ZWJ): + if w == 0 and gcb in ( + GCB_CR, + GCB_LF, + GCB_CONTROL, + GCB_EXTEND, + GCB_ZWJ, + GCB_SPACING_MARK, + GCB_V, + GCB_T, + ): return False, CLUSTER_NONE, -1 return False, init_cluster_state(cp, mode_2027=mode_2027), -1 @@ -300,10 +337,17 @@ def segment_graphemes(text: str) -> list[str]: return clusters -def display_width(text: str, *, mode_2027: bool = True) -> int: +def display_width( + text: str, + *, + mode_2027: bool = True, + profile: Profile | None = None, +) -> int: """Return rendered terminal column width of *text*.""" if text.isascii(): return sum(1 for ch in text if " " <= ch <= "~") + vs15_narrows = profile.vs15_narrows_wide_emoji if profile is not None else True + vs16_wide = profile.vs16_always_wide if profile is not None else False total = 0 cur_w = 0 state = CLUSTER_NONE @@ -313,7 +357,13 @@ def display_width(text: str, *, mode_2027: bool = True) -> int: cur_w = 1 state = init_cluster_state(cp, mode_2027=mode_2027) continue - extends, state, w_override = step_cluster(state, cp, mode_2027=mode_2027) + extends, state, w_override = step_cluster( + state, + cp, + mode_2027=mode_2027, + vs15_narrows=vs15_narrows, + vs16_always_wide=vs16_wide, + ) if extends: if w_override != -1: cur_w = w_override diff --git a/src/libvt/aio.py b/src/libvt/aio.py index b53d163..fdc4f14 100644 --- a/src/libvt/aio.py +++ b/src/libvt/aio.py @@ -6,7 +6,9 @@ import collections.abc import contextlib import dataclasses +import errno import os +import signal import socket import struct import sys @@ -15,6 +17,7 @@ from libvt.config import ( DEFAULT_LIMITS, + DEFAULT_OSC7_HOSTS, DEFAULT_POLICY, DEFAULT_PROFILE, Limits, @@ -28,32 +31,53 @@ type TtyMode = t.Literal["cooked", "cbreak", "raw"] _PTY_TRAMPOLINE = ( - "import errno, fcntl, os, signal, sys, termios\n" - "err_fd = int(sys.argv[1])\n" + "stage = 'bootstrap'\n" + "err_fd = -1\n" "try:\n" + " import errno, fcntl, os, signal, sys, termios\n" + " err_fd = int(sys.argv[1])\n" " os.set_inheritable(err_fd, False)\n" + " stage = 'ctty'\n" " if hasattr(termios, 'TIOCSCTTY'):\n" - " try:\n" - " fcntl.ioctl(0, termios.TIOCSCTTY, 0)\n" - " except OSError as exc:\n" - " if exc.errno not in (errno.EPERM, errno.EINVAL):\n" - " raise\n" + " fcntl.ioctl(0, termios.TIOCSCTTY, 0)\n" + " stage = 'signal'\n" " signal.signal(signal.SIGPIPE, signal.SIG_DFL)\n" + " if hasattr(signal, 'SIGXFSZ'):\n" + " signal.signal(signal.SIGXFSZ, signal.SIG_DFL)\n" + " stage = 'exec'\n" + " os.write(err_fd, b'\\x00')\n" " os.execvp(sys.argv[2], sys.argv[2:])\n" "except BaseException as exc:\n" - " code = getattr(exc, 'errno', None)\n" - " if not isinstance(code, int):\n" - " code = errno.ENOEXEC\n" - " msg = getattr(exc, 'strerror', None) or str(exc)\n" - " os.write(err_fd, f'{code}:{msg}'.encode('utf-8', 'replace'))\n" - " os._exit(127)\n" + " try:\n" + " import errno as _e, os as _os\n" + " if err_fd >= 0:\n" + " code = getattr(exc, 'errno', None)\n" + " if not isinstance(code, int):\n" + " code = _e.ENOEXEC\n" + " msg = (getattr(exc, 'strerror', None) or str(exc))[:360]\n" + " pkt = b'\\x01' + f'{stage}:{code}:{msg}'.encode('utf-8', 'replace')\n" + " _os.write(err_fd, pkt[:500])\n" + " except BaseException:\n" + " pass\n" + " import os as _os2\n" + " _os2._exit(127)\n" ) def _raise_exec_error(err_payload: bytes, cmd: str, default_errno: int) -> t.NoReturn: - code_s, _, err_msg = err_payload.decode("utf-8", "replace").partition(":") + if not err_payload: + msg = f"PTY launcher exited before pre-exec handoff while starting {cmd!r}" + raise RuntimeError(msg) + idx = err_payload.find(b"\x01") + body = err_payload[idx + 1 :] if idx != -1 else err_payload + parts = body.decode("utf-8", "replace").split(":", 2) + if len(parts) == 3: + stage, code_s, err_msg = parts + else: + stage, code_s, err_msg = "exec", "", body.decode("utf-8", "replace") err_no = int(code_s) if code_s.isdigit() else default_errno - raise OSError(err_no, err_msg or os.strerror(err_no), cmd) + target = cmd if stage == "exec" else f"open_pty({stage})" + raise OSError(err_no, err_msg or os.strerror(err_no), target) async def _read_cloexec_pipe(loop: asyncio.AbstractEventLoop, fd: int) -> bytes: @@ -65,7 +89,7 @@ def _on_ready() -> None: while True: try: data = os.read(fd, 4_096) - except BlockingIOError: + except (BlockingIOError, InterruptedError): return except OSError as exc: loop.remove_reader(fd) @@ -298,13 +322,37 @@ def eof(self) -> bool: """Return ``True`` once the PTY master reaches EOF.""" return self._eof + def _drain_nonblocking_master(self) -> None: + """Consume any buffered non-blocking bytes from ``master_fd``.""" + if self._closed or self._eof: + return + while True: + try: + chunk = os.read(self._master_fd, 16_384) + except (BlockingIOError, InterruptedError): + return + except OSError as exc: + if exc.errno == errno.EIO: + chunk = b"" + else: + return + if not chunk: + self._eof = True + return + self.terminal.feed(chunk) + def _on_readable(self) -> None: if self._closed: return try: chunk = os.read(self._master_fd, 16_384) - except OSError: - chunk = b"" + except (BlockingIOError, InterruptedError): + return + except OSError as exc: + if exc.errno == errno.EIO: + chunk = b"" + else: + raise if not chunk: self._eof = True if self._loop is not None: @@ -407,21 +455,35 @@ async def wait_for( await asyncio.wait_for(self._frame_event.wait(), timeout=wait_slice) async def aclose(self) -> int: - """Stop reading, close PTY master fd, and terminate/reap child process.""" + """Signal the owned process group, drain PTY output, and close master fd.""" + if self.process.returncode is None: + pid = self.process.pid + for sig, wait_s in ( + (signal.SIGHUP, 0.4), + (signal.SIGTERM, 0.4), + ): + if self.process.returncode is not None: + break + with contextlib.suppress(ProcessLookupError, PermissionError): + os.killpg(pid, sig) + with contextlib.suppress(TimeoutError): + await asyncio.wait_for(self.process.wait(), timeout=wait_s) + if self.process.returncode is None: + with contextlib.suppress(ProcessLookupError, PermissionError): + os.killpg(pid, signal.SIGKILL) + with contextlib.suppress(ProcessLookupError): + self.process.kill() + await self.process.wait() + if not self._closed: + self._drain_nonblocking_master() self._closed = True if self._loop is not None: with contextlib.suppress(Exception): self._loop.remove_reader(self._master_fd) with contextlib.suppress(OSError): os.close(self._master_fd) - if self.process.returncode is None: - self.process.terminate() - try: - await asyncio.wait_for(self.process.wait(), timeout=1.0) - except TimeoutError: - self.process.kill() - await self.process.wait() + self.terminal.notify_process_exit() return self.process.returncode or 0 @@ -436,6 +498,7 @@ async def open_pty( env: collections.abc.Mapping[str, str] | None = None, cwd: str | os.PathLike[str] | None = None, tty_mode: TtyMode = "cooked", + python_executable: str | os.PathLike[str] | None = None, profile: Profile = DEFAULT_PROFILE, policy: Policy = DEFAULT_POLICY, limits: Limits = DEFAULT_LIMITS, @@ -452,7 +515,17 @@ async def open_pty( msg = f"unsupported tty_mode: {tty_mode!r}" raise ValueError(msg) - import errno + if python_executable is None: + if getattr(sys, "frozen", False) or not sys.executable: + msg = ( + "open_pty requires python_executable in frozen or embedded " + "Python runtimes" + ) + raise RuntimeError(msg) + py_bin = sys.executable + else: + py_bin = os.fspath(python_executable) + import fcntl import pty import termios @@ -479,7 +552,7 @@ async def open_pty( child_env = dict(os.environ if env is None else env) child_env.setdefault("TERM", "xterm-256color") proc = await asyncio.create_subprocess_exec( - sys.executable, + py_bin, "-I", "-S", "-c", @@ -501,11 +574,13 @@ async def open_pty( err_w_closed = True err_payload = await _read_cloexec_pipe(loop, err_r) - if err_payload: + if err_payload != b"\x00": await proc.wait() _raise_exec_error(err_payload, argv[0], errno.ENOEXEC) except BaseException: if proc is not None and proc.returncode is None: + with contextlib.suppress(ProcessLookupError, PermissionError): + os.killpg(proc.pid, signal.SIGKILL) with contextlib.suppress(ProcessLookupError): proc.kill() await proc.wait() @@ -523,12 +598,12 @@ async def open_pty( os.close(err_r) eff_policy = policy - if policy == DEFAULT_POLICY: + if policy.osc7_hosts is None: fqdn = socket.gethostname().lower() short = fqdn.partition(".")[0] eff_policy = dataclasses.replace( policy, - osc7_hosts=policy.osc7_hosts | frozenset({fqdn, short}), + osc7_hosts=DEFAULT_OSC7_HOSTS | frozenset({fqdn, short}), ) recorder = FlightRecorder(max_bytes=limits.max_recorder_bytes) diff --git a/src/libvt/config.py b/src/libvt/config.py index cea9030..2275b2c 100644 --- a/src/libvt/config.py +++ b/src/libvt/config.py @@ -15,7 +15,7 @@ class ColorScheme(enum.IntEnum): @dataclass(frozen=True, slots=True) class Profile: - """Terminal identity responses and compatibility switches. + r"""Terminal identity responses and compatibility switches. Attributes ---------- @@ -29,9 +29,8 @@ class Profile: Version banner emitted in ``DCS > | ST`` (``CSI > q``). osc_7501_capabilities : str Payload body returned for ``OSC 7501 ; ?`` queries when enabled - (for example - ``"?:states=idle,working,done,blocked,error:kinds=permission,question,auth"`` - or ``"?"`` for bare ``tmux`` compatibility). + (``""`` when unsupported, ``"?"`` for ``tmux``, or full capability + list on ``DEFAULT_PROFILE``). color_scheme : ColorScheme Default scheme reported for ``CSI ? 996 n`` color-scheme queries. fg_rgb : tuple[int, int, int] @@ -42,11 +41,20 @@ class Profile: When ``True`` (``TMUX_PROFILE``), ``pending_wrap`` treats the cursor as occupying phantom column ``cols`` on ``CUB`` / ``BS`` and allows ``BS`` at column ``0`` to step onto the end of a soft-wrapped predecessor row, - matching ``tmux``'s ``screen-write.c``. When ``False`` (default), - ``CUB`` / ``BS`` follow ``xterm`` / ``Ghostty`` rules. + matching ``tmux``'s ``screen-write.c``. + vs15_narrows_wide_emoji : bool + When ``True`` (default), ``U+FE0E`` narrows standalone wide emoji + listed in ``emoji-variation-sequences.txt`` from ``2`` columns to ``1``. + ``False`` on ``TMUX_PROFILE`` to match ``tmux 3.8a``. + vs16_always_wide : bool + When ``True``, ``U+FE0F`` widens any narrow spacing base rather than + only ``emoji-variation-sequences.txt`` bases. + tmux_window_rename : bool + When ``True`` (``TMUX_PROFILE``), ``ESC k ESC \`` is consumed as + a window-rename control string rather than printed onto the grid. """ - name: str = "xterm" + name: str = "libvt" da1: bytes = b"\x1b[?62;22c" da2: bytes = b"\x1b[>1;10;0c" xtversion: str = "libvt 0.1" @@ -57,14 +65,17 @@ class Profile: fg_rgb: tuple[int, int, int] = (0xE5, 0xE5, 0xE5) bg_rgb: tuple[int, int, int] = (0x1E, 0x1E, 0x1E) pending_wrap_phantom_col: bool = False + vs15_narrows_wide_emoji: bool = True + vs16_always_wide: bool = False + tmux_window_rename: bool = False -_DEFAULT_OSC7_HOSTS: frozenset[str] = frozenset({"", "localhost"}) +DEFAULT_OSC7_HOSTS: frozenset[str] = frozenset({"", "localhost"}) @dataclass(frozen=True, slots=True) class Policy: - """Default-deny host security and strictness policy. + r"""Default-deny host security and strictness policy. Attributes ---------- @@ -81,26 +92,30 @@ class Policy: Permit ``OSC 10 ; ?``, ``OSC 11 ; ?``, and ``CSI ? 996 n`` palette and color-scheme replies (default ``True``). allow_program_status_query : bool - Force ``OSC 7501 ; ?`` capability replies even when neither ``on_event`` - nor ``record_events`` is enabled (default ``False``, matching - ``libghostty-vt``). + Permit ``OSC 7501 ; ?`` capability replies whenever + ``profile.osc_7501_capabilities`` is non-empty (default ``True``). allow_unsafe_uris : bool Allow schemes outside ``http://``, ``https://``, and ``mailto:`` in HTML ```` output (default ``False``). allow_passthrough : bool - Re-feed unwrapped ``DCS tmux; ESC ESC ... ST`` inner byte streams into - :class:`~libvt.terminal.Terminal` in addition to emitting + Replay unwrapped ``DCS tmux; ESC ESC ... ST`` inner byte streams + through a persistent passthrough parser in addition to emitting :class:`~libvt.events.Passthrough` (default ``False``, matching ``tmux``'s ``allow-passthrough off``). - osc7_hosts : frozenset[str] + abort_dispatch_osc : bool + When ``True``, dispatch an accumulated ``OSC`` string if interrupted by + a non-``\`` ``ESC`` byte (matching ``tmux`` / ``Ghostty`` state-exit + behavior). Defaults to ``False`` (DEC STD 070 abort-and-drop). + osc7_hosts : frozenset[str] | None Lowercase hostnames in ``OSC 7`` ``file:///...`` URIs permitted - to update :attr:`~libvt.terminal.Terminal.cwd` (default - ``frozenset({"", "localhost"})``; :func:`~libvt.aio.open_pty` adds the - local machine hostname automatically). + to update :attr:`~libvt.terminal.Terminal.cwd`. ``None`` (default) + uses ``{"", "localhost"}`` in sans-I/O :class:`~libvt.terminal.Terminal` + and automatically adds the local hostname in + :func:`~libvt.aio.open_pty`. strict : bool - Raise :exc:`~libvt.exc.ProtocolError` on unrecognized escape sequences - instead of ignoring or recording :class:`~libvt.events.UnhandledSequence` - (default ``False``). + Raise :exc:`~libvt.exc.ProtocolError` on unrecognized or overflowing + escape sequences instead of ignoring or recording + :class:`~libvt.events.UnhandledSequence` (default ``False``). """ allow_title_report: bool = False @@ -108,10 +123,11 @@ class Policy: allow_clipboard_read: bool = False allow_clipboard_write: bool = True allow_color_queries: bool = True - allow_program_status_query: bool = False + allow_program_status_query: bool = True allow_unsafe_uris: bool = False allow_passthrough: bool = False - osc7_hosts: frozenset[str] = _DEFAULT_OSC7_HOSTS + abort_dispatch_osc: bool = False + osc7_hosts: frozenset[str] | None = None strict: bool = False @@ -128,7 +144,9 @@ class Limits: max_osc_bytes : int Maximum payload bytes buffered for an ``OSC`` sequence. max_dcs_bytes : int - Maximum payload bytes buffered for a ``DCS`` sequence. + Maximum payload bytes buffered for a ``DCS`` sequence (default + ``8_388_608``, sized above ``max_apc_bytes`` so 4 MiB graphics wrapped + in ``DCS tmux;`` fit without truncation). max_apc_bytes : int Maximum payload bytes buffered for an ``APC`` sequence. max_reply_bytes : int @@ -138,10 +156,14 @@ class Limits: max_prompt_zones : int Maximum ``OSC 133`` prompt zones retained on a terminal. max_status_records : int - Maximum concurrent ``OSC 7501`` task records retained in the store. + Maximum concurrent ``OSC 7501`` task records retained in the store + (default ``256``). max_events : int Maximum unread :data:`~libvt.events.Event` items retained when ``record_events=True``. + max_event_bytes : int + Maximum cumulative payload bytes retained across unread events when + ``record_events=True`` (default ``16_777_216``). max_keyboard_stack : int Maximum entries per screen in the Kitty ``CSI u`` keyboard stack. max_recorder_bytes : int @@ -151,31 +173,40 @@ class Limits: max_grapheme_codepoints: int = 32 max_csi_params: int = 32 max_osc_bytes: int = 131_072 - max_dcs_bytes: int = 4_194_304 + max_dcs_bytes: int = 8_388_608 max_apc_bytes: int = 4_194_304 max_reply_bytes: int = 65_536 max_rep_count: int = 4_096 max_prompt_zones: int = 1_024 - max_status_records: int = 64 + max_status_records: int = 256 max_events: int = 4_096 + max_event_bytes: int = 16_777_216 max_keyboard_stack: int = 8 max_recorder_bytes: int = 4_096 -XTERM_PROFILE = Profile() -DEFAULT_PROFILE = XTERM_PROFILE +DEFAULT_PROFILE = Profile() +XTERM_PROFILE = Profile( + name="xterm", + osc_7501_capabilities="", +) TMUX_PROFILE = Profile( name="tmux", osc_7501_capabilities="?", pending_wrap_phantom_col=True, + vs15_narrows_wide_emoji=False, + tmux_window_rename=True, ) DEFAULT_POLICY = Policy() +TMUX_CAPTURE_POLICY = Policy(allow_passthrough=True) DEFAULT_LIMITS = Limits() __all__ = [ "DEFAULT_LIMITS", + "DEFAULT_OSC7_HOSTS", "DEFAULT_POLICY", "DEFAULT_PROFILE", + "TMUX_CAPTURE_POLICY", "TMUX_PROFILE", "XTERM_PROFILE", "ColorScheme", diff --git a/src/libvt/events.py b/src/libvt/events.py index 2206ab6..f2e1ecb 100644 --- a/src/libvt/events.py +++ b/src/libvt/events.py @@ -142,6 +142,19 @@ class TitleChanged: title: str +@dataclass(frozen=True, slots=True) +class WindowRenamed: + r"""Emitted when ``ESC k ESC \`` updates the ``tmux`` window name. + + Attributes + ---------- + name : str + Reported window name string. + """ + + name: str + + @dataclass(frozen=True, slots=True) class WorkingDirectoryChanged: """Emitted when ``OSC 7`` or ``OSC 9;9`` updates the working directory. @@ -329,6 +342,7 @@ class UnhandledSequence: type Event = ( Bell | TitleChanged + | WindowRenamed | WorkingDirectoryChanged | ClipboardWrite | PromptMark @@ -363,5 +377,6 @@ class UnhandledSequence: "SixelGraphic", "TitleChanged", "UnhandledSequence", + "WindowRenamed", "WorkingDirectoryChanged", ] diff --git a/src/libvt/parser.py b/src/libvt/parser.py index 4ad3ea7..6cbd94f 100644 --- a/src/libvt/parser.py +++ b/src/libvt/parser.py @@ -559,6 +559,7 @@ class Parser: """Streaming VT500 / ANSI escape-sequence byte parser.""" __slots__ = ( + "_abort_dispatch_osc", "_csi_colon_mask", "_csi_cur", "_csi_has_digit", @@ -580,6 +581,7 @@ class Parser: "_str_overflow", "_tmux_dcs_state", "_tmux_passthrough", + "_tmux_window_rename", "_utf8", "_utf8_pending", ) @@ -589,6 +591,8 @@ def __init__( *, encoding: ParserEncoding = "utf-8", tmux_passthrough: bool = True, + tmux_window_rename: bool = False, + abort_dispatch_osc: bool = False, limits: Limits = DEFAULT_LIMITS, ) -> None: if encoding not in ("utf-8", "latin-1"): @@ -597,6 +601,8 @@ def __init__( self._encoding: ParserEncoding = encoding self._latin1: bool = encoding == "latin-1" self._tmux_passthrough: bool = tmux_passthrough + self._tmux_window_rename: bool = tmux_window_rename + self._abort_dispatch_osc: bool = abort_dispatch_osc self._limits = limits self._state: ParserState = ParserState.GROUND self._utf8 = codecs.getincrementaldecoder("utf-8")("replace") @@ -699,6 +705,11 @@ def _decode_utf8_bytes(self, raw: bytes | memoryview, sink: ActionSink) -> None: if cleaned: sink.on_print(cleaned) + def _notify_overflow(self, sink: ActionSink, kind: str, limit: int) -> None: + cb = getattr(sink, "on_overflow", None) + if cb is not None: + cb(kind, limit) + def _dispatch_osc(self, sink: ActionSink, terminator: bytes) -> None: if self._str_overflow: self._abort_string() @@ -726,8 +737,13 @@ def _dispatch_dcs(self, sink: ActionSink) -> None: self._abort_string() def _dispatch_apc(self, sink: ActionSink) -> None: - if self._str_kind == 0x5F and not self._str_overflow: - sink.on_apc(bytes(self._str_buf)) + if not self._str_overflow: + if self._str_kind == 0x5F: + sink.on_apc(bytes(self._str_buf)) + elif self._str_kind == 0x6B: + cb = getattr(sink, "on_window_rename", None) + if cb is not None: + cb(bytes(self._str_buf)) self._abort_string() def _enter_dcs_passthrough(self, final_byte: int) -> None: @@ -875,6 +891,7 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None: else: self._str_buf.clear() self._str_overflow = True + self._notify_overflow(sink, "osc", max_osc) if pos >= n: break b = mv[pos] @@ -915,6 +932,7 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None: else: self._str_buf.clear() self._str_overflow = True + self._notify_overflow(sink, "dcs", max_dcs) if pos >= n: break b = mv[pos] @@ -943,13 +961,20 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None: ): break pos += 1 - if pos > start and self._str_kind == 0x5F and not self._str_overflow: + if ( + pos > start + and self._str_kind in (0x5F, 0x6B) + and not self._str_overflow + ): chunk_len = pos - start - if len(self._str_buf) + chunk_len <= max_apc: + cap = max_apc if self._str_kind == 0x5F else max_osc + if len(self._str_buf) + chunk_len <= cap: self._str_buf.extend(mv[start:pos]) else: self._str_buf.clear() self._str_overflow = True + kind_name = "apc" if self._str_kind == 0x5F else "esc" + self._notify_overflow(sink, kind_name, cap) if pos >= n: break b = mv[pos] @@ -993,12 +1018,21 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None: else: self._str_buf.clear() self._str_overflow = True + self._notify_overflow(sink, "dcs", max_dcs) self._str_esc_origin = None self._state = ParserState.DCS_PASSTHROUGH continue - # Any other byte aborts the unclosed string per DEC STD 070 §5.1.2.3 - # and re-evaluates b starting from ESCAPE. - self._abort_string() + # Non-'\' byte exits string state; opt-in abort_dispatch_osc commits OSC + # except on CAN/SUB (0x18/0x1A), else abort-and-drop per DEC STD 070. + if ( + origin == ParserState.OSC_STRING + and self._abort_dispatch_osc + and b not in (0x18, 0x1A) + ): + self._dispatch_osc(sink, b"\x1b\\") + else: + self._abort_string() + self._intermediates.clear() self._state = ParserState.ESCAPE pos -= 1 continue @@ -1045,7 +1079,9 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None: self._str_buf.clear() self._str_overflow = False self._state = ParserState.DCS_ENTRY - elif b in (0x58, 0x5E, 0x5F): # SOS, PM, APC + elif b in (0x58, 0x5E, 0x5F) or ( + b == 0x6B and self._tmux_window_rename + ): # SOS, PM, APC, or tmux ESC k rename self._str_buf.clear() self._str_overflow = False self._str_kind = b diff --git a/src/libvt/pytest_plugin.py b/src/libvt/pytest_plugin.py index 042096c..b8fb99e 100644 --- a/src/libvt/pytest_plugin.py +++ b/src/libvt/pytest_plugin.py @@ -49,6 +49,7 @@ def __call__( env: collections.abc.Mapping[str, str] | None = None, cwd: str | os.PathLike[str] | None = None, tty_mode: TtyMode = "cooked", + python_executable: str | os.PathLike[str] | None = None, ) -> contextlib.AbstractAsyncContextManager[PtySession]: """Open a POSIX PTY subprocess session.""" @@ -130,6 +131,7 @@ def _spawn( env: collections.abc.Mapping[str, str] | None = None, cwd: str | os.PathLike[str] | None = None, tty_mode: TtyMode = "cooked", + python_executable: str | os.PathLike[str] | None = None, ) -> contextlib.AbstractAsyncContextManager[PtySession]: return open_pty( argv, @@ -138,6 +140,7 @@ def _spawn( env=env, cwd=cwd, tty_mode=tty_mode, + python_executable=python_executable, ) return _spawn diff --git a/src/libvt/screen.py b/src/libvt/screen.py index b4808d9..32fad56 100644 --- a/src/libvt/screen.py +++ b/src/libvt/screen.py @@ -193,64 +193,77 @@ def _slice_indices(s: slice, length: int) -> range: class RowView(collections.abc.Sequence[Cell]): """Read-only sequence view over one live viewport or scrollback row.""" - __slots__ = ("_col_range", "_row") + __slots__ = ("_col_range", "_row", "_row_idx", "_screen") - def __init__(self, row: RowLike, col_range: range | None = None) -> None: + def __init__( + self, + row: RowLike, + col_range: range | None = None, + *, + screen: Screen | None = None, + row_idx: int = -1, + ) -> None: self._row = row - total_cols = len(row.chars) if isinstance(row, _Row) else row.cols + self._screen = screen + self._row_idx = row_idx + total_cols = ( + screen.cols + if screen is not None + else (len(row.chars) if isinstance(row, _Row) else row.cols) + ) self._col_range = range(total_cols) if col_range is None else col_range + def _current_row(self) -> RowLike: + if self._screen is not None and 0 <= self._row_idx < len(self._screen._rows): + return self._screen._rows[self._row_idx] + return self._row + @property def wrapped(self) -> bool: """Return ``True`` when this row soft-wrapped onto the next line.""" - return self._row.wrapped + return self._current_row().wrapped @property def text(self) -> str: """Return right-trimmed rendered text for this row slice.""" - total_cols = ( - len(self._row.chars) if isinstance(self._row, _Row) else self._row.cols - ) + row = self._current_row() + total_cols = len(row.chars) if isinstance(row, _Row) else row.cols if self._col_range.start == 0 and self._col_range.stop == total_cols: - return self._row.rstrip_text() - limit = min(self._col_range.stop, self._row.used) + return row.rstrip_text() + row_t_used = row.text_used if isinstance(row, _Row) else row.used + limit = min(self._col_range.stop, row_t_used) if limit <= self._col_range.start: return "" - if isinstance(self._row, _Row): - raw = "".join(self._row.chars[self._col_range.start : limit]) + if isinstance(row, _Row): + raw = "".join(row.chars[self._col_range.start : limit]) else: - raw = "".join( - self._row.char_at(c) for c in range(self._col_range.start, limit) - ) + raw = "".join(row.char_at(c) for c in range(self._col_range.start, limit)) return raw.rstrip(" ") @property def runs(self) -> tuple[RowRun, ...]: """Return coalesced ``(style, hyperlink)`` spans up to ``used`` columns.""" - limit = min(self._col_range.stop, self._row.used) + row = self._current_row() + limit = min(self._col_range.stop, row.used) start_c = self._col_range.start if limit <= start_c: return () out: list[RowRun] = [] run_start = start_c - first_ext = self._row.ext_at(start_c) - cur_style = unpack_style(self._row.attr_at(start_c), first_ext) + first_ext = row.ext_at(start_c) + cur_style = unpack_style(row.attr_at(start_c), first_ext) cur_link = first_ext.hyperlink if first_ext is not None else None buf: list[str] = [] for c in range(start_c, limit): - word = self._row.attr_at(c) + word = row.attr_at(c) role_bits = raw_width_bits(word) if role_bits in (int(WidthRole.SPACER_TAIL), int(WidthRole.SPACER_HEAD)): continue - ext = self._row.ext_at(c) + ext = row.ext_at(c) st = unpack_style(word, ext) lnk = ext.hyperlink if ext is not None else None - ch = ( - self._row.chars[c] - if isinstance(self._row, _Row) - else self._row.char_at(c) - ) + ch = row.chars[c] if isinstance(row, _Row) else row.char_at(c) if st != cur_style or lnk != cur_link: out.append( RowRun( @@ -291,12 +304,18 @@ def __getitem__(self, index: slice) -> RowView: ... def __getitem__(self, index: int | slice) -> Cell | RowView: """Index one :class:`Cell` or slice a sub-range :class:`RowView`.""" + row = self._current_row() if isinstance(index, slice): sub = _slice_indices(index, len(self._col_range)) base = self._col_range.start - return RowView(self._row, range(base + sub.start, base + sub.stop)) + return RowView( + row, + range(base + sub.start, base + sub.stop), + screen=self._screen, + row_idx=self._row_idx, + ) norm = _normalize_index(index, len(self._col_range), axis="col") - return _materialize_cell(self._row, self._col_range.start + norm) + return _materialize_cell(row, self._col_range.start + norm) class RegionView(collections.abc.Sequence[RowView]): @@ -375,12 +394,14 @@ def slice_grid( rows: collections.abc.Sequence[RowLike], cols: int, key: int | slice | tuple[slice | int, slice | int], + *, + screen: Screen | None = None, ) -> RowView | Cell | RegionView: """Implement ``grid[r]``, ``grid[r, c]``, and ``grid[r1:r2, c1:c2]``.""" height = len(rows) if isinstance(key, int): nr = _normalize_index(key, height, axis="row") - return RowView(rows[nr]) + return RowView(rows[nr], screen=screen, row_idx=nr) if isinstance(key, slice): r_range = _slice_indices(key, height) return RegionView(rows[r_range.start : r_range.stop], range(cols)) @@ -526,13 +547,22 @@ def clear_history(self) -> None: """Clear all sealed scrollback rows (``ED 3``).""" self._history.clear() - def _clear_row_spacer_head(self, row_obj: _Row) -> None: + def _clear_row_spacer_head(self, row_obj: _Row) -> bool: if not row_obj.has_wide or row_obj.attrs is None: - return + return False last = self._cols - 1 if raw_width_bits(row_obj.attrs[last]) == int(WidthRole.SPACER_HEAD): row_obj.chars[last] = " " row_obj.attrs[last] &= _WIDTH_CLEAR_MASK + if row_obj.text_used == last + 1: + row_obj.text_used = last + while ( + row_obj.text_used > 0 + and row_obj.chars[row_obj.text_used - 1] == " " + and row_obj.attr_at(row_obj.text_used - 1) == 0 + and row_obj.ext_at(row_obj.text_used - 1) is None + ): + row_obj.text_used -= 1 while ( row_obj.used > 0 and row_obj.chars[row_obj.used - 1] == " " @@ -540,20 +570,41 @@ def _clear_row_spacer_head(self, row_obj: _Row) -> None: and row_obj.ext_at(row_obj.used - 1) is None ): row_obj.used -= 1 + return True + return False + + def heal_before_edit(self, row: int, col_start: int, col_end: int) -> None: + """Repair cross-row ``SPACER_HEAD`` pairs before mutating cells.""" + if not (0 <= row < len(self._rows)): + return + if col_start <= 1 and row > 0: + prev = self._rows[row - 1] + if self._clear_row_spacer_head(prev): + prev.wrapped = False + self._rows[row]._heal_wide_boundary(0) + if col_end > self._cols - 1: + cur = self._rows[row] + if self._clear_row_spacer_head(cur): + cur.wrapped = False + if row + 1 < len(self._rows): + self._rows[row + 1]._heal_wide_boundary(0) def heal_wrapped_spacer_head(self, row: int) -> None: - """Clear a preceding row's ``SPACER_HEAD`` when ``(row, 0)`` splits.""" + """Clear preceding ``SPACER_HEAD`` and ``wrapped`` if ``(row, 0)`` splits.""" if row <= 0 or row > len(self._rows): return prev = self._rows[row - 1] if not prev.has_wide or prev.attrs is None: return if row == len(self._rows) or not prev.wrapped: - self._clear_row_spacer_head(prev) + if self._clear_row_spacer_head(prev): + prev.wrapped = False return cur = self._rows[row] - if raw_width_bits(cur.attr_at(0)) != int(WidthRole.WIDE): - self._clear_row_spacer_head(prev) + if raw_width_bits(cur.attr_at(0)) != int( + WidthRole.WIDE + ) and self._clear_row_spacer_head(prev): + prev.wrapped = False @property def lines(self) -> tuple[str, ...]: @@ -582,7 +633,7 @@ def __getitem__( key: int | slice | tuple[slice | int, slice | int], ) -> RowView | Cell | RegionView: """Index a row, single ``(row, col)`` cell, or 2D region view.""" - return slice_grid(self._rows, self._cols, key) + return slice_grid(self._rows, self._cols, key, screen=self) def scroll_up( self, @@ -766,30 +817,38 @@ def _reflow_primary(self, *, rows: int, cols: int) -> None: idx += 1 # Extract logical cells across [group_start .. group_end]. - cells: list[tuple[str, int, int, _CellExt | None, bool]] = [] + cells: list[tuple[str, int, int, _CellExt | None, bool, bool]] = [] for r_i in range(group_start, group_end + 1): src = combined[r_i] is_last = r_i == group_end - limit = len(src.chars) if not is_last else src.used - if r_i == cur_abs_idx: - limit = max(limit, cur_col + 1) + src_t_used = src.text_used if isinstance(src, _Row) else len(src.text) + row_limit = len(src.chars) if not is_last else src_t_used + limit = max(row_limit, cur_col + 1) if r_i == cur_abs_idx else row_limit for c_i in range(limit): word = src.attr_at(c_i) rb = raw_width_bits(word) is_cur = r_i == cur_abs_idx and c_i == cur_col + is_dummy = is_last and c_i >= row_limit if rb == int(WidthRole.SPACER_HEAD): if is_cur: - cells.append((" ", 0, 1, None, True)) + cells.append((" ", 0, 1, None, True, True)) continue if rb == int(WidthRole.SPACER_TAIL): if is_cur and cells: - prev_ch, prev_w, prev_cw, prev_ext, _ = cells[-1] - cells[-1] = (prev_ch, prev_w, prev_cw, prev_ext, True) + p_ch, p_w, p_cw, p_ext, _, p_dum = cells[-1] + cells[-1] = (p_ch, p_w, p_cw, p_ext, True, p_dum) continue cw = 2 if rb == int(WidthRole.WIDE) else 1 base_word = word & _WIDTH_CLEAR_MASK cells.append( - (src.chars[c_i], base_word, cw, src.ext_at(c_i), is_cur) + ( + src.chars[c_i], + base_word, + cw, + src.ext_at(c_i), + is_cur, + is_dummy, + ) ) if not cells: @@ -804,7 +863,7 @@ def _reflow_primary(self, *, rows: int, cols: int) -> None: cur_out = _Row(cols) new_all.append(cur_out) out_col = 0 - for ch, base_w, cw, ce, is_cur in cells: + for ch, base_w, cw, ce, is_cur, is_dummy in cells: eff_cw = cw eff_ch = ch if eff_cw == 2 and cols == 1: @@ -812,9 +871,10 @@ def _reflow_primary(self, *, rows: int, cols: int) -> None: eff_cw = 1 if out_col + eff_cw > cols: - if out_col < cols: + if not is_dummy and out_col < cols: cur_out.write_spacer_head(out_col, 0, None) - cur_out.wrapped = True + if not is_dummy: + cur_out.wrapped = True cur_out = _Row(cols) new_all.append(cur_out) out_col = 0 @@ -824,22 +884,15 @@ def _reflow_primary(self, *, rows: int, cols: int) -> None: new_cur_col = out_col cursor_placed = True - if eff_cw == 2: + if is_dummy: + out_col += eff_cw + elif eff_cw == 2: cur_out.write_wide(out_col, eff_ch, base_w, ce) out_col += 2 else: cur_out.write_narrow(out_col, eff_ch, base_w, ce) out_col += 1 - # Re-trim trailing space added only to track cursor position. - while ( - cur_out.used > 0 - and cur_out.chars[cur_out.used - 1] == " " - and cur_out.attr_at(cur_out.used - 1) == 0 - and cur_out.ext_at(cur_out.used - 1) is None - ): - cur_out.used -= 1 - if not new_all: new_all.append(_Row(cols)) diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py index f1831d2..b179bdd 100644 --- a/src/libvt/terminal.py +++ b/src/libvt/terminal.py @@ -24,14 +24,17 @@ ) from libvt._ucd import ( CLUSTER_NONE, + GCB_PREPEND, WidthRole, char_width, init_cluster_state, sanitize_terminal_text, step_cluster, + ucd_lookup, ) from libvt.config import ( DEFAULT_LIMITS, + DEFAULT_OSC7_HOSTS, DEFAULT_POLICY, DEFAULT_PROFILE, Limits, @@ -59,6 +62,7 @@ SixelGraphic, TitleChanged, UnhandledSequence, + WindowRenamed, WorkingDirectoryChanged, ) from libvt.exc import ProtocolError @@ -491,7 +495,8 @@ def _render_vt(self, snapshot: Snapshot) -> str: for r_idx, row in enumerate(snapshot._rows): if r_idx > 0: out.append("\r\n" if not snapshot._rows[r_idx - 1].wrapped else "") - for c in range(row.used): + limit = row.used if row.wrapped else row.text_used + for c in range(limit): word = row.attr_at(c) rb = raw_width_bits(word) if rb in (int(WidthRole.SPACER_TAIL), int(WidthRole.SPACER_HEAD)): @@ -597,6 +602,49 @@ def on_dcs( def on_apc(self, data: bytes) -> None: self._term._handle_apc(data) + def on_overflow(self, kind: str, limit: int) -> None: + self._term._unhandled(kind, f"{kind.upper()} overflow (>{limit} bytes)") + + def on_window_rename(self, data: bytes) -> None: + self._term._handle_window_rename(data) + + +def _event_byte_cost(event: Event) -> int: + if isinstance(event, Passthrough): + return 64 + len(event.data) + if isinstance(event, SixelGraphic): + return 64 + len(event.data.payload) + if isinstance(event, KittyGraphic): + return 64 + len(event.command.payload) + if isinstance(event, ClipboardWrite): + return 64 + len(event.text) + return 64 + + +def _parse_osc_rgb(spec: bytes) -> tuple[int, int, int] | None: + text = spec.decode("ascii", errors="ignore").strip() + if text.startswith("#") and len(text) == 7: + try: + return (int(text[1:3], 16), int(text[3:5], 16), int(text[5:7], 16)) + except ValueError: + return None + if text.lower().startswith("rgb:"): + parts = text[4:].split("/") + if len(parts) != 3: + return None + vals: list[int] = [] + for comp in parts: + if not (1 <= len(comp) <= 4): + return None + try: + raw = int(comp, 16) + except ValueError: + return None + scale = (1 << (4 * len(comp))) - 1 + vals.append((raw * 255) // scale) + return (vals[0], vals[1], vals[2]) + return None + def _hex_encode(text: str) -> str: return text.encode("utf-8").hex() @@ -631,18 +679,19 @@ def __init__( record_events: bool = False, recorder: FlightRecorder | None = None, encoding: ParserEncoding = "utf-8", + newline_mode: bool = False, ) -> None: self._profile = profile self._policy = policy self._limits = limits self._encoding: ParserEncoding = encoding + self._newline_mode: bool = newline_mode self._on_event = on_event self._on_pty_write = on_pty_write self._record_events = record_events self._recorder = recorder - self._events: collections.deque[Event] = collections.deque( - maxlen=limits.max_events, - ) + self._events: collections.deque[Event] = collections.deque() + self._event_bytes: int = 0 self._screens = ScreenSet( rows=rows, cols=cols, @@ -650,7 +699,15 @@ def __init__( keyboard_stack_depth=limits.max_keyboard_stack, ) self._modes = ModeState() - self._parser = Parser(encoding=encoding, limits=limits) + if newline_mode: + self._modes.set_mode(Mode.LNM, enabled=True) + self._parser = Parser( + encoding=encoding, + tmux_window_rename=profile.tmux_window_rename, + abort_dispatch_osc=policy.abort_dispatch_osc, + limits=limits, + ) + self._passthrough_parser: Parser | None = None self._sink = _TerminalSink(self) self._sgr_memo: dict[tuple[Style, CsiParams], Style] = {} self._style: Style = DEFAULT_STYLE @@ -667,7 +724,11 @@ def __init__( self._last_printed_pos: tuple[int, int] | None = None self._cluster_state: int = CLUSTER_NONE self._cluster_len: int = 0 + self._pending_prepend: str = "" self._title: str = "" + self._window_name: str = "" + self._fg_rgb: tuple[int, int, int] = profile.fg_rgb + self._bg_rgb: tuple[int, int, int] = profile.bg_rgb self._title_stack: list[str] = [] self._cwd: str = "" self._cwd_uri: str = "" @@ -766,6 +827,11 @@ def title(self) -> str: """Return window title set by ``OSC 0`` / ``OSC 2``.""" return self._title + @property + def window_name(self) -> str: + r"""Return ``tmux`` window name set by ``ESC k ESC \``.""" + return self._window_name + @property def cwd(self) -> str: """Return local working directory path accepted under ``Policy.osc7_hosts``.""" @@ -892,7 +958,18 @@ def __getitem__( def _emit_event(self, event: Event) -> None: if self._record_events: - self._events.append(event) + max_ev = self._limits.max_events + max_bytes = self._limits.max_event_bytes + cost = _event_byte_cost(event) + if max_ev > 0 and max_bytes > 0: + while self._events and ( + len(self._events) >= max_ev or self._event_bytes + cost > max_bytes + ): + dropped = self._events.popleft() + self._event_bytes -= _event_byte_cost(dropped) + if cost <= max_bytes: + self._events.append(event) + self._event_bytes += cost if self._on_event is not None: self._on_event(event) @@ -909,6 +986,7 @@ def drain_events(self) -> tuple[Event, ...]: return () out = tuple(self._events) self._events.clear() + self._event_bytes = 0 return out def drain_replies(self) -> bytes: @@ -972,6 +1050,7 @@ def _clear_cluster_anchor(self) -> None: self._last_printed_pos = None self._cluster_state = CLUSTER_NONE self._cluster_len = 0 + self._pending_prepend = "" def _sync_pen_cache(self) -> None: self._pen_word = pack_pen_base(self._style) @@ -1026,6 +1105,8 @@ def reset(self, *, soft: bool = False) -> None: was_sync = self.synchronized was_alt = self._screens.active_is_alt self._modes = ModeState() + if self._newline_mode: + self._modes.set_mode(Mode.LNM, enabled=True) self._sync_hold_pending = False self._held_snapshot = None if was_sync: @@ -1050,12 +1131,16 @@ def reset(self, *, soft: bool = False) -> None: scr.keyboard_stack.reset() else: self._parser.reset() + self._passthrough_parser = None self._screens.active_is_alt = False self._screens.primary.reset() self._screens.alternate.reset() self._saved_primary = _SavedCursor() self._saved_alt = _SavedCursor() self._title = "" + self._window_name = "" + self._fg_rgb = self._profile.fg_rgb + self._bg_rgb = self._profile.bg_rgb self._title_stack.clear() self._cwd = "" self._cwd_uri = "" @@ -1240,7 +1325,7 @@ def _handle_print(self, text: str) -> None: insert_mode = self._modes.is_set(Mode.IRM) _, bottom, left, right = self._effective_margins(scr) - if text.isascii() and not insert_mode: + if text.isascii() and not insert_mode and not self._pending_prepend: mode_2027_ascii = self._modes.is_set(Mode.GRAPHEME_CLUSTERING) pos = 0 total = len(text) @@ -1260,14 +1345,13 @@ def _handle_print(self, text: str) -> None: avail = max_col - c_col + 1 seg = text[pos : pos + avail] seg_len = len(seg) + scr.heal_before_edit(scr._cur_row, c_col, c_col + seg_len) scr._rows[scr._cur_row].write_ascii_slice( c_col, seg, self._pen_word, self._cell_ext, ) - if c_col <= 1: - scr.heal_wrapped_spacer_head(scr._cur_row) pos += seg_len end_col = c_col + seg_len - 1 if c_col + seg_len > max_col: @@ -1296,15 +1380,42 @@ def _handle_print(self, text: str) -> None: return mode_2027 = self._modes.is_set(Mode.GRAPHEME_CLUSTERING) + vs15_narrows = self._profile.vs15_narrows_wide_emoji + vs16_wide = self._profile.vs16_always_wide max_cluster = self._limits.max_grapheme_codepoints for ch in text: cp = ord(ch) - if self._last_printed_pos is not None: + if self._pending_prepend: + extends, next_state, _ = step_cluster( + self._cluster_state, + cp, + mode_2027=mode_2027, + vs15_narrows=vs15_narrows, + vs16_always_wide=vs16_wide, + ) + if extends: + w_prep = char_width(ch) + if w_prep == 0: + if len(self._pending_prepend) < max_cluster - 1: + self._pending_prepend += ch + self._cluster_state = next_state + continue + ch_full = self._pending_prepend + ch + self._pending_prepend = "" + else: + self._pending_prepend = "" + ch_full = ch + else: + ch_full = ch + + if len(ch_full) == 1 and self._last_printed_pos is not None: extends, next_state, w_override = step_cluster( self._cluster_state, cp, mode_2027=mode_2027, + vs15_narrows=vs15_narrows, + vs16_always_wide=vs16_wide, ) if extends: self._cluster_state = next_state @@ -1364,6 +1475,12 @@ def _handle_print(self, text: str) -> None: ) continue + if ( + w_override == 2 + and cur_role == int(WidthRole.NARROW) + and pc + 1 < scr.cols + ): + scr.heal_before_edit(pr, pc, pc + 2) row_obj.append_grapheme( pc, ch, @@ -1410,15 +1527,21 @@ def _handle_print(self, text: str) -> None: clear_cluster=False, ) continue - else: + elif len(ch_full) == 1: _, next_state, _ = step_cluster( CLUSTER_NONE, cp, mode_2027=mode_2027, + vs15_narrows=vs15_narrows, + vs16_always_wide=vs16_wide, ) width = char_width(ch) if width == 0: + if mode_2027 and ((ucd_lookup(cp) >> 2) & 0x0F) == GCB_PREPEND: + self._last_printed_pos = None + self._pending_prepend = ch + self._cluster_state = next_state continue c_row = scr._cur_row @@ -1455,9 +1578,12 @@ def _handle_print(self, text: str) -> None: c_row = scr._cur_row c_col = scr._cur_col else: - ch = "\ufffd" + ch_full = "\ufffd" width = 1 + if not just_wrapped_wide: + scr.heal_before_edit(c_row, c_col, c_col + width) + row_obj = scr._rows[c_row] if insert_mode: bce_w, bce_e = self._bce_pair() @@ -1473,7 +1599,7 @@ def _handle_print(self, text: str) -> None: if width == 2 and c_col + 1 <= max_col: row_obj.write_wide( c_col, - ch, + ch_full, self._pen_word, self._cell_ext, ) @@ -1497,7 +1623,7 @@ def _handle_print(self, text: str) -> None: else: row_obj.write_narrow( c_col, - ch, + ch_full, self._pen_word, self._cell_ext, ) @@ -1519,13 +1645,10 @@ def _handle_print(self, text: str) -> None: clear_cluster=False, ) - if c_col <= 1 and not just_wrapped_wide: - scr.heal_wrapped_spacer_head(c_row) - - self._last_printed = ch + self._last_printed = ch_full self._last_printed_pos = (c_row, placed_col) self._cluster_state = next_state - self._cluster_len = 1 + self._cluster_len = len(ch_full) def _cursor_left(self, scr: Screen, count: int, *, is_backspace: bool) -> None: _, top, left, right = ( @@ -1778,6 +1901,7 @@ def _erase_display( c_row = scr._cur_row c_col = scr._cur_col if mode == 0: + scr.heal_before_edit(c_row, c_col, scr.cols) scr._rows[c_row].clear_range( c_col, scr.cols, @@ -1785,8 +1909,6 @@ def _erase_display( bce_e, selective=selective, ) - if c_col <= 1: - scr.heal_wrapped_spacer_head(c_row) scr._rows[c_row].wrapped = False for r in range(c_row + 1, scr.rows): scr._rows[r].clear_range(0, scr.cols, bce_w, bce_e, selective=selective) @@ -1799,6 +1921,7 @@ def _erase_display( elif mode == 1: for r in range(c_row): scr._rows[r].clear_range(0, scr.cols, bce_w, bce_e, selective=selective) + scr.heal_before_edit(c_row, 0, c_col + 1) scr._rows[c_row].clear_range( 0, c_col + 1, @@ -1806,9 +1929,6 @@ def _erase_display( bce_e, selective=selective, ) - scr.heal_wrapped_spacer_head(c_row) - if c_row + 1 < scr.rows: - scr.heal_wrapped_spacer_head(c_row + 1) if c_row > 0: self._notify_erase(Rect(0, 0, c_row, scr.cols), cause) self._notify_erase(Rect(c_row, 0, 1, c_col + 1), cause) @@ -1840,6 +1960,7 @@ def _erase_line( c_row = scr._cur_row c_col = scr._cur_col if mode == 0: + scr.heal_before_edit(c_row, c_col, scr.cols) scr._rows[c_row].clear_range( c_col, scr.cols, @@ -1847,11 +1968,10 @@ def _erase_line( bce_e, selective=selective, ) - if c_col <= 1: - scr.heal_wrapped_spacer_head(c_row) scr._rows[c_row].wrapped = False self._notify_erase(Rect(c_row, c_col, 1, scr.cols - c_col), cause) elif mode == 1: + scr.heal_before_edit(c_row, 0, c_col + 1) scr._rows[c_row].clear_range( 0, c_col + 1, @@ -1859,11 +1979,11 @@ def _erase_line( bce_e, selective=selective, ) - scr.heal_wrapped_spacer_head(c_row) if c_col + 1 >= scr.cols: scr._rows[c_row].wrapped = False self._notify_erase(Rect(c_row, 0, 1, c_col + 1), cause) elif mode == 2: + scr.heal_before_edit(c_row, 0, scr.cols) scr._rows[c_row].clear_range( 0, scr.cols, @@ -1871,7 +1991,6 @@ def _erase_line( bce_e, selective=selective, ) - scr.heal_wrapped_spacer_head(c_row) self._notify_erase(Rect(c_row, 0, 1, scr.cols), cause) self._set_cursor(scr, c_row, c_col, pending_wrap=False) @@ -2095,9 +2214,8 @@ def _handle_csi( self._before_mutate() n = min(scr.cols - c_col, params.get(0, 1)) bce_w, bce_e = self._bce_pair() + scr.heal_before_edit(c_row, c_col, c_col + n) scr._rows[c_row].clear_range(c_col, c_col + n, bce_w, bce_e) - if c_col <= 1: - scr.heal_wrapped_spacer_head(c_row) if c_col + n >= scr.cols: scr._rows[c_row].wrapped = False self._notify_erase(Rect(c_row, c_col, 1, n), EraseCause.ECH) @@ -2106,6 +2224,7 @@ def _handle_csi( self._before_mutate() n = params.get(0, 1) bce_w, bce_e = self._bce_pair() + scr.heal_before_edit(c_row, c_col, right + 1) scr._rows[c_row].insert_blanks( c_col, n, @@ -2114,13 +2233,14 @@ def _handle_csi( bce_word=bce_w, bce_ext=bce_e, ) - if c_col <= 1: - scr.heal_wrapped_spacer_head(c_row) self._set_cursor(scr, c_row, c_col, pending_wrap=False) elif ch_final == "P": # DCH self._before_mutate() n = params.get(0, 1) bce_w, bce_e = self._bce_pair() + scr.heal_before_edit(c_row, c_col, right + 1) + if c_col == 0 and left == 0 and c_row > 0: + scr._rows[c_row - 1].wrapped = False scr._rows[c_row].delete_cells( c_col, n, @@ -2129,8 +2249,6 @@ def _handle_csi( bce_word=bce_w, bce_ext=bce_e, ) - if c_col <= 1: - scr.heal_wrapped_spacer_head(c_row) if right == scr.cols - 1: scr._rows[c_row].wrapped = False self._set_cursor(scr, c_row, c_col, pending_wrap=False) @@ -2313,24 +2431,54 @@ def _handle_csi( else: self._unhandled("csi", f"CSI {ch_final}") - def _update_cwd(self, raw_uri: str) -> None: - cleaned = sanitize_terminal_text(raw_uri.strip()) - if not cleaned: + def _handle_window_rename(self, raw: bytes) -> None: + try: + name = raw.decode("utf-8", errors="strict") + except UnicodeDecodeError: + return + self._window_name = name + self._emit_event(WindowRenamed(name=name)) + + def _update_cwd(self, raw_uri: str, *, from_osc7: bool = True) -> None: + cleaned = raw_uri.strip() + if not cleaned or "\x00" in cleaned: self._cwd = "" self._cwd_uri = "" self._emit_event(WorkingDirectoryChanged(uri="", path="")) return - self._cwd_uri = cleaned - if cleaned.startswith("file://"): - parsed = urllib.parse.urlsplit(cleaned) - host = (parsed.hostname or "").lower() - path = urllib.parse.unquote(parsed.path) - if host in self._policy.osc7_hosts: - self._cwd = path - self._emit_event(WorkingDirectoryChanged(uri=cleaned, path=path)) + safe_uri = sanitize_terminal_text(cleaned) + self._cwd_uri = safe_uri + if not from_osc7 and not cleaned.startswith("file://"): + self._cwd = safe_uri + self._emit_event(WorkingDirectoryChanged(uri=safe_uri, path=safe_uri)) return - self._cwd = cleaned - self._emit_event(WorkingDirectoryChanged(uri=cleaned, path=cleaned)) + parsed = urllib.parse.urlsplit(cleaned) + if parsed.scheme.lower() != "file" or not parsed.path.startswith("/"): + self._cwd = "" + self._emit_event(WorkingDirectoryChanged(uri=safe_uri, path="")) + return + raw_host = urllib.parse.unquote(parsed.hostname or "").lower() + allowed_hosts = ( + self._policy.osc7_hosts + if self._policy.osc7_hosts is not None + else DEFAULT_OSC7_HOSTS + ) + raw_path = urllib.parse.unquote_to_bytes(parsed.path) + if b"\x00" in raw_path: + self._cwd = "" + self._emit_event(WorkingDirectoryChanged(uri=safe_uri, path="")) + return + decoded_path = os.fsdecode(raw_path) + if raw_host in allowed_hosts: + self._cwd = decoded_path + else: + self._cwd = "" + self._emit_event( + WorkingDirectoryChanged( + uri=safe_uri, + path=sanitize_terminal_text(decoded_path), + ), + ) def _handle_osc(self, code: int, data: bytes, terminator: bytes) -> None: scr = self._screens.active @@ -2343,7 +2491,7 @@ def _handle_osc(self, code: int, data: bytes, terminator: bytes) -> None: elif code == 1: return elif code == 7: - self._update_cwd(data.decode("utf-8", errors="replace")) + self._update_cwd(data.decode("utf-8", errors="replace"), from_osc7=True) elif code == 8: text = data.decode("utf-8", errors="replace") sep = text.find(";") @@ -2371,15 +2519,30 @@ def _handle_osc(self, code: int, data: bytes, terminator: bytes) -> None: if changed: self._emit_event(ProgramStatusChanged(status=status, task_id="")) elif len(parts) >= 2 and parts[0] == "9": - self._update_cwd(";".join(parts[1:])) - elif code in (10, 11) and data == b"?" and self._policy.allow_color_queries: - r, g, b = self._profile.fg_rgb if code == 10 else self._profile.bg_rgb - reply = ( - f"\x1b]{code};rgb:{r:02x}{r:02x}/{g:02x}{g:02x}/{b:02x}{b:02x}".encode( - "ascii", - ) - ) - self._emit_reply(reply + out_term) + self._update_cwd(";".join(parts[1:]), from_osc7=False) + elif code in (10, 11): + if data == b"?": + if self._policy.allow_color_queries: + r, g, b = self._fg_rgb if code == 10 else self._bg_rgb + reply = ( + f"\x1b]{code};rgb:{r:02x}{r:02x}/{g:02x}{g:02x}/{b:02x}{b:02x}" + ).encode("ascii") + self._emit_reply(reply + out_term) + return + parsed_rgb = _parse_osc_rgb(data) + if parsed_rgb is not None: + if code == 10: + self._fg_rgb = parsed_rgb + else: + self._bg_rgb = parsed_rgb + elif code == 12: + return + elif code == 110: + self._fg_rgb = self._profile.fg_rgb + elif code == 111: + self._bg_rgb = self._profile.bg_rgb + elif code == 112: + return elif code == 52: semi = data.find(b";") if semi == -1: @@ -2432,13 +2595,8 @@ def _handle_osc(self, code: int, data: bytes, terminator: bytes) -> None: ) elif code == 7501: if data == b"?": - has_consumer = ( - self._policy.allow_program_status_query - or self._on_event is not None - or self._record_events - ) - if has_consumer: - cap = self._profile.osc_7501_capabilities + cap = self._profile.osc_7501_capabilities + if self._policy.allow_program_status_query and cap: self._emit_reply(f"\x1b]7501;{cap}".encode("ascii") + out_term) return changed, rec = self._status_store.apply_osc_7501(data) @@ -2530,10 +2688,22 @@ def _handle_dcs( if self._record_events or self._on_event is not None: self._emit_event(Passthrough(data=unwrapped)) if self._policy.allow_passthrough and self._passthrough_depth < 2: - inner_parser = Parser( - encoding=self._encoding, - limits=self._limits, - ) + if self._passthrough_depth == 0: + if self._passthrough_parser is None: + self._passthrough_parser = Parser( + encoding=self._encoding, + tmux_window_rename=self._profile.tmux_window_rename, + abort_dispatch_osc=self._policy.abort_dispatch_osc, + limits=self._limits, + ) + inner_parser = self._passthrough_parser + else: + inner_parser = Parser( + encoding=self._encoding, + tmux_window_rename=self._profile.tmux_window_rename, + abort_dispatch_osc=self._policy.abort_dispatch_osc, + limits=self._limits, + ) self._passthrough_depth += 1 try: inner_parser.feed_to(unwrapped, self._sink) @@ -2594,9 +2764,16 @@ def render( rows: int = 24, cols: int = 80, profile: Profile = DEFAULT_PROFILE, + newline_mode: bool = False, ) -> str: """Emulate *data* on a fresh ``(rows, cols)`` terminal and return ``text``.""" - term = Terminal(rows=rows, cols=cols, scrollback=0, profile=profile) + term = Terminal( + rows=rows, + cols=cols, + scrollback=0, + profile=profile, + newline_mode=newline_mode, + ) if isinstance(data, str): term.feed_str(data) else: diff --git a/tests/test_aio_and_pytest.py b/tests/test_aio_and_pytest.py index fe71596..583b9b3 100644 --- a/tests/test_aio_and_pytest.py +++ b/tests/test_aio_and_pytest.py @@ -93,8 +93,8 @@ async def test_open_pty_controlling_tty_signals_tty_mode_and_errors( "print('DSR=' + repr(reply.decode('ascii', 'replace')), flush=True)\n" "while not winch:\n" " signal.pause()\n" - "print('WINCH=1', flush=True)\n" "try:\n" + " print('WINCH=1', flush=True)\n" " while True:\n" " signal.pause()\n" "except KeyboardInterrupt:\n" @@ -132,6 +132,24 @@ async def test_open_pty_controlling_tty_signals_tty_mode_and_errors( async with open_pty(("definitely-missing-libvt-command-xyz",)): pass + # Interactive bash + background sleep pipeline reaps cleanly via killpg(SIGHUP), + # and custom Policy still receives local hostname in osc7_hosts! + bash_bin = shutil.which("bash") + if bash_bin is not None: + async with open_pty( + (bash_bin, "--norc", "--noprofile", "-i"), + rows=6, + cols=60, + policy=libvt.Policy(allow_passthrough=True), + ) as bash_sess: + bash_sess.send( + f"printf '\\033]7;file://{host}/tmp\\007'\n" + "sleep 30 &\n" + "printf 'BG_%s\\n' OK\n" + ) + await bash_sess.wait_for("BG_OK", timeout=3.0) + assert bash_sess.terminal.cwd == "/tmp" + def test_assert_screen_literal_borders_and_assert_screen_box( vt_terminal: Terminal, @@ -190,8 +208,7 @@ def test_assert_screen_literal_borders_and_assert_screen_box( spoof_term = vt_factory(rows=1, cols=10, recorder=vt_recorder) spoof_term.feed(b"\x1b[31mhi") - spoof_term.screen._rows[0].chars[2] = "\u202e" - spoof_term.screen._rows[0].used = 3 + spoof_term.screen._rows[0].write_narrow(2, "\u202e", 0, None) with pytest.raises(AssertionError) as exc_info: assert_screen_box(spoof_term, "┌──────────┐\n│mismatch │\n└──────────┘") msg = str(exc_info.value) diff --git a/tests/test_parser.py b/tests/test_parser.py index 6d9ae63..e818a1a 100644 --- a/tests/test_parser.py +++ b/tests/test_parser.py @@ -147,12 +147,27 @@ def test_string_esc_abort_and_oversized_payload_recovery() -> None: assert p.state == ParserState.GROUND # Ubiquitty OSC-G4 on Terminal: unclosed OSC 2 followed by ESC [ 31 m drops title. - term = libvt.Terminal(rows=4, cols=20, limits=Limits(max_osc_bytes=16)) - term.feed(b"\x1b]2;unterminated\x1b[32mok") + term = libvt.Terminal( + rows=4, + cols=20, + limits=Limits(max_osc_bytes=16), + record_events=True, + ) + term.feed(b"\x1b]2;cut\x1b[32mok") assert term.title == "" assert term.text == "ok" assert term[0, 0].style.fg == AnsiColor.GREEN + # Opt-in abort_dispatch_osc=True commits interrupted OSC payloads on ESC (not CAN). + opt_term = libvt.Terminal( + rows=4, + cols=20, + policy=libvt.Policy(abort_dispatch_osc=True), + ) + opt_term.feed(b"\x1b]2;committed\x1b[31mR\x1b]2;cancelled\x18X") + assert opt_term.title == "committed" + assert opt_term.text == "RX" + # Double ESC inside OSC cancels OSC and treats second ESC \ as standalone ST no-op. term.reset() term.feed(b"\x1b]2;short\x1b\x1b\\after") @@ -167,10 +182,12 @@ def test_string_esc_abort_and_oversized_payload_recovery() -> None: assert not any(isinstance(a, DcsDispatch) for a in strict_dcs) term.reset() + term.drain_events() term.feed(b"\x1b]2;" + (b"x" * 64) + b"\x07clean") assert term.title == "" assert term.text == "clean" assert term.parser_state == ParserState.GROUND + assert any(isinstance(ev, libvt.UnhandledSequence) for ev in term.drain_events()) # Exercise SGR memo FIFO eviction past 256 unique entries. for idx in range(300): diff --git a/tests/test_protocols_and_input.py b/tests/test_protocols_and_input.py index 461f946..78c49fc 100644 --- a/tests/test_protocols_and_input.py +++ b/tests/test_protocols_and_input.py @@ -31,13 +31,24 @@ def test_osc_7501_rex_grammar_hierarchy_urgency_and_queries() -> None: """Rex ``OSC 7501`` enforces grammar, hierarchy, urgency, and pruning.""" - silent_term = libvt.Terminal(rows=4, cols=30) - silent_term.feed(b"\x1b]7501;?\x07") - assert silent_term.drain_replies() == b"" + pull_term = libvt.Terminal(rows=4, cols=30, record_events=False) + pull_term.feed(b"\x1b]7501;?\x07") + pull_reply = pull_term.drain_replies() + assert pull_reply.startswith(b"\x1b]7501;?:") + assert pull_reply.endswith(b"\x07") + + suppressed = libvt.Terminal( + rows=4, + cols=30, + policy=Policy(allow_program_status_query=False), + record_events=True, + ) + suppressed.feed(b"\x1b]7501;?\x07") + assert suppressed.drain_replies() == b"" term = libvt.Terminal(rows=6, cols=40, record_events=True) term.feed(b"\x1b]7501;?\x07") - assert term.drain_replies().endswith(b"\x07") + assert term.drain_replies() == pull_reply term.feed(b"\x1b]7501;?\x1b\\") reply_st = term.drain_replies() assert reply_st.startswith(b"\x1b]7501;?:") @@ -106,14 +117,19 @@ def test_osc_133_abs_row_osc_7_osc_52_and_tmux_passthrough() -> None: assert [z.abs_row for z in zones] == sorted(z.abs_row for z in zones) assert zones[-1].exit_code == 0 - # OSC 7: localhost updates cwd & cwd_uri; remote updates cwd_uri only. + # OSC 7: localhost updates cwd & cwd_uri; remote / non-file / NUL clears cwd! term.feed(b"\x1b]7;file://localhost/tmp/my%20dir\x07") assert term.cwd == "/tmp/my dir" assert term.cwd_uri == "file://localhost/tmp/my%20dir" term.feed(b"\x1b]7;file://remote-box.example/srv\x07") - assert term.cwd == "/tmp/my dir" + assert term.cwd == "" assert term.cwd_uri == "file://remote-box.example/srv" assert term.snapshot().cwd_uri == "file://remote-box.example/srv" + term.feed(b"\x1b]7;kitty-shell-cwd://localhost/srv\x07") + assert term.cwd == "" + assert term.cwd_uri == "kitty-shell-cwd://localhost/srv" + term.feed(b"\x1b]7;file://localhost/bad%00path\x07") + assert term.cwd == "" # Empty OSC 7 clears both cwd and cwd_uri. term.feed(b"\x1b]7;\x07") @@ -163,7 +179,27 @@ def test_osc_133_abs_row_osc_7_osc_52_and_tmux_passthrough() -> None: b"\x1b\x1b\\\x1b\\", ) assert "nested2" in allow_term.program_statuses - assert any(isinstance(e, Passthrough) for e in allow_term.drain_events()) + # Split DCS tmux; envelopes preserve inner parser state across packets! + allow_term.feed(b"\x1bPtmux;\x1b\x1b]2;hel\x1b\\" + b"\x1bPtmux;lo\x07\x1b\\") + assert allow_term.title == "hello" + assert allow_term.text == "" + + # TMUX_PROFILE consumes ESC k ESC \ without printing to cells, and + # OSC 10/11 + OSC 110/111 dynamic color overrides/resets work cleanly. + tmux_term = libvt.Terminal( + rows=3, + cols=20, + profile=libvt.TMUX_PROFILE, + policy=Policy(strict=True), + ) + tmux_term.feed(b"\x1bkbuild-win\x1b\\OK\x1b]10;rgb:11/22/33\x1b\\\x1b]110\x1b\\") + assert tmux_term.text == "OK" + assert tmux_term.window_name == "build-win" + assert libvt.render(b"line1\nline2", rows=2, cols=10, newline_mode=True) == ( + "line1\nline2" + ) + assert libvt.DEFAULT_LIMITS.max_dcs_bytes > libvt.DEFAULT_LIMITS.max_apc_bytes + assert libvt.DEFAULT_LIMITS.max_status_records == 256 def test_kitty_keyboard_stack_and_input_encoding() -> None: diff --git a/tests/test_ucd_and_grid.py b/tests/test_ucd_and_grid.py index a935b1a..69c0430 100644 --- a/tests/test_ucd_and_grid.py +++ b/tests/test_ucd_and_grid.py @@ -11,11 +11,14 @@ from libvt._ucd import ( EXT_PICT_BIT, WidthRole, + char_width, display_width, segment_graphemes, ucd_lookup, ) +from libvt.config import TMUX_PROFILE, XTERM_PROFILE from libvt.modes import Mode +from libvt.terminal import Formatter, OutputFormat def test_unicode_17_grapheme_break_test_vectors() -> None: @@ -90,6 +93,17 @@ def test_unicode_width_flags_zwj_incb_and_variation_selectors() -> None: assert display_width("❤\ufe0f") == 2 assert display_width("#\ufe0f\u20e3") == 2 assert display_width("⌚\ufe0e") == 1 + assert display_width("⌚\ufe0e\ufe0f") == 1 + assert display_width("⌚\u0301\ufe0e") == 2 + assert display_width("⌚\ufe0e", profile=TMUX_PROFILE) == 2 + assert display_width("क्ष") == 2 + assert display_width("स्त्र") == 2 + assert display_width("\u0995\u09cb") == 2 + assert char_width("\u09cb") == 0 + assert char_width("\u1161") == 0 + assert char_width("\u0600") == 0 + assert display_width("\u06001") == 1 + assert display_width("\u1100\u1161\u11a8") == 2 term = libvt.Terminal(rows=4, cols=10) term.feed("🇯🇵🇺🇸!".encode()) @@ -107,7 +121,22 @@ def test_unicode_width_flags_zwj_incb_and_variation_selectors() -> None: assert term[0, 0].text == "🧑‍🌾" assert term[0, 0].width == 2 assert term[0, 2].text == "क्ष" - assert term[0, 3].text == "A" + assert term[0, 2].width == 2 + assert term[0, 4].text == "A" + + # Prepend + narrow ASCII stays 1 column on Terminal as well as display_width. + term.reset() + term.feed_str("\u06001!") + assert term[0, 0].text == "\u06001" + assert term[0, 0].width == 1 + assert term[0, 1].text == "!" + + # TMUX_PROFILE preserves width 2 on VS15 (matching live tmux 3.8a). + tmux_term = libvt.Terminal(rows=2, cols=10, profile=TMUX_PROFILE) + tmux_term.feed_str("⌚\ufe0e!") + assert tmux_term[0, 0].width == 2 + assert tmux_term.cursor.col == 3 + assert XTERM_PROFILE.name == "xterm" # VS16 widening at right margin (col == cols - 1) wraps cleanly with SPACER_HEAD. narrow_term = libvt.Terminal(rows=3, cols=4) @@ -120,14 +149,50 @@ def test_unicode_width_flags_zwj_incb_and_variation_selectors() -> None: assert narrow_term.cursor.row == 1 assert narrow_term.cursor.col == 2 - # Overwriting (1, 0) with narrow 'Z' heals (0, 3) SPACER_HEAD and keeps wrapped. + # Overwriting (1, 0) with narrow 'Z' heals (0, 3) SPACER_HEAD and clears wrapped! narrow_term.feed(b"\x1b[2;1HZ") assert narrow_term[0, 3].width_role == WidthRole.NARROW assert narrow_term[0, 3].text == " " - assert narrow_term[0].wrapped is True + assert narrow_term[0].wrapped is False assert narrow_term[1, 0].text == "Z" assert narrow_term[1, 1].text == " " assert narrow_term[1, 1].width_role == WidthRole.NARROW + vt_replayed = libvt.render( + Formatter(OutputFormat.VT).format_snapshot(narrow_term.snapshot()), + rows=3, + cols=8, + ) + narrow_term.resize(rows=3, cols=8) + assert narrow_term.text == "abc\nZ" + assert vt_replayed == narrow_term.text + narrow_term.resize(rows=3, cols=4) + assert narrow_term.screen._rows[0].used == 3 + + # Wide-to-wide CUP overwrite at (1, 0) also repairs pre-edit SPACER_HEAD! + w2w_term = libvt.Terminal(rows=3, cols=4) + w2w_term.feed_str("abc❤️") + w2w_term.feed_str("\x1b[2;1H日") + assert w2w_term[0, 3].width_role == WidthRole.NARROW + assert w2w_term[0].wrapped is False + assert w2w_term[1, 0].text == "日" + + # BCE EL 0 with colored background keeps background style without padding .text! + bce_term = libvt.Terminal(rows=3, cols=80) + bce_term.feed(b"\x1b[44mfoo\x1b[K\r\nbar") + assert bce_term[0].text == "foo" + assert bce_term[1].text == "bar" + assert bce_term[0, 10].style.bg is not None + bce_term.resize(rows=3, cols=40) + assert bce_term[0].text == "foo" + assert bce_term[1].text == "bar" + + # RowView stays anchored to viewport row coordinates across scroll recycling! + scroll_term = libvt.Terminal(rows=2, cols=10, scrollback=5) + scroll_term.feed(b"row-0\r\nrow-1") + top_view = scroll_term[0] + assert top_view.text == "row-0" + scroll_term.feed(b"\r\nrow-2") + assert top_view.text == "row-1" # Disabling ?2027 leaves narrow base + VS16 at width 1. legacy = libvt.Terminal(rows=2, cols=6) From 63e126aa34864603371791d700db869452d9c4f4 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 21 Nov 2026 20:01:04 -0600 Subject: [PATCH 08/29] Docs(docs[adr]): Sync ADRs and changelog Document profile- and policy-gated OSC 7501;? replies, updated Limits defaults, TMUX_CAPTURE_POLICY, WindowRenamed, and hardened open_pty() process-group teardown across ADRs 0002, 0007, and 0010, protocols docs, and CHANGES. --- CHANGES | 10 +++++--- ...ns-io-layers-profiles-and-closed-events.md | 25 +++++++++++-------- ...501-program-status-and-semantic-prompts.md | 24 ++++++++++-------- ...ly-asyncio-and-diagnostic-pytest-plugin.md | 19 +++++++------- docs/topics/protocols-and-input.md | 7 +++--- 5 files changed, 47 insertions(+), 38 deletions(-) diff --git a/CHANGES b/CHANGES index 715a406..b12481d 100644 --- a/CHANGES +++ b/CHANGES @@ -46,10 +46,12 @@ escape sequences, and span-coalesced HTML with URI scheme allowlisting. {class}`~libvt.status.ProgramStatus` implement the Rex `OSC 7501` Program Status specification, including hierarchical task identifiers, ancestor `app` inheritance, urgency ranking, base64 `title`/`msg` -validation, consumer-gated `OSC 7501 ; ?` capability replies, `OSC 9;4` -fallback, and lifecycle pruning alongside `OSC 133` prompt zones, -`OSC 7` working directory updates, `OSC 52` clipboard writes, `DA1`/`DA2`, -`DSR`, `DECRQM`, `DECRQSS`, `XTVERSION`, `XTGETTCAP`, and `?2031`/`?996n` +validation, profile- and policy-gated `OSC 7501 ; ?` capability replies, +`OSC 9;4` fallback, and lifecycle pruning alongside `OSC 133` prompt zones, +`OSC 7` RFC 8089 working directory updates, `OSC 52` clipboard writes, +`OSC 10`/`11` and `OSC 110`/`111` dynamic colors, `tmux` `ESC k` window +renames ({class}`~libvt.events.WindowRenamed`), `DA1`/`DA2`, `DSR`, +`DECRQM`, `DECRQSS`, `XTVERSION`, `XTGETTCAP`, and `?2031`/`?996n` color-scheme queries. Configuration splits cleanly across {class}`~libvt.config.Profile`, {class}`~libvt.config.Policy`, and {class}`~libvt.config.Limits`. See {doc}`topics/protocols-and-input` for diff --git a/docs/project/adr/0002-sans-io-layers-profiles-and-closed-events.md b/docs/project/adr/0002-sans-io-layers-profiles-and-closed-events.md index 19cb319..33eab7b 100644 --- a/docs/project/adr/0002-sans-io-layers-profiles-and-closed-events.md +++ b/docs/project/adr/0002-sans-io-layers-profiles-and-closed-events.md @@ -57,19 +57,21 @@ security gates (`Policy`), resource bounds (`Limits`), outbound wire replies 2. **Three immutable configuration objects (`libvt.config`)**: - `Profile`: Terminal identity and compatibility behavior (`name`, `da1`, `da2`, `xtversion`, `osc_7501_capabilities`, `color_scheme`, - `fg_rgb`, `bg_rgb`, `pending_wrap_phantom_col`), with presets - `DEFAULT_PROFILE` (`XTERM_PROFILE`) and `TMUX_PROFILE`. + `fg_rgb`, `bg_rgb`, `pending_wrap_phantom_col`, + `vs15_narrows_wide_emoji`, `vs16_always_wide`, `tmux_window_rename`), + with presets `DEFAULT_PROFILE`, `XTERM_PROFILE`, and `TMUX_PROFILE`. - `Policy`: Default-deny host security gates (`allow_title_report=False`, `allow_checksum_report=False`, `allow_clipboard_read=False`, `allow_clipboard_write=True`, `allow_color_queries=True`, - `allow_program_status_query=False`, `allow_unsafe_uris=False`, - `allow_passthrough=False`, `osc7_hosts=frozenset({"", "localhost"})`, - `strict=False`). + `allow_program_status_query=True`, `allow_unsafe_uris=False`, + `allow_passthrough=False`, `abort_dispatch_osc=False`, + `osc7_hosts=None`, `strict=False`) plus `TMUX_CAPTURE_POLICY`. - `Limits`: Hard memory and CPU bounds (`max_grapheme_codepoints=32`, - `max_csi_params=32`, `max_osc_bytes=131_072`, `max_dcs_bytes=4_194_304`, + `max_csi_params=32`, `max_osc_bytes=131_072`, `max_dcs_bytes=8_388_608`, `max_apc_bytes=4_194_304`, `max_reply_bytes=65_536`, `max_rep_count=4_096`, `max_prompt_zones=1_024`, - `max_status_records=64`, `max_events=4_096`, `max_keyboard_stack=8`). + `max_status_records=256`, `max_events=4_096`, + `max_event_bytes=16_777_216`, `max_keyboard_stack=8`). 3. **Zero-allocation hot path with private `_TerminalSink`**: - `Terminal.feed(data, /) -> None` mutates terminal state in place through an internal `_TerminalSink` passed to `Parser.feed_to()`. Public @@ -78,10 +80,11 @@ security gates (`Policy`), resource bounds (`Limits`), outbound wire replies `bytearray` drained via `term.drain_replies() -> bytes` (or forwarded via `on_pty_write` when attached). 4. **Closed algebraic `Event` union (`libvt.events`)**: - - `type Event = Bell | TitleChanged | WorkingDirectoryChanged | - ClipboardWrite | PromptMark | ProgramStatusChanged | RenderHoldChanged | - ColorSchemeQueried | InBandResize | SixelGraphic | KittyGraphic | - ScreenErased | Passthrough | UnhandledSequence`. + - `type Event = Bell | TitleChanged | WindowRenamed | + WorkingDirectoryChanged | ClipboardWrite | PromptMark | + ProgramStatusChanged | RenderHoldChanged | ColorSchemeQueried | + InBandResize | SixelGraphic | KittyGraphic | ScreenErased | + Passthrough | UnhandledSequence`. - Callers either pass `on_event: Callable[[Event], None]` (push) or set `record_events: bool = True` and call `term.drain_events() -> tuple[Event, ...]` (pull). When neither is enabled, `feed()` allocates diff --git a/docs/project/adr/0007-rex-osc-7501-program-status-and-semantic-prompts.md b/docs/project/adr/0007-rex-osc-7501-program-status-and-semantic-prompts.md index cf36ef6..e937cda 100644 --- a/docs/project/adr/0007-rex-osc-7501-program-status-and-semantic-prompts.md +++ b/docs/project/adr/0007-rex-osc-7501-program-status-and-semantic-prompts.md @@ -49,17 +49,18 @@ capability query: Unicode BiDi overrides. - `state=clear` removes `id` and all `id/*` descendants (when `id == ""`, clears the entire store). Total active records stay bounded by - `Limits.max_status_records` (`64`). + `Limits.max_status_records` (`256`). - Expose `term.program_status` (most urgent active `ProgramStatus` ordered `blocked > error > working > done > idle`, or root record) and `term.program_statuses -> dict[str, ProgramStatus]`. - - **Consumer-gated `OSC 7501 ; ?` reply**: Reply only when - `Policy.allow_program_status_query` is `True` *or* an event consumer - (`on_event` or `record_events=True`) is attached (matching `libghostty-vt` - `5b0690d`), formatting the capability payload from + - **Profile- and policy-gated `OSC 7501 ; ?` reply**: Reply whenever + `Policy.allow_program_status_query` is `True` (default `True`) and + `Profile.osc_7501_capabilities` is non-empty (independent of `on_event` + and `record_events` so pull-mode `term.program_status` inspection never + changes wire negotiation), formatting the capability payload from `Profile.osc_7501_capabilities` (full `states=...:kinds=...` on - `DEFAULT_PROFILE`, bare `?` on `TMUX_PROFILE`) and mirroring the incoming - `BEL` (`\x07`) vs `ST` (`\x1b\\`) terminator. + `DEFAULT_PROFILE`, bare `?` on `TMUX_PROFILE`, empty on `XTERM_PROFILE`) + and mirroring the incoming `BEL` (`\x07`) vs `ST` (`\x1b\\`) terminator. - **Lifecycle and `OSC 9;4` fallback**: Map `OSC 9;4;st;prog` into synthetic root status until the first native `OSC 7501` arrives (re-enabled on `RIS`). On `OSC 133;A` prompt start (ignoring `k=s` secondary continuation @@ -87,9 +88,10 @@ capability query: - **Simplified `OSC 7501;value;progress` string split**: Rejected because it is wire-incompatible with `tmux`, `Ghostty`, and Rex CLI emitters. -- **Unconditional `OSC 7501 ; ?` reply when no consumer is listening**: - Rejected in favor of `libghostty-vt`'s consumer/policy gate so passive text - scrapers do not solicit unused status traffic. +- **Coupling `OSC 7501 ; ?` replies to `record_events` / `on_event`**: + Rejected because attaching an observer must not alter wire capabilities + seen by the child process, and pull-mode `term.program_status` callers rely + on the built-in `ProgramStatusStore`. ## Consequences @@ -109,4 +111,4 @@ capability query: - Untrusted PTY output flooding `OSC 133;A` or `OSC 7501` unique IDs. Mitigation: `Limits.max_prompt_zones = 1_024` (`deque` FIFO) and - `Limits.max_status_records = 64`. + `Limits.max_status_records = 256`. diff --git a/docs/project/adr/0010-transport-only-asyncio-and-diagnostic-pytest-plugin.md b/docs/project/adr/0010-transport-only-asyncio-and-diagnostic-pytest-plugin.md index 1042e77..abe5f95 100644 --- a/docs/project/adr/0010-transport-only-asyncio-and-diagnostic-pytest-plugin.md +++ b/docs/project/adr/0010-transport-only-asyncio-and-diagnostic-pytest-plugin.md @@ -42,17 +42,18 @@ empirical testing: pairs, flushing `drain_replies()` automatically and enforcing `sync_timeout` via `Terminal.expire_synchronized_output(sync_gen)` in both background-task (`async with`) and on-demand `wait_for()` modes. - - `open_pty(argv, *, rows=24, cols=80, env=None, cwd=None, tty_mode="cooked")` + - `open_pty(argv, *, rows=24, cols=80, env=None, cwd=None, tty_mode="cooked", python_executable=None)` spawns a child process attached to a stdlib `pty.openpty()` master/slave pair via an isolated `-I -S` child trampoline (`start_new_session=True`, - `TIOCSCTTY` controlling terminal acquisition, `SIGPIPE` reset to - `SIG_DFL`, and `CLOEXEC` `err_fd` exec-failure propagation without - `preexec_fn`), configures `TIOCSWINSZ` and optional `"cbreak"` / `"raw"` - termios modes, augments default `Policy.osc7_hosts` with the local - hostname, pumps output + `drain_replies()`, and exposes `send()`, - `send_key()`, `paste()`, `resize()`, and `wait_for()`. On Windows - (`sys.platform == "win32"`), `open_pty()` raises `NotImplementedError` - cleanly while the entire Sans-I/O core works unchanged. + strict `TIOCSCTTY` controlling terminal acquisition, `SIGPIPE`/`SIGXFSZ` + reset to `SIG_DFL`, and a pre-exec marker + bounded stage/errno packet on + a `CLOEXEC` `err_fd` pipe without `preexec_fn`), configures `TIOCSWINSZ` + and optional `"cbreak"` / `"raw"` termios modes, augments unset + `Policy.osc7_hosts` with the local hostname, and reaps owned process + groups on `aclose()` via `os.killpg` (`SIGHUP` -> `SIGTERM` -> `SIGKILL`) + after draining final PTY bytes. On Windows (`sys.platform == "win32"`), + `open_pty()` raises `NotImplementedError` cleanly while the entire + Sans-I/O core works unchanged. 3. **Strictly `vt_`-prefixed, `Protocol`-typed `pytest11` plugin (`libvt.pytest_plugin`)**: - Register `vt_terminal`, `vt_factory` (typed via `TerminalFactory` diff --git a/docs/topics/protocols-and-input.md b/docs/topics/protocols-and-input.md index d938466..948d1f7 100644 --- a/docs/topics/protocols-and-input.md +++ b/docs/topics/protocols-and-input.md @@ -21,9 +21,10 @@ fallback): ('ci/approve', 'pytest') ``` -`OSC 7501 ; ?` capability queries stay silent unless `on_event`, -`record_events=True`, or `Policy(allow_program_status_query=True)` -indicates an active status consumer. +`OSC 7501 ; ?` capability queries answer whenever +`Policy.allow_program_status_query` is `True` (the default) and +`Profile.osc_7501_capabilities` is non-empty, independent of whether +`on_event` or `record_events=True` is attached. ## Semantic prompts (`OSC 133`) and queries From ae61d4f16a3853ea25ff51ae0fc2fe93776941db Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 22 Nov 2026 08:24:27 -0600 Subject: [PATCH 09/29] Screen(fix[resize]): Preserve pending_wrap on resize (#4) why: Unconditionally clearing pending_wrap on resize caused same-size resizes to overwrite the last column, widening with reflow to drop the right-margin advance, and dummy cursor cells to inject phantom blank rows on exact-fit shrinks. what: - Add reflow_on_resize to Profile (False on XTERM_PROFILE) and default Terminal.resize and PtySession.resize reflow=None to the profile - Return early from Screen.resize when dimensions do not change - Track logical eff_cur_col and cur_after_extra in _reflow_primary without dummy trailing cells - Preserve pending_wrap on non-reflow resizes when old_cur_col < cols and synchronize _saved_primary cursor state when resizing on ?1049h --- src/libvt/aio.py | 8 +++- src/libvt/config.py | 12 ++++-- src/libvt/screen.py | 77 ++++++++++++++++++++++------------ src/libvt/terminal.py | 30 +++++++++++-- tests/test_pr2_review_fixes.py | 69 ++++++++++++++++++++++++++++++ 5 files changed, 162 insertions(+), 34 deletions(-) create mode 100644 tests/test_pr2_review_fixes.py diff --git a/src/libvt/aio.py b/src/libvt/aio.py index fdc4f14..d98fc67 100644 --- a/src/libvt/aio.py +++ b/src/libvt/aio.py @@ -394,7 +394,13 @@ def paste(self, text: str, /, *, sanitize: bool = False) -> None: """Encode *text* as a :class:`PasteEvent` and write to the PTY.""" self.send_event(PasteEvent(text=text, sanitize=sanitize)) - def resize(self, *, rows: int, cols: int, reflow: bool = True) -> None: + def resize( + self, + *, + rows: int, + cols: int, + reflow: bool | None = None, + ) -> None: """Update kernel ``TIOCSWINSZ`` and resize :attr:`terminal`.""" import fcntl import termios diff --git a/src/libvt/config.py b/src/libvt/config.py index 2275b2c..2930494 100644 --- a/src/libvt/config.py +++ b/src/libvt/config.py @@ -13,7 +13,7 @@ class ColorScheme(enum.IntEnum): LIGHT = 2 -@dataclass(frozen=True, slots=True) +@dataclass(frozen=True, slots=True, kw_only=True) class Profile: r"""Terminal identity responses and compatibility switches. @@ -52,6 +52,10 @@ class Profile: tmux_window_rename : bool When ``True`` (``TMUX_PROFILE``), ``ESC k ESC \`` is consumed as a window-rename control string rather than printed onto the grid. + reflow_on_resize : bool + Default reflow behavior for :meth:`~libvt.terminal.Terminal.resize` + when ``reflow=None`` (``True`` on ``DEFAULT_PROFILE`` and + ``TMUX_PROFILE``, ``False`` on ``XTERM_PROFILE``). """ name: str = "libvt" @@ -68,12 +72,13 @@ class Profile: vs15_narrows_wide_emoji: bool = True vs16_always_wide: bool = False tmux_window_rename: bool = False + reflow_on_resize: bool = True DEFAULT_OSC7_HOSTS: frozenset[str] = frozenset({"", "localhost"}) -@dataclass(frozen=True, slots=True) +@dataclass(frozen=True, slots=True, kw_only=True) class Policy: r"""Default-deny host security and strictness policy. @@ -131,7 +136,7 @@ class Policy: strict: bool = False -@dataclass(frozen=True, slots=True) +@dataclass(frozen=True, slots=True, kw_only=True) class Limits: """Resource ceilings protecting memory and CPU against hostile byte streams. @@ -189,6 +194,7 @@ class Limits: XTERM_PROFILE = Profile( name="xterm", osc_7501_capabilities="", + reflow_on_resize=False, ) TMUX_PROFILE = Profile( name="tmux", diff --git a/src/libvt/screen.py b/src/libvt/screen.py index 32fad56..e67a222 100644 --- a/src/libvt/screen.py +++ b/src/libvt/screen.py @@ -800,11 +800,12 @@ def _reflow_primary(self, *, rows: int, cols: int) -> None: combined = hist_thawed + self._rows[: last_active + 1] cur_abs_idx = hist_len + self._cur_row - cur_col = self._cur_col + eff_cur_col = self._cur_col + (1 if self._pending_wrap else 0) new_all: list[_Row] = [] new_cur_abs = 0 new_cur_col = 0 + new_pending_wrap = False cursor_placed = False idx = 0 @@ -816,54 +817,65 @@ def _reflow_primary(self, *, rows: int, cols: int) -> None: group_end = idx idx += 1 - # Extract logical cells across [group_start .. group_end]. - cells: list[tuple[str, int, int, _CellExt | None, bool, bool]] = [] + if group_start <= cur_abs_idx < group_end and eff_cur_col >= len( + combined[cur_abs_idx].chars + ): + cur_abs_idx += 1 + eff_cur_col = 0 + + # Extract real logical cells across [group_start .. group_end]. + cells: list[tuple[str, int, int, _CellExt | None, int]] = [] + cur_after_extra: int | None = None + carry_cur = False for r_i in range(group_start, group_end + 1): src = combined[r_i] is_last = r_i == group_end src_t_used = src.text_used if isinstance(src, _Row) else len(src.text) row_limit = len(src.chars) if not is_last else src_t_used - limit = max(row_limit, cur_col + 1) if r_i == cur_abs_idx else row_limit - for c_i in range(limit): + if r_i == cur_abs_idx and eff_cur_col >= row_limit: + cur_after_extra = eff_cur_col - row_limit + for c_i in range(row_limit): word = src.attr_at(c_i) rb = raw_width_bits(word) - is_cur = r_i == cur_abs_idx and c_i == cur_col - is_dummy = is_last and c_i >= row_limit + is_cur = r_i == cur_abs_idx and c_i == eff_cur_col if rb == int(WidthRole.SPACER_HEAD): if is_cur: - cells.append((" ", 0, 1, None, True, True)) + carry_cur = True continue if rb == int(WidthRole.SPACER_TAIL): if is_cur and cells: - p_ch, p_w, p_cw, p_ext, _, p_dum = cells[-1] - cells[-1] = (p_ch, p_w, p_cw, p_ext, True, p_dum) + p_ch, p_w, p_cw, p_ext, _ = cells[-1] + cells[-1] = (p_ch, p_w, p_cw, p_ext, 1) continue cw = 2 if rb == int(WidthRole.WIDE) else 1 base_word = word & _WIDTH_CLEAR_MASK + cur_off = 0 if (is_cur or carry_cur) else -1 + carry_cur = False cells.append( ( src.chars[c_i], base_word, cw, src.ext_at(c_i), - is_cur, - is_dummy, + cur_off, ) ) if not cells: empty_row = _Row(cols) + new_all.append(empty_row) if group_start <= cur_abs_idx <= group_end and not cursor_placed: - new_cur_abs = len(new_all) - new_cur_col = 0 + extra = 0 if cur_after_extra is None else cur_after_extra + new_cur_abs = len(new_all) - 1 + new_cur_col = min(cols - 1, extra) + new_pending_wrap = False cursor_placed = True - new_all.append(empty_row) continue cur_out = _Row(cols) new_all.append(cur_out) out_col = 0 - for ch, base_w, cw, ce, is_cur, is_dummy in cells: + for ch, base_w, cw, ce, cur_off in cells: eff_cw = cw eff_ch = ch if eff_cw == 2 and cols == 1: @@ -871,28 +883,37 @@ def _reflow_primary(self, *, rows: int, cols: int) -> None: eff_cw = 1 if out_col + eff_cw > cols: - if not is_dummy and out_col < cols: + if out_col < cols: cur_out.write_spacer_head(out_col, 0, None) - if not is_dummy: - cur_out.wrapped = True + cur_out.wrapped = True cur_out = _Row(cols) new_all.append(cur_out) out_col = 0 - if is_cur and not cursor_placed: + if cur_off >= 0 and not cursor_placed: new_cur_abs = len(new_all) - 1 - new_cur_col = out_col + new_cur_col = min(cols - 1, out_col + cur_off) + new_pending_wrap = False cursor_placed = True - if is_dummy: - out_col += eff_cw - elif eff_cw == 2: + if eff_cw == 2: cur_out.write_wide(out_col, eff_ch, base_w, ce) out_col += 2 else: cur_out.write_narrow(out_col, eff_ch, base_w, ce) out_col += 1 + if (cur_after_extra is not None or carry_cur) and not cursor_placed: + extra = 0 if cur_after_extra is None else cur_after_extra + new_cur_abs = len(new_all) - 1 + if extra == 0 and out_col == cols: + new_cur_col = cols - 1 + new_pending_wrap = True + else: + new_cur_col = min(cols - 1, out_col + extra) + new_pending_wrap = False + cursor_placed = True + if not new_all: new_all.append(_Row(cols)) @@ -911,7 +932,7 @@ def _reflow_primary(self, *, rows: int, cols: int) -> None: self._cols = cols self._cur_row = max(0, min(rows - 1, new_cur_abs - hist_cut)) self._cur_col = max(0, min(cols - 1, new_cur_col)) - self._pending_wrap = False + self._pending_wrap = new_pending_wrap def resize(self, *, rows: int, cols: int, reflow: bool = True) -> None: """Resize screen to ``(rows, cols)``, optionally reflowing soft wraps.""" @@ -920,9 +941,13 @@ def resize(self, *, rows: int, cols: int, reflow: bool = True) -> None: raise ValueError(msg) old_cols = self._cols + if rows == len(self._rows) and cols == old_cols: + return + if reflow and cols != old_cols: self._reflow_primary(rows=rows, cols=cols) else: + old_cur_col = self._cur_col if cols != old_cols: for r in self._rows: r.resize(cols) @@ -948,7 +973,7 @@ def resize(self, *, rows: int, cols: int, reflow: bool = True) -> None: self._cur_row = min(self._cur_row, rows - 1) self._cur_col = min(self._cur_col, cols - 1) - self._pending_wrap = False + self._pending_wrap = self._pending_wrap and old_cur_col < cols self.scroll_region = ScrollRegion( top=0, diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py index b179bdd..796bfbc 100644 --- a/src/libvt/terminal.py +++ b/src/libvt/terminal.py @@ -1080,11 +1080,33 @@ def _notify_erase(self, rect: Rect, cause: EraseCause) -> None: ), ) - def resize(self, *, rows: int, cols: int, reflow: bool = True) -> None: + def resize( + self, + *, + rows: int, + cols: int, + reflow: bool | None = None, + ) -> None: """Resize terminal screens to ``(rows, cols)``.""" + eff_reflow = self._profile.reflow_on_resize if reflow is None else reflow self._before_mutate() self._clear_cluster_anchor() - self._screens.resize(rows=rows, cols=cols, reflow=reflow) + self._screens.resize(rows=rows, cols=cols, reflow=eff_reflow) + if not self._modes.is_set(Mode.DECAWM): + self._screens.primary._pending_wrap = False + self._screens.alternate._pending_wrap = False + if self._screens.active_is_alt: + prim = self._screens.primary + self._saved_primary = _SavedCursor( + row=prim._cur_row, + col=prim._cur_col, + pending_wrap=prim._pending_wrap, + style=self._saved_primary.style, + decom=self._saved_primary.decom, + g_sets=self._saved_primary.g_sets, + gl=self._saved_primary.gl, + protected=self._saved_primary.protected, + ) self._generation += 1 if self._modes.is_set(Mode.IN_BAND_RESIZE): self._emit_reply(f"\x1b[48;{rows};{cols};0;0t".encode("ascii")) @@ -1337,7 +1359,7 @@ def _handle_print(self, text: str) -> None: can_advance = scr._cur_row < scr.rows - 1 or ( scr._cur_row == bottom and left <= c_col <= right ) - if can_advance and min_col == 0 and max_col == scr.cols - 1: + if can_advance and min_col == 0 and c_col == scr.cols - 1: scr._rows[scr._cur_row].wrapped = True self._linefeed(scr) self._set_cursor(scr, scr._cur_row, min_col, pending_wrap=False) @@ -1554,7 +1576,7 @@ def _handle_print(self, text: str) -> None: can_advance = c_row < scr.rows - 1 or ( c_row == bottom and left <= c_col <= right ) - if can_advance and min_col == 0 and max_col == scr.cols - 1: + if can_advance and min_col == 0 and c_col == scr.cols - 1: scr._rows[c_row].wrapped = True self._linefeed(scr) self._set_cursor(scr, scr._cur_row, min_col, pending_wrap=False) diff --git a/tests/test_pr2_review_fixes.py b/tests/test_pr2_review_fixes.py new file mode 100644 index 0000000..5c4c6a7 --- /dev/null +++ b/tests/test_pr2_review_fixes.py @@ -0,0 +1,69 @@ +"""Regression tests for PR #2 architectural and terminal-profile review fixes.""" + +from __future__ import annotations + +import libvt +from libvt.config import XTERM_PROFILE + + +def test_resize_preserves_pending_wrap_and_wide_glyphs() -> None: + """``resize()`` preserves ``pending_wrap``, wide cells, and profile reflow rules.""" + # Case 1a: same-size 4x2 -> 4x2 preserves pending_wrap and scroll_region. + same = libvt.Terminal(rows=2, cols=4) + same.feed(b"\x1b[1;2rABCD") + assert same.cursor.pending_wrap is True + same.resize(rows=2, cols=4) + assert same.cursor.pending_wrap is True + same.feed(b"E") + assert same.lines == ("ABCD", "E") + assert (same.cursor.row, same.cursor.col) == (1, 1) + assert same.cursor.pending_wrap is False + assert same[0].wrapped is True + + # Case 1b (DEFAULT_PROFILE reflow=True): widen 4x2 -> 8x2 unwraps pending_wrap. + widened = libvt.Terminal(rows=2, cols=4) + widened.feed(b"ABCD") + widened.resize(rows=2, cols=8) + assert widened.cursor.col == 4 + assert widened.cursor.pending_wrap is False + widened.feed(b"E") + assert widened.lines == ("ABCDE", "") + assert (widened.cursor.row, widened.cursor.col) == (0, 5) + assert widened[0].wrapped is False + + # Case 1b (XTERM_PROFILE reflow_on_resize=False): widen keeps col 3 + pending_wrap. + xt = libvt.Terminal(rows=2, cols=4, profile=XTERM_PROFILE) + xt.feed(b"ABCD") + xt.resize(rows=2, cols=8) + assert xt.cursor.col == 3 + assert xt.cursor.pending_wrap is True + xt.feed(b"E") + assert xt.lines == ("ABCD", "E") + assert (xt.cursor.row, xt.cursor.col) == (1, 1) + assert xt[0].wrapped is False + + # Wide glyph ending at right margin ('AB界' on 4 cols) reflows cleanly on widen. + wide = libvt.Terminal(rows=2, cols=4) + wide.feed("AB界".encode()) + assert wide.cursor.pending_wrap is True + wide.resize(rows=2, cols=8) + wide.feed(b"E") + assert wide.lines == ("AB界E", "") + assert (wide.cursor.row, wide.cursor.col) == (0, 5) + + # Exact-fit shrink 8x2 -> 4x2 after 'ABCD' produces no phantom blank row. + shrink = libvt.Terminal(rows=2, cols=8, scrollback=10) + shrink.feed(b"ABCD") + assert (shrink.cursor.row, shrink.cursor.col) == (0, 4) + shrink.resize(rows=2, cols=4) + assert shrink.history == () + shrink.feed(b"E") + assert shrink.lines == ("ABCD", "E") + assert (shrink.cursor.row, shrink.cursor.col) == (1, 1) + + # Resizing while inside ?1049h keeps primary saved cursor synchronized on ?1049l. + alt_resize = libvt.Terminal(rows=2, cols=4) + alt_resize.feed(b"ABCDabc\x1b[?1049h") + alt_resize.resize(rows=2, cols=8) + alt_resize.feed(b"\x1b[?1049lX") + assert alt_resize[0].text == "ABCDabcX" From a3ac0e96726018ee48836933cbbd8453bf8e16a3 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 22 Nov 2026 08:26:17 -0600 Subject: [PATCH 10/29] Terminal(fix[sync]): Freeze ?2026 state at BSU (#5) why: Updating _generation only at the end of feed() allowed a cached pre-feed snapshot to leak into _held_snapshot when bytes preceded BSU in the same chunk, and scalar cursor, mode, and OSC mutations bypassed _before_mutate(). what: - Invalidate _cached_snapshot inside _before_mutate() and build held snapshots with TRANSIENT_SNAPSHOT_MODES excluded - Call _before_mutate() across cursor, DECTCEM/DECSCUSR, mode, title, cwd, prompt-zone, and program-status mutators - Emit RenderHoldChanged(active=False) after reset() updates generation --- src/libvt/terminal.py | 110 ++++++++++++++++++++++----------- tests/test_pr2_review_fixes.py | 50 +++++++++++++++ 2 files changed, 124 insertions(+), 36 deletions(-) diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py index 796bfbc..23fb696 100644 --- a/src/libvt/terminal.py +++ b/src/libvt/terminal.py @@ -906,20 +906,21 @@ def committed(self) -> Snapshot: return self._held_snapshot return self.snapshot() - def _ensure_sync_snapshot(self) -> None: - if self._sync_hold_pending and self._held_snapshot is None: - self._held_snapshot = self.snapshot() - self._sync_hold_pending = False + def _invalidate_cache(self) -> None: + if self._cached_snapshot is not None: + self._cached_snapshot = None + self._generation += 1 - def snapshot(self) -> Snapshot: - """Capture an immutable :class:`Snapshot` of live terminal state.""" - if ( - self._cached_snapshot is not None - and self._cached_snapshot.generation == self._generation - ): - return self._cached_snapshot + def _build_snapshot( + self, + *, + exclude_modes: frozenset[Mode] = frozenset(), + ) -> Snapshot: scr = self._screens.active - snap = Snapshot( + modes = self._modes.enabled_modes() + if exclude_modes: + modes = modes - exclude_modes + return Snapshot( rows=tuple(r.clone() for r in scr._rows), history=tuple(self._screens.primary._history), cols=scr.cols, @@ -927,13 +928,29 @@ def snapshot(self) -> Snapshot: title=self._title, cwd=self._cwd, cwd_uri=self._cwd_uri, - modes=self._modes.enabled_modes(), + modes=modes, active_is_alt=self._screens.active_is_alt, prompt_zones=self.prompt_zones, program_status=self._status_store.most_urgent, program_statuses=self._status_store.records, generation=self._generation, ) + + def _ensure_sync_snapshot(self) -> None: + if self._sync_hold_pending and self._held_snapshot is None: + self._held_snapshot = self._build_snapshot( + exclude_modes=TRANSIENT_SNAPSHOT_MODES, + ) + self._sync_hold_pending = False + + def snapshot(self) -> Snapshot: + """Capture an immutable :class:`Snapshot` of live terminal state.""" + if ( + self._cached_snapshot is not None + and self._cached_snapshot.generation == self._generation + ): + return self._cached_snapshot + snap = self._build_snapshot() self._cached_snapshot = snap return snap @@ -1021,6 +1038,7 @@ def expire_synchronized_output( self._modes.set_mode(Mode.SYNCHRONIZED_OUTPUT, enabled=False) self._sync_hold_pending = False self._held_snapshot = None + self._cached_snapshot = None self._generation += 1 self._emit_event( RenderHoldChanged( @@ -1033,6 +1051,7 @@ def expire_synchronized_output( def notify_process_exit(self) -> None: """Prune transient ``working`` / ``blocked`` ``OSC 7501`` status records.""" + self._before_mutate() if self._status_store.on_process_exit(): self._generation += 1 self._emit_event( @@ -1131,13 +1150,6 @@ def reset(self, *, soft: bool = False) -> None: self._modes.set_mode(Mode.LNM, enabled=True) self._sync_hold_pending = False self._held_snapshot = None - if was_sync: - self._emit_event( - RenderHoldChanged( - active=False, - sync_generation=self._sync_generation, - ), - ) if soft: if was_alt: self._modes.sync_alt_screen(active_is_alt=True) @@ -1172,11 +1184,20 @@ def reset(self, *, soft: bool = False) -> None: Rect(0, 0, self.rows, self.cols), EraseCause.RESET, ) + self._cached_snapshot = None self._generation += 1 + if was_sync: + self._emit_event( + RenderHoldChanged( + active=False, + sync_generation=self._sync_generation, + ), + ) def _before_mutate(self) -> None: if self._sync_hold_pending: self._ensure_sync_snapshot() + self._invalidate_cache() def feed_str(self, text: str, /) -> None: """Encode *text* as UTF-8 and feed into the terminal.""" @@ -1283,6 +1304,7 @@ def _set_cursor( pending_wrap: bool = False, clear_cluster: bool = True, ) -> None: + self._before_mutate() scr._cur_row = max(0, min(scr.rows - 1, row)) scr._cur_col = max(0, min(scr.cols - 1, col)) scr._pending_wrap = pending_wrap @@ -1684,6 +1706,7 @@ def _cursor_left(self, scr: Screen, count: int, *, is_backspace: bool) -> None: ) n = max(1, count) if scr._pending_wrap and rev_wrap: + self._before_mutate() scr._pending_wrap = False self._clear_cluster_anchor() n -= 1 @@ -1759,6 +1782,7 @@ def _save_cursor(self) -> None: self._saved_primary = saved def _restore_cursor(self) -> None: + self._before_mutate() scr = self._screens.active saved = self._saved_alt if self._screens.active_is_alt else self._saved_primary self._style = saved.style @@ -1847,6 +1871,28 @@ def _apply_mode(self, code: int, *, private: bool, enabled: bool) -> None: return was_set = self._modes.is_set(mode) + if mode == Mode.SYNCHRONIZED_OUTPUT: + if enabled == was_set: + return + self._invalidate_cache() + self._modes.set_mode(mode, enabled=enabled) + if enabled: + self._sync_generation += 1 + self._sync_hold_pending = True + self._held_snapshot = None + self._step_event |= StopOn.SYNC_START + else: + self._sync_hold_pending = False + self._held_snapshot = None + self._step_event |= StopOn.SYNC_END + self._emit_event( + RenderHoldChanged( + active=enabled, + sync_generation=self._sync_generation, + ), + ) + return + if mode in ALT_SCREEN_MODES: self._before_mutate() self._clear_cluster_anchor() @@ -1867,6 +1913,7 @@ def _apply_mode(self, code: int, *, private: bool, enabled: bool) -> None: self._modes.sync_alt_screen(active_is_alt=False) return + self._before_mutate() self._modes.set_mode(mode, enabled=enabled) scr = self._screens.active @@ -1893,22 +1940,6 @@ def _apply_mode(self, code: int, *, private: bool, enabled: bool) -> None: self._save_cursor() else: self._restore_cursor() - elif mode == Mode.SYNCHRONIZED_OUTPUT and enabled != was_set: - if enabled: - self._sync_generation += 1 - self._sync_hold_pending = True - self._held_snapshot = None - self._step_event |= StopOn.SYNC_START - else: - self._sync_hold_pending = False - self._held_snapshot = None - self._step_event |= StopOn.SYNC_END - self._emit_event( - RenderHoldChanged( - active=enabled, - sync_generation=self._sync_generation, - ), - ) def _erase_display( self, @@ -2081,6 +2112,7 @@ def _handle_csi( # DECSCUSR: CSI Ps SP q if prefix == 0 and intermediates == b" " and final == ord("q"): + self._before_mutate() ps = params.raw_or_default(0, 0) shape = CursorShape.BLOCK blinking = True @@ -2448,6 +2480,7 @@ def _handle_csi( if len(self._title_stack) < 16: self._title_stack.append(self._title) elif op == 23 and self._title_stack: # pop title from stack + self._before_mutate() self._title = self._title_stack.pop() self._emit_event(TitleChanged(title=self._title)) else: @@ -2462,6 +2495,7 @@ def _handle_window_rename(self, raw: bytes) -> None: self._emit_event(WindowRenamed(name=name)) def _update_cwd(self, raw_uri: str, *, from_osc7: bool = True) -> None: + self._before_mutate() cleaned = raw_uri.strip() if not cleaned or "\x00" in cleaned: self._cwd = "" @@ -2507,6 +2541,7 @@ def _handle_osc(self, code: int, data: bytes, terminator: bytes) -> None: out_term = b"\x07" if terminator == b"\x07" else b"\x1b\\" if code in (0, 2): + self._before_mutate() text = data.decode("utf-8", errors="replace") self._title = text self._emit_event(TitleChanged(title=text)) @@ -2535,6 +2570,7 @@ def _handle_osc(self, code: int, data: bytes, terminator: bytes) -> None: text = data.decode("utf-8", errors="replace") parts = text.split(";") if len(parts) >= 2 and parts[0] == "4" and parts[1].isdigit(): + self._before_mutate() sub = int(parts[1]) prog = int(parts[2]) if len(parts) >= 3 and parts[2].isdigit() else None changed, status = self._status_store.apply_osc_9_4(sub, prog) @@ -2587,6 +2623,7 @@ def _handle_osc(self, code: int, data: bytes, terminator: bytes) -> None: parts = text.split(";") raw_kind = parts[0][:1] if parts and parts[0] else "" if raw_kind in ("A", "B", "C", "D"): + self._before_mutate() kind = PromptKind(raw_kind) exit_code: int | None = None is_continuation = any(p.strip() == "k=s" for p in parts[1:]) @@ -2621,6 +2658,7 @@ def _handle_osc(self, code: int, data: bytes, terminator: bytes) -> None: if self._policy.allow_program_status_query and cap: self._emit_reply(f"\x1b]7501;{cap}".encode("ascii") + out_term) return + self._before_mutate() changed, rec = self._status_store.apply_osc_7501(data) if changed: tid = rec.id if rec is not None else "" diff --git a/tests/test_pr2_review_fixes.py b/tests/test_pr2_review_fixes.py index 5c4c6a7..ce65099 100644 --- a/tests/test_pr2_review_fixes.py +++ b/tests/test_pr2_review_fixes.py @@ -4,6 +4,7 @@ import libvt from libvt.config import XTERM_PROFILE +from libvt.modes import Mode def test_resize_preserves_pending_wrap_and_wide_glyphs() -> None: @@ -67,3 +68,52 @@ def test_resize_preserves_pending_wrap_and_wide_glyphs() -> None: alt_resize.resize(rows=2, cols=8) alt_resize.feed(b"\x1b[?1049lX") assert alt_resize[0].text == "ABCDabcX" + + +def test_sync_2026_chunk_and_observer_invariance_and_cursor_hold() -> None: + """``?2026`` ``committed`` freezes pre-``BSU`` screen/cursor independent of cuts.""" + payload = b"B\x1b[?2026hC" + splits: list[list[bytes]] = [ + [payload], + [bytes([b]) for b in payload], + *[[payload[:i], payload[i:]] for i in range(1, len(payload))], + ] + for observe_before in (False, True): + for chunks in splits: + term = libvt.Terminal(rows=2, cols=8) + term.feed(b"A") + if observe_before: + assert term.committed[0].text == "A" + for chunk in chunks: + term.feed(chunk) + assert term.synchronized is True + held = term.committed + assert held[0].text == "AB" + assert (held.cursor.row, held.cursor.col) == (0, 2) + assert Mode.SYNCHRONIZED_OUTPUT not in held.modes + + live = term.snapshot() + assert live[0].text == "ABC" + assert (live.cursor.row, live.cursor.col) == (0, 3) + assert Mode.SYNCHRONIZED_OUTPUT in live.modes + + term.feed(b"\x1b[?2026l") + after = term.committed + assert after[0].text == "ABC" + assert (after.cursor.row, after.cursor.col) == (0, 3) + + # Scalar cursor/visibility/title hold at BSU while CPR & DECRQM report live state. + term2 = libvt.Terminal(rows=3, cols=10) + term2.feed(b"A") + term2.feed(b"\x1b[?2026h\x1b[2;3H\x1b[?25l\x1b]2;Next\x07\x1b[6n\x1b[?2026$p") + held2 = term2.committed + assert (held2.cursor.row, held2.cursor.col) == (0, 1) + assert held2.cursor.visible is True + assert held2.title == "" + assert term2.drain_replies() == b"\x1b[2;3R\x1b[?2026;1$y" + + term2.feed(b"\x1b[?2026l") + done2 = term2.committed + assert (done2.cursor.row, done2.cursor.col) == (1, 2) + assert done2.cursor.visible is False + assert done2.title == "Next" From 571ffd9318dcb5bda20e2fe907c4b3204096e18d Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 22 Nov 2026 08:27:22 -0600 Subject: [PATCH 11/29] Terminal(fix[erase]): Keep viewport on CSI 3 J (#6) why: Sharing the ED 2 branch with ED 3 erased all visible viewport cells, cleared pending_wrap, and emitted ScreenErased on scrollback-only CSI 3 J clears. what: - Separate mode == 3 and not selective from ED 2 so CSI 3 J clears scrollback without mutating visible rows or pending_wrap - Add Profile.ed3_clears_scrollback_on_alt (True on XTERM_PROFILE and TMUX_PROFILE, False on DEFAULT_PROFILE) - Ignore unrecognized ED/EL parameters and DECSED 3 without clearing pending_wrap --- src/libvt/config.py | 7 ++++++ src/libvt/terminal.py | 20 ++++++++++++++--- tests/test_pr2_review_fixes.py | 40 +++++++++++++++++++++++++++++++++- 3 files changed, 63 insertions(+), 4 deletions(-) diff --git a/src/libvt/config.py b/src/libvt/config.py index 2930494..0c2e5da 100644 --- a/src/libvt/config.py +++ b/src/libvt/config.py @@ -56,6 +56,10 @@ class Profile: Default reflow behavior for :meth:`~libvt.terminal.Terminal.resize` when ``reflow=None`` (``True`` on ``DEFAULT_PROFILE`` and ``TMUX_PROFILE``, ``False`` on ``XTERM_PROFILE``). + ed3_clears_scrollback_on_alt : bool + When ``True`` (``XTERM_PROFILE`` and ``TMUX_PROFILE``), ``CSI 3 J`` + executed while the alternate screen is active still clears primary + scrollback history. """ name: str = "libvt" @@ -73,6 +77,7 @@ class Profile: vs16_always_wide: bool = False tmux_window_rename: bool = False reflow_on_resize: bool = True + ed3_clears_scrollback_on_alt: bool = False DEFAULT_OSC7_HOSTS: frozenset[str] = frozenset({"", "localhost"}) @@ -195,6 +200,7 @@ class Limits: name="xterm", osc_7501_capabilities="", reflow_on_resize=False, + ed3_clears_scrollback_on_alt=True, ) TMUX_PROFILE = Profile( name="tmux", @@ -202,6 +208,7 @@ class Limits: pending_wrap_phantom_col=True, vs15_narrows_wide_emoji=False, tmux_window_rename=True, + ed3_clears_scrollback_on_alt=True, ) DEFAULT_POLICY = Policy() TMUX_CAPTURE_POLICY = Policy(allow_passthrough=True) diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py index 23fb696..518996c 100644 --- a/src/libvt/terminal.py +++ b/src/libvt/terminal.py @@ -1948,6 +1948,20 @@ def _erase_display( *, selective: bool, ) -> None: + if mode == 3 and not selective: + self._before_mutate() + if ( + not self._screens.active_is_alt + or self._profile.ed3_clears_scrollback_on_alt + ): + self._screens.primary.clear_history() + else: + scr.clear_history() + return + + if mode not in (0, 1, 2) and not (mode == 22 and not selective): + return + self._before_mutate() bce_w, bce_e = self._bce_pair() cause = EraseCause.DECSED if selective else EraseCause.ED @@ -1985,11 +1999,9 @@ def _erase_display( if c_row > 0: self._notify_erase(Rect(0, 0, c_row, scr.cols), cause) self._notify_erase(Rect(c_row, 0, 1, c_col + 1), cause) - elif mode in (2, 3): + elif mode == 2: for r in range(scr.rows): scr._rows[r].clear_range(0, scr.cols, bce_w, bce_e, selective=selective) - if mode == 3 and not selective: - scr.clear_history() self._notify_erase(Rect(0, 0, scr.rows, scr.cols), cause) elif mode == 22 and not selective: if not self._screens.active_is_alt: @@ -2007,6 +2019,8 @@ def _erase_line( *, selective: bool, ) -> None: + if mode not in (0, 1, 2): + return self._before_mutate() bce_w, bce_e = self._bce_pair() cause = EraseCause.DECSEL if selective else EraseCause.EL diff --git a/tests/test_pr2_review_fixes.py b/tests/test_pr2_review_fixes.py index ce65099..c4c6685 100644 --- a/tests/test_pr2_review_fixes.py +++ b/tests/test_pr2_review_fixes.py @@ -3,7 +3,8 @@ from __future__ import annotations import libvt -from libvt.config import XTERM_PROFILE +from libvt.config import DEFAULT_PROFILE, TMUX_PROFILE, XTERM_PROFILE +from libvt.events import ScreenErased from libvt.modes import Mode @@ -117,3 +118,40 @@ def test_sync_2026_chunk_and_observer_invariance_and_cursor_hold() -> None: assert (done2.cursor.row, done2.cursor.col) == (1, 2) assert done2.cursor.visible is False assert done2.title == "Next" + + +def test_ed3_preserves_viewport_and_pending_wrap_and_profile_alt() -> None: + """``CSI 3 J`` clears history without wiping viewport cells or ``pending_wrap``.""" + term = libvt.Terminal(rows=2, cols=4, scrollback=10, record_events=True) + term.feed(b"old\r\nnew\r\nABCD") + assert [r.text for r in term.history] == ["old"] + assert term.lines == ("new", "ABCD") + assert term.cursor.pending_wrap is True + term.drain_events() + + term.feed(b"\x1b[3J") + assert term.history == () + assert term.lines == ("new", "ABCD") + assert term.cursor.pending_wrap is True + assert [e for e in term.drain_events() if isinstance(e, ScreenErased)] == [] + + # DECSED 3 and out-of-range ED 99 are complete no-ops. + term.feed(b"\x1b[?3J\x1b[99J") + assert term.lines == ("new", "ABCD") + assert term.cursor.pending_wrap is True + + term.feed(b"E") + assert term.lines == ("ABCD", "E") + assert [r.text for r in term.history] == ["new"] + + # Alternate-screen ED 3 respects profile.ed3_clears_scrollback_on_alt. + def_term = libvt.Terminal(rows=2, cols=6, scrollback=10, profile=DEFAULT_PROFILE) + def_term.feed(b"hist1\r\nhist2\r\nvis\x1b[?1049hALT\x1b[3J") + assert def_term[0].text == "ALT" + assert [r.text for r in def_term.history] == ["hist1"] + + for prof in (XTERM_PROFILE, TMUX_PROFILE): + p_term = libvt.Terminal(rows=2, cols=6, scrollback=10, profile=prof) + p_term.feed(b"hist1\r\nhist2\r\nvis\x1b[?1049hALT\x1b[3J") + assert p_term[0].text == "ALT" + assert p_term.history == () From 5ad89f2f75843fe8b6223e449ff11854fc621dc6 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 22 Nov 2026 08:28:12 -0600 Subject: [PATCH 12/29] Terminal(feat[csi]): Add HPR and VPR motions (#7) why: Applications using terminfo hpa/vpa or relative cursor stepping emit CSI a (HPR) and CSI e (VPR), which differ from CUF/CUD outside origin mode and are ignored by tmux. what: - Implement CSI Ps a (HPR) and CSI Ps e (VPR) clamping to active margins under DECOM and to screen edges when DECOM is reset - Add Profile.hpr_vpr_enabled (False on TMUX_PROFILE) so tmux profile ignores HPR/VPR without raising ProtocolError under strict policy - Add HPR and VPR mnemonics to libvt.explain() --- src/libvt/codec.py | 2 ++ src/libvt/config.py | 6 ++++++ src/libvt/terminal.py | 12 ++++++++++++ tests/test_pr2_review_fixes.py | 36 +++++++++++++++++++++++++++++++++- 4 files changed, 55 insertions(+), 1 deletion(-) diff --git a/src/libvt/codec.py b/src/libvt/codec.py index 3bdc76a..237abf3 100644 --- a/src/libvt/codec.py +++ b/src/libvt/codec.py @@ -73,9 +73,11 @@ class ExplainedSpan: "X": "ECH", "Z": "CBT", "`": "HPA", + "a": "HPR", "b": "REP", "c": "DA1", "d": "VPA", + "e": "VPR", "f": "HVP", "g": "TBC", "h": "SM", diff --git a/src/libvt/config.py b/src/libvt/config.py index 0c2e5da..2f00bcd 100644 --- a/src/libvt/config.py +++ b/src/libvt/config.py @@ -60,6 +60,10 @@ class Profile: When ``True`` (``XTERM_PROFILE`` and ``TMUX_PROFILE``), ``CSI 3 J`` executed while the alternate screen is active still clears primary scrollback history. + hpr_vpr_enabled : bool + When ``True``, ``HPR`` (``CSI Ps a``) and ``VPR`` (``CSI Ps e``) move + the cursor relatively; when ``False`` (``TMUX_PROFILE``), both are + quietly ignored. """ name: str = "libvt" @@ -78,6 +82,7 @@ class Profile: tmux_window_rename: bool = False reflow_on_resize: bool = True ed3_clears_scrollback_on_alt: bool = False + hpr_vpr_enabled: bool = True DEFAULT_OSC7_HOSTS: frozenset[str] = frozenset({"", "localhost"}) @@ -209,6 +214,7 @@ class Limits: vs15_narrows_wide_emoji=False, tmux_window_rename=True, ed3_clears_scrollback_on_alt=True, + hpr_vpr_enabled=False, ) DEFAULT_POLICY = Policy() TMUX_CAPTURE_POLICY = Policy(allow_passthrough=True) diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py index 518996c..320b675 100644 --- a/src/libvt/terminal.py +++ b/src/libvt/terminal.py @@ -2257,6 +2257,12 @@ def _handle_csi( if col_iter <= floor: break self._set_cursor(scr, c_row, col_iter, pending_wrap=False) + elif ch_final == "a": # HPR + if not self._profile.hpr_vpr_enabled: + return + n = params.get(0, 1) + ceil = right if self._modes.is_set(Mode.DECOM) else scr.cols - 1 + self._set_cursor(scr, c_row, min(ceil, c_col + n), pending_wrap=False) elif ch_final == "d": # VPA row_1 = params.get(0, 1) if self._modes.is_set(Mode.DECOM): @@ -2264,6 +2270,12 @@ def _handle_csi( else: target_r = min(scr.rows - 1, row_1 - 1) self._set_cursor(scr, max(0, target_r), c_col) + elif ch_final == "e": # VPR + if not self._profile.hpr_vpr_enabled: + return + n = params.get(0, 1) + ceil = bottom if self._modes.is_set(Mode.DECOM) else scr.rows - 1 + self._set_cursor(scr, min(ceil, c_row + n), c_col, pending_wrap=False) elif ch_final in ("H", "f"): # CUP / HVP row_1 = params.get(0, 1) col_1 = params.get(1, 1) diff --git a/tests/test_pr2_review_fixes.py b/tests/test_pr2_review_fixes.py index c4c6685..e0a579c 100644 --- a/tests/test_pr2_review_fixes.py +++ b/tests/test_pr2_review_fixes.py @@ -3,7 +3,7 @@ from __future__ import annotations import libvt -from libvt.config import DEFAULT_PROFILE, TMUX_PROFILE, XTERM_PROFILE +from libvt.config import DEFAULT_PROFILE, TMUX_PROFILE, XTERM_PROFILE, Policy from libvt.events import ScreenErased from libvt.modes import Mode @@ -155,3 +155,37 @@ def test_ed3_preserves_viewport_and_pending_wrap_and_profile_alt() -> None: p_term.feed(b"hist1\r\nhist2\r\nvis\x1b[?1049hALT\x1b[3J") assert p_term[0].text == "ALT" assert p_term.history == () + + +def test_hpr_vpr_margins_decom_and_tmux_ignore() -> None: + """``HPR`` and ``VPR`` honor ``DECOM`` margins and ``TMUX_PROFILE`` ignore.""" + term = libvt.Terminal(rows=4, cols=8) + term.feed(b"A\x1b[2aB\x1b[1eC") + assert term[0].text == "A B" + assert term[1].text == " C" + + # HPR clears pending_wrap. + wrap_t = libvt.Terminal(rows=2, cols=4) + wrap_t.feed(b"ABCD\x1b[1aE") + assert wrap_t.lines == ("ABCE", "") + + # DECOM off (?6l): HPR/VPR cross DECLRMM and DECSTBM margins to screen edges. + margin_t = libvt.Terminal(rows=4, cols=8) + margin_t.feed(b"\x1b[?69h\x1b[2;3r\x1b[3;6s\x1b[2;3H\x1b[10a\x1b[10e") + assert (margin_t.cursor.row, margin_t.cursor.col) == (3, 7) + + # DECOM on (?6h): HPR/VPR clamp to active margins without double-adding origin. + margin_t.feed(b"\x1b[?6h\x1b[1a\x1b[1e") + assert (margin_t.cursor.row, margin_t.cursor.col) == (2, 3) + margin_t.feed(b"\x1b[99a\x1b[99e") + assert (margin_t.cursor.row, margin_t.cursor.col) == (2, 5) + + # TMUX_PROFILE ignores HPR/VPR quietly even under Policy(strict=True). + tm = libvt.Terminal( + rows=2, cols=8, profile=TMUX_PROFILE, policy=Policy(strict=True) + ) + tm.feed(b"A\x1b[3aB\x1b[2eC") + assert tm[0].text == "ABC" + + spans = libvt.explain(b"\x1b[3a\x1b[2e") + assert [s.mnemonic for s in spans] == ["HPR", "VPR"] From 9d49d6109c9018112ff4bf943439a828cbb6908e Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 22 Nov 2026 08:30:02 -0600 Subject: [PATCH 13/29] Grid(fix[margins]): Fix DECSLRM scroll and REP (#8) why: Partial-width DECSLRM scrolls left text_used stale, partial ECH and _Row.freeze() checked full cols rather than row used bounds, non-print actions retained REP's last character, and ?7l right-margin VS16 appended a 2-column selector onto a 1-column slot. what: - Synchronize dst_row.used and dst_row.text_used bidirectionally in partial-width scroll_up and scroll_down - Guard clear_range, insert_blanks, delete_cells, and freeze() against row used/text_used and right-margin bounds - Clear _last_printed on non-print actions and reset margins/rows on DECALN (ESC # 8) - Keep right-margin narrow cells unexpanded on VS16 when wrapping is unavailable --- src/libvt/_grid.py | 43 ++++++++++++++++++------------- src/libvt/screen.py | 37 ++++++++++++++++++++++++-- src/libvt/terminal.py | 31 +++++++++++++++++++--- tests/test_pr2_review_fixes.py | 47 ++++++++++++++++++++++++++++++++++ 4 files changed, 135 insertions(+), 23 deletions(-) diff --git a/src/libvt/_grid.py b/src/libvt/_grid.py index 049e7a4..dca378c 100644 --- a/src/libvt/_grid.py +++ b/src/libvt/_grid.py @@ -207,7 +207,8 @@ def used(self) -> int: if self.cells is not None: return len(self.cells) run_end = self.runs[-1][0] if self.runs else 0 - return max(len(self.text), run_end) + ext_end = (self.exts[-1][0] + 1) if self.exts else 0 + return max(len(self.text), run_end, ext_end) def rstrip_text(self) -> str: """Return right-trimmed row text.""" @@ -558,7 +559,7 @@ def clear_range( self._set_raw(c, " ", bce_word, WidthRole.NARROW, bce_ext) if bce_word != 0 or bce_ext is not None: self.used = max(self.used, hi) - elif hi >= cols: + elif hi >= self.used: while ( self.used > lo and self.chars[self.used - 1] == " " @@ -566,7 +567,7 @@ def clear_range( and self.ext_at(self.used - 1) is None ): self.used -= 1 - if hi >= cols: + if hi >= self.text_used: while self.text_used > lo and not self.is_protected(self.text_used - 1): self.text_used -= 1 return @@ -601,10 +602,10 @@ def clear_range( self.ext.pop(c, None) if bce_word != 0: self.used = max(self.used, hi) - elif hi >= cols: + elif hi >= self.used: # Clamp used to lo without erasing explicit spaces printed left of lo! self.used = min(self.used, lo) - if hi >= cols: + if hi >= self.text_used: self.text_used = min(self.text_used, lo) def insert_blanks( @@ -675,9 +676,11 @@ def insert_blanks( for c in range(col, col + shift): self._set_raw(c, " ", bce_word, WidthRole.NARROW, bce_ext) - if bce_word != 0 or bce_ext is not None or self.used > col: + if self.used <= right + 1 and ( + bce_word != 0 or bce_ext is not None or self.used > col + ): self.used = min(right + 1, max(self.used + shift, col + shift)) - if self.text_used > col: + if self.text_used <= right + 1 and self.text_used > col: self.text_used = min(right + 1, self.text_used + shift) def delete_cells( @@ -740,11 +743,12 @@ def delete_cells( for c in range(right - shift + 1, right + 1): self._set_raw(c, " ", bce_word, WidthRole.NARROW, bce_ext) - if bce_word != 0 or bce_ext is not None: - self.used = max(self.used, right + 1) - elif self.used > col: - self.used = max(col, self.used - shift) - if self.text_used > col: + if self.used <= right + 1: + if bce_word != 0 or bce_ext is not None: + self.used = max(self.used, right + 1) + elif self.used > col: + self.used = max(col, self.used - shift) + if self.text_used <= right + 1 and self.text_used > col: self.text_used = max(col, self.text_used - shift) def resize(self, cols: int) -> None: @@ -801,19 +805,22 @@ def freeze(self) -> FrozenRow: if len(text) != t_used: cells = tuple(self.chars[:t_used]) + u = min(cols, self.used) runs: tuple[tuple[int, int], ...] - if self.attrs is None: - runs = () if self.uniform_attr == 0 else ((cols, self.uniform_attr),) + if u == 0: + runs = () + elif self.attrs is None: + runs = () if self.uniform_attr == 0 else ((u, self.uniform_attr),) else: run_list: list[tuple[int, int]] = [] - cur_word = self.attrs[0] if cols > 0 else 0 - for c in range(1, cols): + cur_word = self.attrs[0] + for c in range(1, u): w = self.attrs[c] if w != cur_word: run_list.append((c, cur_word)) cur_word = w - if cols > 0 and (cur_word != 0 or run_list): - run_list.append((cols, cur_word)) + if cur_word != 0: + run_list.append((u, cur_word)) runs = tuple(run_list) exts = tuple(sorted(self.ext.items())) if self.ext else () diff --git a/src/libvt/screen.py b/src/libvt/screen.py index e67a222..b34d929 100644 --- a/src/libvt/screen.py +++ b/src/libvt/screen.py @@ -697,7 +697,7 @@ def scroll_up( role = unpack_width_role(word) base = word & _WIDTH_CLEAR_MASK dst_row._set_raw(c, src_row.chars[c], base, role, src_row.ext_at(c)) - dst_row.used = max(dst_row.used, min(src_row.used, r_col + 1)) + _sync_partial_scroll_bounds(dst_row, src_row, left, r_col) for clr_r in range(b_row - shift + 1, b_row + 1): self._rows[clr_r].wrapped = False @@ -756,7 +756,7 @@ def scroll_down( role = unpack_width_role(word) base = word & _WIDTH_CLEAR_MASK dst_row._set_raw(c, src_row.chars[c], base, role, src_row.ext_at(c)) - dst_row.used = max(dst_row.used, min(src_row.used, r_col + 1)) + _sync_partial_scroll_bounds(dst_row, src_row, left, r_col) for clr_r in range(t_row, t_row + shift): self._rows[clr_r].wrapped = False @@ -1010,6 +1010,39 @@ def reset(self) -> None: self.keyboard_stack.reset() +def _sync_partial_scroll_bounds( + dst_row: _Row, + src_row: _Row, + left: int, + r_col: int, +) -> None: + limit = r_col + 1 + if dst_row.used <= limit: + cand_u = ( + min(src_row.used, limit) if src_row.used > left else min(dst_row.used, left) + ) + floor_u = min(dst_row.used, left) + while ( + cand_u > floor_u + and dst_row.chars[cand_u - 1] == " " + and dst_row.attr_at(cand_u - 1) == 0 + and dst_row.ext_at(cand_u - 1) is None + ): + cand_u -= 1 + dst_row.used = cand_u + if dst_row.text_used <= limit: + cand_t = ( + min(src_row.text_used, limit) + if src_row.text_used > left + else min(dst_row.text_used, left) + ) + if src_row.text_used > limit: + floor_t = min(dst_row.text_used, left) + while cand_t > floor_t and dst_row.chars[cand_t - 1] == " ": + cand_t -= 1 + dst_row.text_used = cand_t + + class ScreenSet: """Dual primary and alternate (``?1049``) screen pair.""" diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py index 320b675..f430636 100644 --- a/src/libvt/terminal.py +++ b/src/libvt/terminal.py @@ -1519,6 +1519,15 @@ def _handle_print(self, text: str) -> None: ) continue + if ( + w_override == 2 + and cur_role == int(WidthRole.NARROW) + and pc >= eff_right + ): + # Cannot wrap (e.g. ?7l or bottom margin): keep cell narrow + # without appending a selector that inflates display_width. + continue + if ( w_override == 2 and cur_role == int(WidthRole.NARROW) @@ -1732,6 +1741,7 @@ def _cursor_left(self, scr: Screen, count: int, *, is_backspace: bool) -> None: ) def _handle_execute(self, byte: int) -> None: + self._last_printed = "" scr = self._screens.active _, _, left, right = self._effective_margins(scr) if byte == 0x07: # BEL @@ -1800,6 +1810,7 @@ def _restore_cursor(self) -> None: ) def _handle_esc(self, intermediates: bytes, final: int) -> None: + self._last_printed = "" scr = self._screens.active if not intermediates: if final == 0x37: # ESC 7 DECSC @@ -1856,8 +1867,16 @@ def _handle_esc(self, intermediates: bytes, final: int) -> None: self._g_sets[slot] = "B" elif intermediates == b"#" and final == 0x38: # DECALN self._before_mutate() + fill = "E" * scr.cols for r in scr._rows: - r.write_ascii_slice(0, "E" * scr.cols, 0, None) + r.reset_blank(scr.cols) + r.write_ascii_slice(0, fill, 0, None) + scr.scroll_region = ScrollRegion( + top=0, + bottom=scr.rows - 1, + left=0, + right=scr.cols - 1, + ) self._set_cursor(scr, 0, 0, pending_wrap=False) else: inter_s = intermediates.decode("ascii", errors="replace") @@ -2068,6 +2087,8 @@ def _handle_csi( intermediates: bytes, final: int, ) -> None: + prev_printed = self._last_printed + self._last_printed = "" scr = self._screens.active top, bottom, left, right = self._effective_margins(scr) @@ -2419,9 +2440,9 @@ def _handle_csi( ) self._clear_cluster_anchor() elif ch_final == "b": # REP - if self._last_printed: + if prev_printed: count = min(self._limits.max_rep_count, params.get(0, 1)) - self._handle_print(self._last_printed * count) + self._handle_print(prev_printed * count) elif ch_final == "r": # DECSTBM t_arg = params.get(0, 1) - 1 b_arg = params.get(1, scr.rows) - 1 @@ -2513,6 +2534,7 @@ def _handle_csi( self._unhandled("csi", f"CSI {ch_final}") def _handle_window_rename(self, raw: bytes) -> None: + self._last_printed = "" try: name = raw.decode("utf-8", errors="strict") except UnicodeDecodeError: @@ -2563,6 +2585,7 @@ def _update_cwd(self, raw_uri: str, *, from_osc7: bool = True) -> None: ) def _handle_osc(self, code: int, data: bytes, terminator: bytes) -> None: + self._last_printed = "" scr = self._screens.active out_term = b"\x07" if terminator == b"\x07" else b"\x1b\\" @@ -2752,6 +2775,7 @@ def _handle_dcs( final: int, data: bytes, ) -> None: + self._last_printed = "" # DECRQSS: DCS $ q ST if prefix == 0 and intermediates == b"$" and final == ord("q"): self._handle_decrqss(data) @@ -2817,6 +2841,7 @@ def _handle_dcs( self._unhandled("dcs", f"DCS {inter_s}{chr(final)}") def _handle_apc(self, data: bytes) -> None: + self._last_printed = "" if data.startswith(b"G"): if self._record_events or self._on_event is not None: body = data[1:] diff --git a/tests/test_pr2_review_fixes.py b/tests/test_pr2_review_fixes.py index e0a579c..c809680 100644 --- a/tests/test_pr2_review_fixes.py +++ b/tests/test_pr2_review_fixes.py @@ -189,3 +189,50 @@ def test_hpr_vpr_margins_decom_and_tmux_ignore() -> None: spans = libvt.explain(b"\x1b[3a\x1b[2e") assert [s.mnemonic for s in spans] == ["HPR", "VPR"] + + +def test_decslrm_scroll_clear_range_rep_decaln_and_vs16_clamp() -> None: + """``DECSLRM`` scroll, ``ECH``, ``REP``, ``DECALN``, and ``?7l`` ``VS16`` hold.""" + # DECSLRM scroll_up updates text_used bidirectionally. + scr_t = libvt.Terminal(rows=2, cols=6) + scr_t.feed(b"AB\x1b[?69h\x1b[1;2s\x1b[1;1H\x1b[S") + assert scr_t[0].text == "" + + scr_t2 = libvt.Terminal(rows=2, cols=6) + scr_t2.feed(b"\r\nCD\x1b[?69h\x1b[1;2s\x1b[1;1H\x1b[S") + assert scr_t2[0].text == "CD" + + scr_t3 = libvt.Terminal(rows=2, cols=6) + scr_t3.feed(b"AB\x1b[?69h\x1b[1;2s\x1b[1;1H\x1b[T") + assert scr_t3[1].text == "AB" + + # Partial ECH trims text_used when erasing to the end of written text. + ech_t = libvt.Terminal(rows=2, cols=10) + ech_t.feed(b"ABCD\x1b[3G\x1b[2X") + assert ech_t[0].text == "AB" + + # _Row.freeze() does not inflate FrozenRow.used to full screen width. + fr_t = libvt.Terminal(rows=2, cols=80, scrollback=5) + fr_t.feed(b"\x1b[31mA\x1b[0m\r\nB\r\nC") + assert fr_t._screens.primary._history[0].used == 1 + + # Non-print sequences clear REP _last_printed state. + rep_t = libvt.Terminal(rows=2, cols=10) + rep_t.feed(b"A\x1b[C\x1b[3b") + assert rep_t[0].text == "A" + rep_t.reset() + rep_t.feed(b"A\r\x1b[3b") + assert rep_t[0].text == "A" + + # DECALN resets margins and wrapped flags before filling 'E'. + aln_t = libvt.Terminal(rows=2, cols=4) + aln_t.feed(b"ABCDEF\x1b[?69h\x1b[2;3s\x1b#8") + assert aln_t.lines == ("EEEE", "EEEE") + assert aln_t[0].wrapped is False + assert aln_t.screen.scroll_region == libvt.ScrollRegion(0, 1, 0, 3) + + # ?7l right-margin VS16 keeps display_width <= cols without 2-col overflow. + vs_t = libvt.Terminal(rows=2, cols=4) + vs_t.feed("\x1b[?7lABC\u26a0\ufe0f".encode()) + assert libvt.display_width(vs_t[0].text) <= 4 + assert vs_t[0, 3].width == 1 From 22d972630f878bcd2f4056f8958488c3604e05d0 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 22 Nov 2026 08:32:35 -0600 Subject: [PATCH 14/29] Format(fix[export]): Keep VT BCE and timeout info (#9) why: Formatter(VT) dropped background-color-erase styles beyond text_used, Formatter(HTML) omitted ANSI/indexed palettes and decoration styles, and TerminalTimeoutError carried no parser or flight-recorder diagnostics on stuck waits. what: - Emit CSI K and CSI Ps X spans in Formatter(VT) so BCE backgrounds and right-trimmed row text both round-trip - Resolve 16/256-color palettes, reverse video, and combined underline decorations in Formatter(HTML) - Add keyword diagnostic attributes and pickle support to TerminalTimeoutError while preserving single-arg OSError formatting - Attach a default FlightRecorder in AsyncTerminalStream, format boxed timeout dumps, and forward full open_pty() kwargs in vt_pty --- src/libvt/aio.py | 88 +++++++++++++++++++++--------- src/libvt/exc.py | 56 +++++++++++++++++++ src/libvt/pytest_plugin.py | 16 ++++++ src/libvt/style.py | 44 +++++++++++++++ src/libvt/terminal.py | 98 ++++++++++++++++++++++++++++++---- tests/test_pr2_review_fixes.py | 64 ++++++++++++++++++++++ 6 files changed, 329 insertions(+), 37 deletions(-) diff --git a/src/libvt/aio.py b/src/libvt/aio.py index d98fc67..40f1aec 100644 --- a/src/libvt/aio.py +++ b/src/libvt/aio.py @@ -111,6 +111,29 @@ def _on_ready() -> None: loop.remove_reader(fd) +def _make_timeout_error( + terminal: Terminal, + snap: Snapshot, + header: str, + *, + eof: bool, +) -> TerminalTimeoutError: + from libvt.testing import format_flight_recorder, format_screen_box + + rec = terminal.recorder + recent = rec.tail(256) if rec is not None else b"" + box = format_screen_box(snap, rows=min(snap.rows, 12), cols=min(snap.cols, 80)) + diag = format_flight_recorder(terminal) + full_msg = f"{header}\n{box}\n{diag}" + return TerminalTimeoutError( + full_msg, + parser_state=terminal.parser_state, + screen_text=snap.text, + recent_bytes=recent, + eof=eof, + ) + + class ReplyWriter(t.Protocol): """Structural writer protocol satisfied by :class:`asyncio.StreamWriter`.""" @@ -150,7 +173,9 @@ def __init__( self.reader = reader self.writer = writer self.terminal = ( - terminal if terminal is not None else Terminal(rows=rows, cols=cols) + terminal + if terminal is not None + else Terminal(rows=rows, cols=cols, recorder=FlightRecorder()) ) self.chunk_size = chunk_size self.sync_timeout = sync_timeout @@ -199,8 +224,11 @@ async def pump_once(self) -> bool: return True async def _pump_loop(self) -> None: - while await self.pump_once(): - pass + try: + while await self.pump_once(): + pass + finally: + self._frame_event.set() def start(self) -> asyncio.Task[None]: """Start background stream pumping on the running event loop.""" @@ -248,6 +276,14 @@ async def wait_for( ) deadline = time.monotonic() + timeout while True: + if ( + self._task is not None + and self._task.done() + and not self._task.cancelled() + ): + task_exc = self._task.exception() + if task_exc is not None: + raise task_exc now = time.monotonic() if self.terminal.synchronized: self._update_sync_timer(now) @@ -255,21 +291,23 @@ async def wait_for( if check(snap): return snap if self._eof: - msg = ( - f"stream reached EOF before predicate matched; " - f"screen text={snap.text!r}" + raise _make_timeout_error( + self.terminal, + snap, + "stream reached EOF before predicate matched", + eof=True, ) - raise TerminalTimeoutError(msg) remaining = deadline - now if remaining <= 0: live = self.terminal.snapshot() if check(live): return live - msg = ( - f"timed out after {timeout:.2f}s waiting for terminal state; " - f"screen text={live.text!r}" + raise _make_timeout_error( + self.terminal, + live, + f"timed out after {timeout:.2f}s waiting for terminal state", + eof=False, ) - raise TerminalTimeoutError(msg) self._frame_event.clear() wait_slice = ( min(remaining, self.sync_timeout) @@ -277,14 +315,10 @@ async def wait_for( else remaining ) if self._task is None: - try: + with contextlib.suppress(TimeoutError): await asyncio.wait_for(self.pump_once(), timeout=wait_slice) - except TimeoutError as exc: - if self.terminal.synchronized: - self._update_sync_timer(time.monotonic()) - continue - msg = f"timed out after {timeout:.2f}s waiting for stream bytes" - raise TerminalTimeoutError(msg) from exc + if self.terminal.synchronized: + self._update_sync_timer(time.monotonic()) else: with contextlib.suppress(TimeoutError): await asyncio.wait_for( @@ -436,21 +470,23 @@ async def wait_for( if check(snap): return snap if self._eof: - msg = ( - f"PTY reached EOF before predicate matched; " - f"screen text={snap.text!r}" + raise _make_timeout_error( + self.terminal, + snap, + "PTY reached EOF before predicate matched", + eof=True, ) - raise TerminalTimeoutError(msg) remaining = deadline - now if remaining <= 0: live = self.terminal.snapshot() if check(live): return live - msg = ( - f"timed out after {timeout:.2f}s waiting for PTY state; " - f"screen text={live.text!r}" + raise _make_timeout_error( + self.terminal, + live, + f"timed out after {timeout:.2f}s waiting for PTY state", + eof=False, ) - raise TerminalTimeoutError(msg) self._frame_event.clear() wait_slice = ( min(remaining, self.sync_timeout) diff --git a/src/libvt/exc.py b/src/libvt/exc.py index e841ea9..5b19d47 100644 --- a/src/libvt/exc.py +++ b/src/libvt/exc.py @@ -2,6 +2,12 @@ from __future__ import annotations +import collections.abc +import typing as t + +if t.TYPE_CHECKING: + from libvt.parser import ParserState + class LibVtError(Exception): """Base exception for all libvt errors.""" @@ -15,9 +21,59 @@ class UnsafePasteError(LibVtError): """Raised when pasted text contains control or bracket-escape bytes.""" +def _rebuild_terminal_timeout_error( + message: str, + parser_state: ParserState | None, + screen_text: str, + recent_bytes: bytes, + eof: bool, +) -> TerminalTimeoutError: + return TerminalTimeoutError( + message, + parser_state=parser_state, + screen_text=screen_text, + recent_bytes=recent_bytes, + eof=eof, + ) + + class TerminalTimeoutError(LibVtError, TimeoutError): """Raised when an async terminal stream wait exceeds its deadline.""" + def __init__( + self, + message: str, + *, + parser_state: ParserState | None = None, + screen_text: str = "", + recent_bytes: bytes = b"", + eof: bool = False, + ) -> None: + super().__init__(message) + self._message = message + self.parser_state = parser_state + self.screen_text = screen_text + self.recent_bytes = recent_bytes + self.eof = eof + + def __reduce__( + self, + ) -> tuple[ + collections.abc.Callable[..., TerminalTimeoutError], + tuple[str, ParserState | None, str, bytes, bool], + ]: + """Preserve message and diagnostic attributes across ``pickle``.""" + return ( + _rebuild_terminal_timeout_error, + ( + self._message, + self.parser_state, + self.screen_text, + self.recent_bytes, + self.eof, + ), + ) + class ScreenAssertionError(LibVtError, AssertionError): """Raised when :func:`~libvt.testing.assert_screen` detects a screen mismatch.""" diff --git a/src/libvt/pytest_plugin.py b/src/libvt/pytest_plugin.py index b8fb99e..525943e 100644 --- a/src/libvt/pytest_plugin.py +++ b/src/libvt/pytest_plugin.py @@ -46,10 +46,15 @@ def __call__( *, rows: int = 24, cols: int = 80, + scrollback: int = 2_000, env: collections.abc.Mapping[str, str] | None = None, cwd: str | os.PathLike[str] | None = None, tty_mode: TtyMode = "cooked", python_executable: str | os.PathLike[str] | None = None, + profile: Profile = ..., + policy: Policy = ..., + limits: Limits = ..., + sync_timeout: float = 1.0, ) -> contextlib.AbstractAsyncContextManager[PtySession]: """Open a POSIX PTY subprocess session.""" @@ -122,25 +127,36 @@ def vt_pty() -> PtyFactory: pytest.skip("vt_pty requires POSIX pty.openpty()") from libvt.aio import open_pty + from libvt.config import DEFAULT_LIMITS, DEFAULT_POLICY, DEFAULT_PROFILE def _spawn( argv: collections.abc.Sequence[str], *, rows: int = 24, cols: int = 80, + scrollback: int = 2_000, env: collections.abc.Mapping[str, str] | None = None, cwd: str | os.PathLike[str] | None = None, tty_mode: TtyMode = "cooked", python_executable: str | os.PathLike[str] | None = None, + profile: Profile = DEFAULT_PROFILE, + policy: Policy = DEFAULT_POLICY, + limits: Limits = DEFAULT_LIMITS, + sync_timeout: float = 1.0, ) -> contextlib.AbstractAsyncContextManager[PtySession]: return open_pty( argv, rows=rows, cols=cols, + scrollback=scrollback, env=env, cwd=cwd, tty_mode=tty_mode, python_executable=python_executable, + profile=profile, + policy=policy, + limits=limits, + sync_timeout=sync_timeout, ) return _spawn diff --git a/src/libvt/style.py b/src/libvt/style.py index a4ab883..83559b8 100644 --- a/src/libvt/style.py +++ b/src/libvt/style.py @@ -151,6 +151,50 @@ class Style: DEFAULT_STYLE = Style() +_ANSI_16_RGB: tuple[tuple[int, int, int], ...] = ( + (0, 0, 0), + (205, 0, 0), + (0, 205, 0), + (205, 205, 0), + (0, 0, 238), + (205, 0, 205), + (0, 205, 205), + (229, 229, 229), + (127, 127, 127), + (255, 0, 0), + (0, 255, 0), + (255, 255, 0), + (92, 92, 255), + (255, 0, 255), + (0, 255, 255), + (255, 255, 255), +) +_CUBE_STEPS: tuple[int, ...] = (0, 95, 135, 175, 215, 255) + + +def _resolve_color_rgb( + color: Color, + default_rgb: tuple[int, int, int], +) -> tuple[int, int, int]: + """Resolve *color* to an 8-bit ``(r, g, b)`` triple using standard xterm256.""" + if color is None: + return default_rgb + if isinstance(color, RgbColor): + return (color.r, color.g, color.b) + idx = int(color) if isinstance(color, AnsiColor) else color.index + if idx < 16: + return _ANSI_16_RGB[idx] + if idx < 232: + n = idx - 16 + return ( + _CUBE_STEPS[n // 36], + _CUBE_STEPS[(n // 6) % 6], + _CUBE_STEPS[n % 6], + ) + gray = 8 + (idx - 232) * 10 + return (gray, gray, gray) + + __all__ = [ "DEFAULT_STYLE", "AnsiColor", diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py index f430636..af3fae4 100644 --- a/src/libvt/terminal.py +++ b/src/libvt/terminal.py @@ -94,9 +94,9 @@ Color, Hyperlink, IndexedColor, - RgbColor, Style, UnderlineStyle, + _resolve_color_rgb, ) # DEC Special Graphics ('0') mapping for 0x5F..0x7E (VT100 / xterm / tmux tty-acs.c). @@ -352,9 +352,14 @@ def format( output_format: OutputFormat = OutputFormat.PLAIN, *, policy: Policy = DEFAULT_POLICY, + profile: Profile = DEFAULT_PROFILE, ) -> str: """Render this snapshot using :class:`Formatter`.""" - return Formatter(output_format, policy=policy).format_snapshot(self) + return Formatter( + output_format, + policy=policy, + profile=profile, + ).format_snapshot(self) def to_dict(self) -> dict[str, t.Any]: """Serialize snapshot state into a deterministic JSON-compatible dict.""" @@ -452,16 +457,18 @@ def _is_safe_uri(uri: str) -> bool: class Formatter: """Serialize a :class:`Snapshot` or :class:`Terminal` to text, VT, or HTML.""" - __slots__ = ("output_format", "policy") + __slots__ = ("output_format", "policy", "profile") def __init__( self, output_format: OutputFormat = OutputFormat.PLAIN, *, policy: Policy = DEFAULT_POLICY, + profile: Profile = DEFAULT_PROFILE, ) -> None: self.output_format = output_format self.policy = policy + self.profile = profile def format_snapshot(self, snapshot: Snapshot) -> str: """Render *snapshot* in :attr:`output_format`.""" @@ -515,6 +522,44 @@ def _render_vt(self, snapshot: Snapshot) -> str: out.append(_style_to_sgr(style)) cur_style = style out.append(row.chars[c]) + if not row.wrapped and row.used > limit: + cur_col_pos = limit + span_c = limit + row_used = min(snapshot.cols, row.used) + while span_c < row_used: + word = row.attr_at(span_c) + ext = row.ext_at(span_c) + style = unpack_style(word, ext) + link = ext.hyperlink if ext is not None else None + end_c = span_c + 1 + while end_c < row_used: + nw = row.attr_at(end_c) + ne = row.ext_at(end_c) + if ( + unpack_style(nw, ne) != style + or (ne.hyperlink if ne is not None else None) != link + ): + break + end_c += 1 + if style != DEFAULT_STYLE or link is not None: + if cur_col_pos != span_c: + out.append(f"\x1b[{r_idx + 1};{span_c + 1}H") + cur_col_pos = span_c + if link != cur_link: + if link is None: + out.append("\x1b]8;;\x1b\\") + else: + param = f"id={link.id}" if link.id else "" + out.append(f"\x1b]8;{param};{link.uri}\x1b\\") + cur_link = link + if style != cur_style: + out.append(_style_to_sgr(style)) + cur_style = style + if end_c == snapshot.cols: + out.append("\x1b[K") + else: + out.append(f"\x1b[{end_c - span_c}X") + span_c = end_c if cur_link is not None: out.append("\x1b]8;;\x1b\\") if cur_style != DEFAULT_STYLE: @@ -525,6 +570,14 @@ def _render_vt(self, snapshot: Snapshot) -> str: def _render_html(self, snapshot: Snapshot) -> str: lines: list[str] = ['
']
         allow_unsafe = self.policy.allow_unsafe_uris
+        def_fg = self.profile.fg_rgb
+        def_bg = self.profile.bg_rgb
+        ul_styles = {
+            UnderlineStyle.DOUBLE: "double",
+            UnderlineStyle.CURLY: "wavy",
+            UnderlineStyle.DOTTED: "dotted",
+            UnderlineStyle.DASHED: "dashed",
+        }
         for row in snapshot._rows:
             view = RowView(row)
             chunks: list[str] = []
@@ -534,16 +587,39 @@ def _render_html(self, snapshot: Snapshot) -> str:
                 css: list[str] = []
                 if style.bold:
                     css.append("font-weight:bold")
+                if style.dim:
+                    css.append("opacity:0.65")
                 if style.italic:
                     css.append("font-style:italic")
-                if isinstance(style.fg, RgbColor):
-                    css.append(
-                        f"color:rgb({style.fg.r},{style.fg.g},{style.fg.b})",
-                    )
-                if isinstance(style.bg, RgbColor):
-                    css.append(
-                        f"background-color:rgb({style.bg.r},{style.bg.g},{style.bg.b})",
-                    )
+                if style.hidden:
+                    css.append("visibility:hidden")
+                if style.reverse:
+                    fg_r, fg_g, fg_b = _resolve_color_rgb(style.bg, def_bg)
+                    bg_r, bg_g, bg_b = _resolve_color_rgb(style.fg, def_fg)
+                    css.append(f"color:rgb({fg_r},{fg_g},{fg_b})")
+                    css.append(f"background-color:rgb({bg_r},{bg_g},{bg_b})")
+                else:
+                    if style.fg is not None:
+                        fg_r, fg_g, fg_b = _resolve_color_rgb(style.fg, def_fg)
+                        css.append(f"color:rgb({fg_r},{fg_g},{fg_b})")
+                    if style.bg is not None:
+                        bg_r, bg_g, bg_b = _resolve_color_rgb(style.bg, def_bg)
+                        css.append(f"background-color:rgb({bg_r},{bg_g},{bg_b})")
+                dec_lines: list[str] = []
+                if style.underline != UnderlineStyle.NONE:
+                    dec_lines.append("underline")
+                if style.overline:
+                    dec_lines.append("overline")
+                if style.strikethrough:
+                    dec_lines.append("line-through")
+                if dec_lines:
+                    css.append(f"text-decoration-line:{' '.join(dec_lines)}")
+                ul_css = ul_styles.get(style.underline)
+                if ul_css is not None:
+                    css.append(f"text-decoration-style:{ul_css}")
+                if style.underline_color is not None:
+                    ur, ug, ub = _resolve_color_rgb(style.underline_color, def_fg)
+                    css.append(f"text-decoration-color:rgb({ur},{ug},{ub})")
                 span = (
                     f'{escaped}'
                     if css
diff --git a/tests/test_pr2_review_fixes.py b/tests/test_pr2_review_fixes.py
index c809680..59d29af 100644
--- a/tests/test_pr2_review_fixes.py
+++ b/tests/test_pr2_review_fixes.py
@@ -2,10 +2,20 @@
 
 from __future__ import annotations
 
+import asyncio
+import pickle
+
+import pytest
+
 import libvt
+from libvt.aio import AsyncTerminalStream
 from libvt.config import DEFAULT_PROFILE, TMUX_PROFILE, XTERM_PROFILE, Policy
 from libvt.events import ScreenErased
+from libvt.exc import TerminalTimeoutError
 from libvt.modes import Mode
+from libvt.parser import ParserState
+from libvt.style import AnsiColor
+from libvt.terminal import OutputFormat
 
 
 def test_resize_preserves_pending_wrap_and_wide_glyphs() -> None:
@@ -236,3 +246,57 @@ def test_decslrm_scroll_clear_range_rep_decaln_and_vs16_clamp() -> None:
     vs_t.feed("\x1b[?7lABC\u26a0\ufe0f".encode())
     assert libvt.display_width(vs_t[0].text) <= 4
     assert vs_t[0, 3].width == 1
+
+
+async def test_formatter_vt_bce_roundtrip_html_palette_and_timeout_diagnostics() -> (
+    None
+):
+    """``Formatter`` preserves BCE/HTML styles and timeout diagnostics."""
+    # VT formatter preserves both right-trimmed text AND trailing BCE background!
+    bce_t = libvt.Terminal(rows=2, cols=10)
+    bce_t.feed(b"\x1b[42mHI\x1b[K")
+    snap = bce_t.snapshot()
+    assert snap[0].text == "HI"
+    assert snap[0, 9].style.bg == AnsiColor.GREEN
+
+    vt_str = snap.format(OutputFormat.VT)
+    rt = libvt.Terminal(rows=2, cols=10)
+    rt.feed_str(vt_str)
+    assert rt[0].text == "HI"
+    assert rt[0, 9].style.bg == AnsiColor.GREEN
+
+    # HTML formatter renders ANSI/indexed colors, reverse video, and wavy lines.
+    html_t = libvt.Terminal(rows=2, cols=16)
+    html_t.feed(b"\x1b[31;48;5;208;4:3;9;53mWARN\x1b[0;7mREV\x1b[0m")
+    rendered_html = html_t.snapshot().format(OutputFormat.HTML)
+    assert "color:rgb(" in rendered_html
+    assert "background-color:rgb(255,135,0)" in rendered_html
+    assert "text-decoration-style:wavy" in rendered_html
+    assert "underline" in rendered_html and "overline" in rendered_html
+
+    # TerminalTimeoutError preserves single-arg OSError str/errno and pickles cleanly.
+    manual = TerminalTimeoutError(
+        "timed out",
+        parser_state=ParserState.OSC_STRING,
+        screen_text="hello",
+        recent_bytes=b"\x1b]0;stuck",
+        eof=False,
+    )
+    assert isinstance(manual, TimeoutError)
+    assert manual.errno is None
+    assert str(manual) == "timed out"
+    unpickled = pickle.loads(pickle.dumps(manual))
+    assert str(unpickled) == "timed out"
+    assert unpickled.parser_state == ParserState.OSC_STRING
+    assert unpickled.recent_bytes == b"\x1b]0;stuck"
+
+    # AsyncTerminalStream attaches FlightRecorder and populates timeout fields.
+    reader = asyncio.StreamReader()
+    stream = AsyncTerminalStream(reader, rows=2, cols=10)
+    reader.feed_data(b"hello\x1b]0;stuck")
+    with pytest.raises(TerminalTimeoutError) as exc_info:
+        await stream.wait_for("missing", timeout=0.05)
+    err = exc_info.value
+    assert err.parser_state == ParserState.OSC_STRING
+    assert b"\x1b]0;stuck" in err.recent_bytes
+    assert "Flight Recorder:" in str(err)

From 5eda5ffb6b81019ce4621a23b67fa6ce4c95bf08 Mon Sep 17 00:00:00 2001
From: Tony Narlock 
Date: Sun, 22 Nov 2026 08:35:45 -0600
Subject: [PATCH 15/29] Config(feat[tmux]): Model phantom col and versions
 (#10)

why: tmux stores s->cx == cols after printing in the rightmost column,
making EL 0, ECH, ICH, and DCH no-ops, preserving wrap across vertical
motions, reporting cols + 1 in CPR, keeping cursor column on IL/DL, and
changing REP right-margin wrapping in tmux 3.9.

what:
- Add Charset, Profile.il_dl_resets_col, Profile.rep_wraps,
  Profile.default_g1_charset, and Profile.tmux(version)
- Honor pending_wrap_phantom_col across EL, ED, ECH, ICH, DCH, LF/IND,
  RI, VPA, DECRC, CPR, and DECXCPR
- Preserve cursor column on IL and DL when il_dl_resets_col is False
---
 src/libvt/__init__.py          |   2 +
 src/libvt/config.py            |  61 +++++++++++---
 src/libvt/terminal.py          | 140 ++++++++++++++++++++++++---------
 tests/test_pr2_review_fixes.py |  64 ++++++++++++++-
 4 files changed, 217 insertions(+), 50 deletions(-)

diff --git a/src/libvt/__init__.py b/src/libvt/__init__.py
index 86b34fe..5d7301b 100644
--- a/src/libvt/__init__.py
+++ b/src/libvt/__init__.py
@@ -33,6 +33,7 @@
     TMUX_CAPTURE_POLICY,
     TMUX_PROFILE,
     XTERM_PROFILE,
+    Charset,
     ColorScheme,
     Limits,
     Policy,
@@ -138,6 +139,7 @@
     "Bell",
     "BlockKind",
     "Cell",
+    "Charset",
     "ClipboardWrite",
     "Color",
     "ColorScheme",
diff --git a/src/libvt/config.py b/src/libvt/config.py
index 2f00bcd..72f0120 100644
--- a/src/libvt/config.py
+++ b/src/libvt/config.py
@@ -3,8 +3,14 @@
 from __future__ import annotations
 
 import enum
+import re
+import typing as t
 from dataclasses import dataclass
 
+type Charset = t.Literal["B", "0", "A"]
+
+_TMUX_VERSION_RE = re.compile(r"^\s*(\d+)\.(\d+)[a-z]?\s*$")
+
 
 class ColorScheme(enum.IntEnum):
     """``CSI ? 997 ; Ps n`` color-scheme values (``DEC ?2031`` / ``DSR ?996n``)."""
@@ -39,8 +45,8 @@ class Profile:
         Default background 8-bit RGB reported for ``OSC 11 ; ?``.
     pending_wrap_phantom_col : bool
         When ``True`` (``TMUX_PROFILE``), ``pending_wrap`` treats the cursor as
-        occupying phantom column ``cols`` on ``CUB`` / ``BS`` and allows ``BS``
-        at column ``0`` to step onto the end of a soft-wrapped predecessor row,
+        occupying phantom column ``cols`` across ``EL``/``ED``, ``ECH``/``ICH``/
+        ``DCH``, vertical motions, ``DECRC``, ``CPR``, and ``CUB`` / ``BS``,
         matching ``tmux``'s ``screen-write.c``.
     vs15_narrows_wide_emoji : bool
         When ``True`` (default), ``U+FE0E`` narrows standalone wide emoji
@@ -64,6 +70,17 @@ class Profile:
         When ``True``, ``HPR`` (``CSI Ps a``) and ``VPR`` (``CSI Ps e``) move
         the cursor relatively; when ``False`` (``TMUX_PROFILE``), both are
         quietly ignored.
+    il_dl_resets_col : bool
+        When ``True`` (ECMA-48 / ``xterm`` / ``Ghostty``), ``IL`` and ``DL``
+        move the cursor to the active left margin; when ``False``
+        (``TMUX_PROFILE``), the cursor column is preserved.
+    rep_wraps : bool
+        When ``True`` (default and ``tmux >= 3.9``), ``REP`` (``CSI Ps b``)
+        autowraps across the right margin; when ``False`` (``tmux <= 3.8``),
+        ``REP`` halts at phantom column ``cols``.
+    default_g1_charset : Charset
+        Initial ``G1`` character-set designation on startup and ``RIS``
+        (``"B"`` US-ASCII by default).
     """
 
     name: str = "libvt"
@@ -83,6 +100,35 @@ class Profile:
     reflow_on_resize: bool = True
     ed3_clears_scrollback_on_alt: bool = False
     hpr_vpr_enabled: bool = True
+    il_dl_resets_col: bool = True
+    rep_wraps: bool = True
+    default_g1_charset: Charset = "B"
+
+    @classmethod
+    def tmux(cls, version: tuple[int, int] | str = "3.8a") -> Profile:
+        """Build a version-specific ``tmux`` compatibility :class:`Profile`."""
+        if isinstance(version, tuple):
+            major, minor = version
+        else:
+            m = _TMUX_VERSION_RE.match(version)
+            if m is None:
+                msg = (
+                    f"invalid tmux version {version!r}; expected e.g. '3.8a' or (3, 8)"
+                )
+                raise ValueError(msg)
+            major, minor = int(m.group(1)), int(m.group(2))
+        at_least_3_9 = (major, minor) >= (3, 9)
+        return cls(
+            name="tmux",
+            osc_7501_capabilities="?",
+            pending_wrap_phantom_col=True,
+            vs15_narrows_wide_emoji=False,
+            tmux_window_rename=True,
+            ed3_clears_scrollback_on_alt=True,
+            hpr_vpr_enabled=False,
+            il_dl_resets_col=False,
+            rep_wraps=at_least_3_9,
+        )
 
 
 DEFAULT_OSC7_HOSTS: frozenset[str] = frozenset({"", "localhost"})
@@ -207,15 +253,7 @@ class Limits:
     reflow_on_resize=False,
     ed3_clears_scrollback_on_alt=True,
 )
-TMUX_PROFILE = Profile(
-    name="tmux",
-    osc_7501_capabilities="?",
-    pending_wrap_phantom_col=True,
-    vs15_narrows_wide_emoji=False,
-    tmux_window_rename=True,
-    ed3_clears_scrollback_on_alt=True,
-    hpr_vpr_enabled=False,
-)
+TMUX_PROFILE = Profile.tmux("3.8a")
 DEFAULT_POLICY = Policy()
 TMUX_CAPTURE_POLICY = Policy(allow_passthrough=True)
 DEFAULT_LIMITS = Limits()
@@ -228,6 +266,7 @@ class Limits:
     "TMUX_CAPTURE_POLICY",
     "TMUX_PROFILE",
     "XTERM_PROFILE",
+    "Charset",
     "ColorScheme",
     "Limits",
     "Policy",
diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py
index af3fae4..2dd5f2a 100644
--- a/src/libvt/terminal.py
+++ b/src/libvt/terminal.py
@@ -791,11 +791,12 @@ def __init__(
         self._pen_word: int = 0
         self._hyperlink: Hyperlink | None = None
         self._cell_ext: _CellExt | None = None
-        self._g_sets: list[str] = ["B", "B", "B", "B"]
+        def_g = ("B", profile.default_g1_charset, "B", "B")
+        self._g_sets: list[str] = list(def_g)
         self._gl: int = 0
         self._single_shift: int | None = None
-        self._saved_primary = _SavedCursor()
-        self._saved_alt = _SavedCursor()
+        self._saved_primary = _SavedCursor(g_sets=def_g)
+        self._saved_alt = _SavedCursor(g_sets=def_g)
         self._last_printed: str = ""
         self._last_printed_pos: tuple[int, int] | None = None
         self._cluster_state: int = CLUSTER_NONE
@@ -1216,7 +1217,8 @@ def reset(self, *, soft: bool = False) -> None:
         self._sync_pen_cache()
         self._last_printed = ""
         self._clear_cluster_anchor()
-        self._g_sets = ["B", "B", "B", "B"]
+        def_g = ("B", self._profile.default_g1_charset, "B", "B")
+        self._g_sets = list(def_g)
         self._gl = 0
         self._single_shift = None
         was_sync = self.synchronized
@@ -1245,8 +1247,8 @@ def reset(self, *, soft: bool = False) -> None:
             self._screens.active_is_alt = False
             self._screens.primary.reset()
             self._screens.alternate.reset()
-            self._saved_primary = _SavedCursor()
-            self._saved_alt = _SavedCursor()
+            self._saved_primary = _SavedCursor(g_sets=def_g)
+            self._saved_alt = _SavedCursor(g_sets=def_g)
             self._title = ""
             self._window_name = ""
             self._fg_rgb = self._profile.fg_rgb
@@ -1391,6 +1393,11 @@ def _linefeed(self, scr: Screen, *, carriage_return: bool = False) -> None:
         self._before_mutate()
         top, bottom, left, right = self._effective_margins(scr)
         col = left if carriage_return else scr._cur_col
+        keep_wrap = (
+            (not carriage_return)
+            and self._profile.pending_wrap_phantom_col
+            and scr._pending_wrap
+        )
         if scr._cur_row == bottom and left <= scr._cur_col <= right:
             bce_word, bce_ext = self._bce_pair()
             scr.scroll_up(
@@ -1407,11 +1414,11 @@ def _linefeed(self, scr: Screen, *, carriage_return: bool = False) -> None:
                 Rect(bottom, left, 1, right - left + 1),
                 EraseCause.SCROLL,
             )
-            self._set_cursor(scr, bottom, col, pending_wrap=False)
+            self._set_cursor(scr, bottom, col, pending_wrap=keep_wrap)
         elif scr._cur_row < scr.rows - 1:
-            self._set_cursor(scr, scr._cur_row + 1, col, pending_wrap=False)
+            self._set_cursor(scr, scr._cur_row + 1, col, pending_wrap=keep_wrap)
         else:
-            self._set_cursor(scr, scr._cur_row, col, pending_wrap=False)
+            self._set_cursor(scr, scr._cur_row, col, pending_wrap=keep_wrap)
 
     def _map_charset(self, text: str) -> str:
         if self._single_shift is not None:
@@ -1878,11 +1885,14 @@ def _restore_cursor(self) -> None:
         self._gl = saved.gl
         self._single_shift = None
         self._modes.set_mode(Mode.DECOM, enabled=saved.decom)
+        restored_wrap = (
+            False if self._profile.pending_wrap_phantom_col else saved.pending_wrap
+        )
         self._set_cursor(
             scr,
             saved.row,
             saved.col,
-            pending_wrap=saved.pending_wrap,
+            pending_wrap=restored_wrap,
         )
 
     def _handle_esc(self, intermediates: bytes, final: int) -> None:
@@ -1902,6 +1912,7 @@ def _handle_esc(self, intermediates: bytes, final: int) -> None:
             elif final == 0x4D:  # ESC M RI
                 self._before_mutate()
                 top, bottom, left, right = self._effective_margins(scr)
+                keep_wrap = self._profile.pending_wrap_phantom_col and scr._pending_wrap
                 if scr._cur_row == top and left <= scr._cur_col <= right:
                     bce_w, bce_e = self._bce_pair()
                     scr.scroll_down(
@@ -1920,7 +1931,10 @@ def _handle_esc(self, intermediates: bytes, final: int) -> None:
                     self._clear_cluster_anchor()
                 elif scr._cur_row > 0:
                     self._set_cursor(
-                        scr, scr._cur_row - 1, scr._cur_col, pending_wrap=False
+                        scr,
+                        scr._cur_row - 1,
+                        scr._cur_col,
+                        pending_wrap=keep_wrap,
                     )
             elif final == 0x4E:  # ESC N SS2 -> G2
                 self._single_shift = 2
@@ -2062,38 +2076,41 @@ def _erase_display(
         cause = EraseCause.DECSED if selective else EraseCause.ED
         c_row = scr._cur_row
         c_col = scr._cur_col
+        phantom = self._profile.pending_wrap_phantom_col and scr._pending_wrap
         if mode == 0:
-            scr.heal_before_edit(c_row, c_col, scr.cols)
-            scr._rows[c_row].clear_range(
-                c_col,
-                scr.cols,
-                bce_w,
-                bce_e,
-                selective=selective,
-            )
-            scr._rows[c_row].wrapped = False
+            if not phantom:
+                scr.heal_before_edit(c_row, c_col, scr.cols)
+                scr._rows[c_row].clear_range(
+                    c_col,
+                    scr.cols,
+                    bce_w,
+                    bce_e,
+                    selective=selective,
+                )
+                scr._rows[c_row].wrapped = False
+                self._notify_erase(Rect(c_row, c_col, 1, scr.cols - c_col), cause)
             for r in range(c_row + 1, scr.rows):
                 scr._rows[r].clear_range(0, scr.cols, bce_w, bce_e, selective=selective)
-            self._notify_erase(Rect(c_row, c_col, 1, scr.cols - c_col), cause)
             if c_row + 1 < scr.rows:
                 self._notify_erase(
                     Rect(c_row + 1, 0, scr.rows - c_row - 1, scr.cols),
                     cause,
                 )
         elif mode == 1:
+            end_c = scr.cols if phantom else c_col + 1
             for r in range(c_row):
                 scr._rows[r].clear_range(0, scr.cols, bce_w, bce_e, selective=selective)
-            scr.heal_before_edit(c_row, 0, c_col + 1)
+            scr.heal_before_edit(c_row, 0, end_c)
             scr._rows[c_row].clear_range(
                 0,
-                c_col + 1,
+                end_c,
                 bce_w,
                 bce_e,
                 selective=selective,
             )
             if c_row > 0:
                 self._notify_erase(Rect(0, 0, c_row, scr.cols), cause)
-            self._notify_erase(Rect(c_row, 0, 1, c_col + 1), cause)
+            self._notify_erase(Rect(c_row, 0, 1, end_c), cause)
         elif mode == 2:
             for r in range(scr.rows):
                 scr._rows[r].clear_range(0, scr.cols, bce_w, bce_e, selective=selective)
@@ -2105,7 +2122,7 @@ def _erase_display(
                 for r in range(scr.rows):
                     scr._rows[r].clear_range(0, scr.cols, bce_w, bce_e)
             self._notify_erase(Rect(0, 0, scr.rows, scr.cols), cause)
-        self._set_cursor(scr, c_row, c_col, pending_wrap=False)
+        self._set_cursor(scr, c_row, c_col, pending_wrap=phantom)
 
     def _erase_line(
         self,
@@ -2116,6 +2133,9 @@ def _erase_line(
     ) -> None:
         if mode not in (0, 1, 2):
             return
+        phantom = self._profile.pending_wrap_phantom_col and scr._pending_wrap
+        if mode == 0 and phantom:
+            return
         self._before_mutate()
         bce_w, bce_e = self._bce_pair()
         cause = EraseCause.DECSEL if selective else EraseCause.EL
@@ -2133,17 +2153,18 @@ def _erase_line(
             scr._rows[c_row].wrapped = False
             self._notify_erase(Rect(c_row, c_col, 1, scr.cols - c_col), cause)
         elif mode == 1:
-            scr.heal_before_edit(c_row, 0, c_col + 1)
+            end_c = scr.cols if phantom else c_col + 1
+            scr.heal_before_edit(c_row, 0, end_c)
             scr._rows[c_row].clear_range(
                 0,
-                c_col + 1,
+                end_c,
                 bce_w,
                 bce_e,
                 selective=selective,
             )
-            if c_col + 1 >= scr.cols:
+            if end_c >= scr.cols:
                 scr._rows[c_row].wrapped = False
-            self._notify_erase(Rect(c_row, 0, 1, c_col + 1), cause)
+            self._notify_erase(Rect(c_row, 0, 1, end_c), cause)
         elif mode == 2:
             scr.heal_before_edit(c_row, 0, scr.cols)
             scr._rows[c_row].clear_range(
@@ -2154,7 +2175,7 @@ def _erase_line(
                 selective=selective,
             )
             self._notify_erase(Rect(c_row, 0, 1, scr.cols), cause)
-        self._set_cursor(scr, c_row, c_col, pending_wrap=False)
+        self._set_cursor(scr, c_row, c_col, pending_wrap=phantom)
 
     def _handle_csi(
         self,
@@ -2266,15 +2287,22 @@ def _handle_csi(
             elif final == ord("n"):  # Private DSR (?6n DECXCPR, ?996n color scheme)
                 ps = params.raw_or_default(0, 0)
                 if ps == 6:
+                    phantom_extra = (
+                        1
+                        if (
+                            self._profile.pending_wrap_phantom_col and scr._pending_wrap
+                        )
+                        else 0
+                    )
                     r_out = (
                         (scr._cur_row - top + 1)
                         if self._modes.is_set(Mode.DECOM)
                         else (scr._cur_row + 1)
                     )
                     c_out = (
-                        (scr._cur_col - left + 1)
+                        (scr._cur_col - left + 1 + phantom_extra)
                         if self._modes.is_set(Mode.DECOM)
-                        else (scr._cur_col + 1)
+                        else (scr._cur_col + 1 + phantom_extra)
                     )
                     self._emit_reply(f"\x1b[?{r_out};{c_out}R".encode("ascii"))
                 elif ps == 996 and self._policy.allow_color_queries:
@@ -2366,7 +2394,8 @@ def _handle_csi(
                 target_r = min(bottom, top + row_1 - 1)
             else:
                 target_r = min(scr.rows - 1, row_1 - 1)
-            self._set_cursor(scr, max(0, target_r), c_col)
+            keep_wrap = self._profile.pending_wrap_phantom_col and scr._pending_wrap
+            self._set_cursor(scr, max(0, target_r), c_col, pending_wrap=keep_wrap)
         elif ch_final == "e":  # VPR
             if not self._profile.hpr_vpr_enabled:
                 return
@@ -2388,6 +2417,8 @@ def _handle_csi(
         elif ch_final == "K":  # EL
             self._erase_line(scr, params.raw_or_default(0, 0), selective=False)
         elif ch_final == "X":  # ECH
+            if self._profile.pending_wrap_phantom_col and scr._pending_wrap:
+                return
             self._before_mutate()
             n = min(scr.cols - c_col, params.get(0, 1))
             bce_w, bce_e = self._bce_pair()
@@ -2398,6 +2429,8 @@ def _handle_csi(
             self._notify_erase(Rect(c_row, c_col, 1, n), EraseCause.ECH)
             self._set_cursor(scr, c_row, c_col, pending_wrap=False)
         elif ch_final == "@":  # ICH
+            if self._profile.pending_wrap_phantom_col and scr._pending_wrap:
+                return
             self._before_mutate()
             n = params.get(0, 1)
             bce_w, bce_e = self._bce_pair()
@@ -2412,6 +2445,8 @@ def _handle_csi(
             )
             self._set_cursor(scr, c_row, c_col, pending_wrap=False)
         elif ch_final == "P":  # DCH
+            if self._profile.pending_wrap_phantom_col and scr._pending_wrap:
+                return
             self._before_mutate()
             n = params.get(0, 1)
             bce_w, bce_e = self._bce_pair()
@@ -2434,6 +2469,11 @@ def _handle_csi(
                 self._before_mutate()
                 n = params.get(0, 1)
                 bce_w, bce_e = self._bce_pair()
+                keep_wrap = (
+                    not self._profile.il_dl_resets_col
+                    and self._profile.pending_wrap_phantom_col
+                    and scr._pending_wrap
+                )
                 scr.scroll_down(
                     n,
                     top=c_row,
@@ -2447,12 +2487,18 @@ def _handle_csi(
                     Rect(c_row, left, min(n, bottom - c_row + 1), right - left + 1),
                     EraseCause.SCROLL,
                 )
-                self._set_cursor(scr, c_row, left)
+                target_col = left if self._profile.il_dl_resets_col else c_col
+                self._set_cursor(scr, c_row, target_col, pending_wrap=keep_wrap)
         elif ch_final == "M":  # DL
             if top <= c_row <= bottom and left <= c_col <= right:
                 self._before_mutate()
                 n = params.get(0, 1)
                 bce_w, bce_e = self._bce_pair()
+                keep_wrap = (
+                    not self._profile.il_dl_resets_col
+                    and self._profile.pending_wrap_phantom_col
+                    and scr._pending_wrap
+                )
                 scr.scroll_up(
                     n,
                     top=c_row,
@@ -2472,7 +2518,8 @@ def _handle_csi(
                     ),
                     EraseCause.SCROLL,
                 )
-                self._set_cursor(scr, c_row, left)
+                target_col = left if self._profile.il_dl_resets_col else c_col
+                self._set_cursor(scr, c_row, target_col, pending_wrap=keep_wrap)
         elif ch_final == "S":  # SU
             self._before_mutate()
             n = params.get(0, 1)
@@ -2518,7 +2565,19 @@ def _handle_csi(
         elif ch_final == "b":  # REP
             if prev_printed:
                 count = min(self._limits.max_rep_count, params.get(0, 1))
-                self._handle_print(prev_printed * count)
+                if not self._profile.rep_wraps and self._modes.is_set(Mode.DECAWM):
+                    if scr._pending_wrap and self._profile.pending_wrap_phantom_col:
+                        self._last_printed = prev_printed
+                    else:
+                        w = max(1, char_width(prev_printed[0]))
+                        max_c = right if c_col <= right else scr.cols - 1
+                        avail_cols = max_c - c_col + 1
+                        fit = max(0, avail_cols // w)
+                        if fit > 0:
+                            self._handle_print(prev_printed * min(count, fit))
+                        self._last_printed = prev_printed
+                else:
+                    self._handle_print(prev_printed * count)
         elif ch_final == "r":  # DECSTBM
             t_arg = params.get(0, 1) - 1
             b_arg = params.get(1, scr.rows) - 1
@@ -2577,13 +2636,18 @@ def _handle_csi(
             if ps == 5:
                 self._emit_reply(b"\x1b[0n")
             elif ps == 6:
+                phantom_extra = (
+                    1
+                    if (self._profile.pending_wrap_phantom_col and scr._pending_wrap)
+                    else 0
+                )
                 r_out = (
                     (c_row - top + 1) if self._modes.is_set(Mode.DECOM) else (c_row + 1)
                 )
                 c_out = (
-                    (c_col - left + 1)
+                    (c_col - left + 1 + phantom_extra)
                     if self._modes.is_set(Mode.DECOM)
-                    else (c_col + 1)
+                    else (c_col + 1 + phantom_extra)
                 )
                 self._emit_reply(f"\x1b[{r_out};{c_out}R".encode("ascii"))
         elif ch_final == "t":  # XTWINOPS
diff --git a/tests/test_pr2_review_fixes.py b/tests/test_pr2_review_fixes.py
index 59d29af..ef0e871 100644
--- a/tests/test_pr2_review_fixes.py
+++ b/tests/test_pr2_review_fixes.py
@@ -9,7 +9,7 @@
 
 import libvt
 from libvt.aio import AsyncTerminalStream
-from libvt.config import DEFAULT_PROFILE, TMUX_PROFILE, XTERM_PROFILE, Policy
+from libvt.config import DEFAULT_PROFILE, TMUX_PROFILE, XTERM_PROFILE, Policy, Profile
 from libvt.events import ScreenErased
 from libvt.exc import TerminalTimeoutError
 from libvt.modes import Mode
@@ -300,3 +300,65 @@ async def test_formatter_vt_bce_roundtrip_html_palette_and_timeout_diagnostics()
     assert err.parser_state == ParserState.OSC_STRING
     assert b"\x1b]0;stuck" in err.recent_bytes
     assert "Flight Recorder:" in str(err)
+
+
+def test_tmux_phantom_column_il_dl_and_version_factory() -> None:
+    """``TMUX_PROFILE`` models phantom col ``cols``, ``IL``/``DL``, and versions."""
+    # Reverse-video header + EL 0 at phantom column preserves col 4 glyph and style!
+    tm = libvt.Terminal(rows=3, cols=5, profile=TMUX_PROFILE)
+    tm.feed(b"\x1b[7mHEAD!\x1b[K\x1b[0m")
+    assert tm[0].text == "HEAD!"
+    assert tm[0, 4].style.reverse is True
+    assert tm.cursor.pending_wrap is True
+
+    # ED 0 at phantom column keeps current row, clears below, and keeps pending_wrap.
+    tm.reset()
+    tm.feed(b"12345\r\nrow-2\x1b[1;1H12345\x1b[J")
+    assert tm.lines == ("12345", "", "")
+    assert tm.cursor.pending_wrap is True
+
+    # ECH, ICH, DCH at phantom column are no-ops keeping pending_wrap.
+    for seq in (b"\x1b[X", b"\x1b[@", b"\x1b[P"):
+        tm.reset()
+        tm.feed(b"12345" + seq)
+        assert tm[0].text == "12345"
+        assert tm.cursor.pending_wrap is True
+
+    # LF (LNM off), IND, RI, and VPA preserve pending_wrap under TMUX_PROFILE.
+    tm.reset()
+    tm.feed(b"12345\nX")
+    assert tm.lines == ("12345", "", "X")
+
+    tm.reset()
+    tm.feed(b"\x1b[2;1H12345\x1bMX")
+    assert tm.lines == ("", "X2345", "")
+
+    tm.reset()
+    tm.feed(b"12345\x1b[2dX")
+    assert tm.lines == ("12345", "", "X")
+
+    # DECRC drops pending_wrap under TMUX_PROFILE, clamping to cols - 1.
+    tm.reset()
+    tm.feed(b"12345\x1b7\x1b8X")
+    assert tm[0].text == "1234X"
+
+    # CPR (CSI 6 n) reports cols + 1 at phantom column under TMUX_PROFILE.
+    tm.reset()
+    tm.feed(b"12345\x1b[6n")
+    assert tm.drain_replies() == b"\x1b[1;6R"
+
+    # IL and DL preserve cursor column under TMUX_PROFILE (unlike DEFAULT_PROFILE).
+    tm.reset()
+    tm.feed(b"abcde\r\n12345\x1b[2;4H\x1b[L")
+    assert tm.cursor.col == 3
+    tm.feed(b"\x1b[M")
+    assert tm.cursor.col == 3
+
+    # Profile.tmux("3.8a") vs Profile.tmux("3.9") versioned quirks.
+    tm38 = libvt.Terminal(rows=2, cols=5, profile=Profile.tmux("3.8a"))
+    tm38.feed(b"1234X\x1b[2b")
+    assert tm38.lines == ("1234X", "")
+
+    tm39 = libvt.Terminal(rows=2, cols=5, profile=Profile.tmux("3.9"))
+    tm39.feed(b"1234X\x1b[2b")
+    assert tm39.lines == ("1234X", "XX")

From 6eee7b3b3f54ad777dbba6eeaacdcd557fb9059c Mon Sep 17 00:00:00 2001
From: Tony Narlock 
Date: Sun, 22 Nov 2026 08:37:58 -0600
Subject: [PATCH 16/29] Parser(feat[scan]): Add regex and BMP fast paths (#11)

why: Byte-by-byte Python loops across OSC, DCS, and APC payloads and
narrow non-ASCII UTF-8 spans dominated feed() and feed_until() CPU time,
and spacing GCB_PREPEND codepoints split across chunks bypassed UAX #29
clustering when followed by ASCII.

what:
- Scan OSC, DCS, APC, and Latin-1 GROUND payloads with compiled C regex
  patterns in Parser.feed_to and Terminal.feed_until
- Guard the slice print path on active GCB_PREPEND cluster state and
  extend it to single-width non-combining Latin, Greek, Cyrillic,
  box-drawing, and block-element BMP runs
- Sync CHANGES for HPR/VPR, Profile.tmux(), and TerminalTimeoutError
---
 CHANGES                        | 26 +++++++------
 src/libvt/parser.py            | 68 ++++++++++++++++------------------
 src/libvt/terminal.py          | 42 ++++++++++++++-------
 tests/test_pr2_review_fixes.py | 40 +++++++++++++++++++-
 4 files changed, 113 insertions(+), 63 deletions(-)

diff --git a/CHANGES b/CHANGES
index b12481d..35089b2 100644
--- a/CHANGES
+++ b/CHANGES
@@ -23,14 +23,14 @@ subcommands.
 {class}`~libvt.parser.Parser` decodes incremental UTF-8, colon-delimited
 ITU T.416 SGR subparameters (`4:3`, `38:2::R:G:B`, `58:5:idx`), `G0`–`G3`
 character-set designations (`ESC ( 0` DEC Special Graphics, `SO`/`SI`,
-`SS2`/`SS3`), `CBT`/`CHT`, `DECSCA`/`DECSED`/`DECSEL`, `CSI 22 J`, and
-`DCS tmux;` passthrough framing while isolating UTF-8 `0x9C` and `U+009B`
-bytes from 8-bit `C1` controls (with optional `encoding="latin-1"` 8-bit
-wire mode). SHA-256-pinned Unicode 17.0.0 two-stage tables drive East
-Asian width and DEC `?2027` UAX #29 grapheme clustering across ZWJ
-emoji, Regional Indicator flag pairs, Indic conjuncts, Hangul jamo, and
-`VS15` / `VS16` emoji variation sequences. See {doc}`topics/architecture`
-for details.
+`SS2`/`SS3`), `HPR`/`VPR` (`CSI a` / `CSI e`), `CBT`/`CHT`,
+`DECSCA`/`DECSED`/`DECSEL`, `CSI 3 J` / `CSI 22 J`, and `DCS tmux;`
+passthrough framing while isolating UTF-8 `0x9C` and `U+009B` bytes from
+8-bit `C1` controls (with optional `encoding="latin-1"` 8-bit wire mode).
+SHA-256-pinned Unicode 17.0.0 two-stage tables drive East Asian width and
+DEC `?2027` UAX #29 grapheme clustering across ZWJ emoji, Regional
+Indicator flag pairs, Indic conjuncts, Hangul jamo, and `VS15` / `VS16`
+emoji variation sequences. See {doc}`topics/architecture` for details.
 
 #### Synchronized output stepping, Rex `OSC 7501`, and host queries (#2)
 
@@ -52,8 +52,9 @@ validation, profile- and policy-gated `OSC 7501 ; ?` capability replies,
 `OSC 10`/`11` and `OSC 110`/`111` dynamic colors, `tmux` `ESC k` window
 renames ({class}`~libvt.events.WindowRenamed`), `DA1`/`DA2`, `DSR`,
 `DECRQM`, `DECRQSS`, `XTVERSION`, `XTGETTCAP`, and `?2031`/`?996n`
-color-scheme queries. Configuration splits cleanly across
-{class}`~libvt.config.Profile`, {class}`~libvt.config.Policy`, and
+color-scheme queries. Configuration splits cleanly across {class}`~libvt.config.Profile`
+(including versioned {meth}`~libvt.config.Profile.tmux` phantom-column
+and resize compatibility profiles), {class}`~libvt.config.Policy`, and
 {class}`~libvt.config.Limits`. See {doc}`topics/protocols-and-input` for
 details.
 
@@ -72,8 +73,9 @@ pseudo-terminals (`TIOCSCTTY` and `tty_mode`) without importing `asyncio`
 or `pty` on `import libvt`. The `pytest11` plugin provides
 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`, and
-{class}`~libvt.terminal.FlightRecorder` diagnostics. See
+{func}`~libvt.testing.assert_screen_box`,
+{exc}`~libvt.exc.TerminalTimeoutError` stream diagnostics, and
+{class}`~libvt.terminal.FlightRecorder` ring buffers. See
 {doc}`topics/sync-and-asyncio` for details.
 
 ### Documentation
diff --git a/src/libvt/parser.py b/src/libvt/parser.py
index 6cbd94f..2ff2d81 100644
--- a/src/libvt/parser.py
+++ b/src/libvt/parser.py
@@ -30,8 +30,15 @@
 _PARAM_CLAMP = 65_535
 _MEMO_LIMIT = 256
 _CTRL_RE = re.compile(rb"[\x00-\x1f\x7f]")
+_LATIN1_PRINT_RE = re.compile(rb"[\x20-\x7e\xa0-\xff]+")
 _CSI_FAST_RE = re.compile(rb"([\x3c-\x3f]?)([0-9;:]{0,256})([\x40-\x7e])")
 _C1_CHAR_RE = re.compile(r"[\x80-\x9f]")
+_OSC_STOP_RE = re.compile(rb"[\x07\x18\x1a\x1b]")
+_OSC_STOP_LATIN1_RE = re.compile(rb"[\x07\x18\x1a\x1b\x80-\x9f]")
+_DCS_STOP_RE = re.compile(rb"[\x18\x1a\x1b\x7f]")
+_DCS_STOP_LATIN1_RE = re.compile(rb"[\x18\x1a\x1b\x7f\x80-\x9f]")
+_APC_STOP_RE = re.compile(rb"[\x18\x1a\x1b]")
+_APC_STOP_LATIN1_RE = re.compile(rb"[\x18\x1a\x1b\x80-\x9f]")
 
 type ParserEncoding = t.Literal["utf-8", "latin-1"]
 
@@ -817,10 +824,9 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None:
 
             if state == ParserState.GROUND:
                 if latin1:
-                    end = pos
-                    while end < n and (0x20 <= mv[end] <= 0x7E or mv[end] >= 0xA0):
-                        end += 1
-                    if end > pos:
+                    lat_m = _LATIN1_PRINT_RE.match(mv, pos)
+                    if lat_m is not None:
+                        end = lat_m.end()
                         sink.on_print(bytes(mv[pos:end]).decode("latin-1"))
                         pos = end
                         if pos >= n:
@@ -876,22 +882,18 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None:
                 continue
 
             if state == ParserState.OSC_STRING:
-                start = pos
-                while pos < n:
-                    b_scan = mv[pos]
-                    if b_scan in (0x07, 0x18, 0x1A, 0x1B) or (
-                        latin1 and 0x80 <= b_scan <= 0x9F
-                    ):
-                        break
-                    pos += 1
-                if pos > start and not self._str_overflow:
-                    chunk_len = pos - start
+                stop_re = _OSC_STOP_LATIN1_RE if latin1 else _OSC_STOP_RE
+                osc_m = stop_re.search(mv, pos)
+                end = osc_m.start() if osc_m is not None else n
+                if end > pos and not self._str_overflow:
+                    chunk_len = end - pos
                     if len(self._str_buf) + chunk_len <= max_osc:
-                        self._str_buf.extend(mv[start:pos])
+                        self._str_buf.extend(mv[pos:end])
                     else:
                         self._str_buf.clear()
                         self._str_overflow = True
                         self._notify_overflow(sink, "osc", max_osc)
+                pos = end
                 if pos >= n:
                     break
                 b = mv[pos]
@@ -913,18 +915,13 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None:
                 continue
 
             if state == ParserState.DCS_PASSTHROUGH:
-                start = pos
-                while pos < n:
-                    b_scan = mv[pos]
-                    if b_scan in (0x18, 0x1A, 0x1B, 0x7F) or (
-                        latin1 and 0x80 <= b_scan <= 0x9F
-                    ):
-                        break
-                    pos += 1
-                if pos > start and not self._str_overflow:
-                    chunk_len = pos - start
+                stop_re = _DCS_STOP_LATIN1_RE if latin1 else _DCS_STOP_RE
+                dcs_m = stop_re.search(mv, pos)
+                end = dcs_m.start() if dcs_m is not None else n
+                if end > pos and not self._str_overflow:
+                    chunk_len = end - pos
                     if len(self._str_buf) + chunk_len <= max_dcs:
-                        self._str_buf.extend(mv[start:pos])
+                        self._str_buf.extend(mv[pos:end])
                         if self._tmux_dcs_state == 1 and len(self._str_buf) >= 4:
                             self._tmux_dcs_state = (
                                 2 if self._str_buf[:4] == b"mux;" else -1
@@ -933,6 +930,7 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None:
                         self._str_buf.clear()
                         self._str_overflow = True
                         self._notify_overflow(sink, "dcs", max_dcs)
+                pos = end
                 if pos >= n:
                     break
                 b = mv[pos]
@@ -953,28 +951,24 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None:
                 continue
 
             if state == ParserState.SOS_PM_APC_STRING:
-                start = pos
-                while pos < n:
-                    b_scan = mv[pos]
-                    if b_scan in (0x18, 0x1A, 0x1B) or (
-                        latin1 and 0x80 <= b_scan <= 0x9F
-                    ):
-                        break
-                    pos += 1
+                stop_re = _APC_STOP_LATIN1_RE if latin1 else _APC_STOP_RE
+                apc_m = stop_re.search(mv, pos)
+                end = apc_m.start() if apc_m is not None else n
                 if (
-                    pos > start
+                    end > pos
                     and self._str_kind in (0x5F, 0x6B)
                     and not self._str_overflow
                 ):
-                    chunk_len = pos - start
+                    chunk_len = end - pos
                     cap = max_apc if self._str_kind == 0x5F else max_osc
                     if len(self._str_buf) + chunk_len <= cap:
-                        self._str_buf.extend(mv[start:pos])
+                        self._str_buf.extend(mv[pos:end])
                     else:
                         self._str_buf.clear()
                         self._str_overflow = True
                         kind_name = "apc" if self._str_kind == 0x5F else "esc"
                         self._notify_overflow(sink, kind_name, cap)
+                pos = end
                 if pos >= n:
                     break
                 b = mv[pos]
diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py
index 2dd5f2a..6a66582 100644
--- a/src/libvt/terminal.py
+++ b/src/libvt/terminal.py
@@ -9,6 +9,7 @@
 import enum
 import html
 import os
+import re
 import typing as t
 import urllib.parse
 from dataclasses import dataclass
@@ -140,6 +141,13 @@
 _UK_CHARSET = str.maketrans({"#": "£"})
 
 _SAFE_URI_PREFIXES = ("https://", "http://", "mailto:")
+_PRINT_ASCII_RE = re.compile(rb"[\x20-\x7e]+")
+_STR_BODY_UTF8_RE = re.compile(rb"[^\x07\x18\x1a\x1b\x7f]+")
+_STR_BODY_LATIN1_RE = re.compile(rb"[^\x07\x18\x1a\x1b\x7f\x80-\x9f]+")
+# BMP blocks where every codepoint has width 1, GCB_OTHER, and INCB_NONE.
+_SAFE_NARROW_BMP_RE = re.compile(
+    r"[\x20-\x7e\xa0-\xa8\xaa-\xac\xaf-\u02ff\u0391-\u03a1\u03a3-\u03ff\u0400-\u0482\u2500-\u259f]+",
+)
 
 
 class StopOn(enum.IntFlag):
@@ -1315,10 +1323,9 @@ def feed_until(
                 and not self._parser.utf8_pending
                 and not (stop & StopOn.GROUND)
             ):
-                end = idx
-                while end < n and 0x20 <= mv[end] < 0x7F:
-                    end += 1
-                if end > idx:
+                ascii_m = _PRINT_ASCII_RE.match(mv, idx)
+                if ascii_m is not None:
+                    end = ascii_m.end()
                     span = mv[idx:end]
                     if self._recorder is not None:
                         self._recorder.record(span)
@@ -1327,16 +1334,20 @@ def feed_until(
                     self._generation += 1
                     continue
 
-            # Bulk-advance interior payload bytes inside OSC / DCS / APC strings!
+            # Bulk-advance interior payload bytes inside OSC / DCS / APC strings.
             if state in (
                 ParserState.OSC_STRING,
                 ParserState.DCS_PASSTHROUGH,
                 ParserState.SOS_PM_APC_STRING,
             ):
-                end = idx
-                while end < n and mv[end] not in (0x07, 0x18, 0x1A, 0x1B, 0x9C):
-                    end += 1
-                if end > idx:
+                body_re = (
+                    _STR_BODY_LATIN1_RE
+                    if self._encoding == "latin-1"
+                    else _STR_BODY_UTF8_RE
+                )
+                body_m = body_re.match(mv, idx)
+                if body_m is not None:
+                    end = body_m.end()
                     span = mv[idx:end]
                     if self._recorder is not None:
                         self._recorder.record(span)
@@ -1452,8 +1463,14 @@ def _handle_print(self, text: str) -> None:
         insert_mode = self._modes.is_set(Mode.IRM)
         _, bottom, left, right = self._effective_margins(scr)
 
-        if text.isascii() and not insert_mode and not self._pending_prepend:
-            mode_2027_ascii = self._modes.is_set(Mode.GRAPHEME_CLUSTERING)
+        mode_2027 = self._modes.is_set(Mode.GRAPHEME_CLUSTERING)
+        can_slice = (
+            not insert_mode
+            and not self._pending_prepend
+            and (not mode_2027 or ((self._cluster_state >> 1) & 0x0F) != GCB_PREPEND)
+            and (text.isascii() or _SAFE_NARROW_BMP_RE.fullmatch(text) is not None)
+        )
+        if can_slice:
             pos = 0
             total = len(text)
             while pos < total:
@@ -1501,12 +1518,11 @@ def _handle_print(self, text: str) -> None:
                 self._last_printed_pos = (scr._cur_row, end_col)
                 self._cluster_state = init_cluster_state(
                     ord(seg[-1]),
-                    mode_2027=mode_2027_ascii,
+                    mode_2027=mode_2027,
                 )
                 self._cluster_len = 1
             return
 
-        mode_2027 = self._modes.is_set(Mode.GRAPHEME_CLUSTERING)
         vs15_narrows = self._profile.vs15_narrows_wide_emoji
         vs16_wide = self._profile.vs16_always_wide
         max_cluster = self._limits.max_grapheme_codepoints
diff --git a/tests/test_pr2_review_fixes.py b/tests/test_pr2_review_fixes.py
index ef0e871..ef30335 100644
--- a/tests/test_pr2_review_fixes.py
+++ b/tests/test_pr2_review_fixes.py
@@ -15,7 +15,7 @@
 from libvt.modes import Mode
 from libvt.parser import ParserState
 from libvt.style import AnsiColor
-from libvt.terminal import OutputFormat
+from libvt.terminal import OutputFormat, StopOn
 
 
 def test_resize_preserves_pending_wrap_and_wide_glyphs() -> None:
@@ -362,3 +362,41 @@ def test_tmux_phantom_column_il_dl_and_version_factory() -> None:
     tm39 = libvt.Terminal(rows=2, cols=5, profile=Profile.tmux("3.9"))
     tm39.feed(b"1234X\x1b[2b")
     assert tm39.lines == ("1234X", "XX")
+
+
+def test_parser_c_regex_dcs_del_bel_latin1_feed_until_and_narrow_bmp() -> None:
+    """Parser C-regex scans, ``latin-1`` ``feed_until``, and narrow BMP match."""
+    # DCS ignores 0x7F (DEL) while preserving 0x07 (BEL) inside DCS tmux; passthrough.
+    term = libvt.Terminal(
+        rows=2,
+        cols=16,
+        policy=Policy(allow_passthrough=True),
+    )
+    term.feed(b"\x1bPt\x7fmux;\x1b\x1b]2;ok-title\x07\x1b\\")
+    assert term.title == "ok-title"
+
+    # encoding='latin-1' feed_until handles 8-bit C1 0x9B aborting OSC_STRING!
+    lat_t = libvt.Terminal(rows=2, cols=10, encoding="latin-1")
+    step = lat_t.feed_until(
+        b"\x9d2;unterminated\x9b?2026hHI\x9b?2026ltrailing",
+        stop=StopOn.SYNC_END,
+    )
+    assert step.stopped_on == StopOn.SYNC_END
+    assert lat_t[0].text == "HI"
+
+    # Spacing GCB_PREPEND (U+0600) split across feed() before ASCII '1' matches atomic.
+    whole = libvt.Terminal(rows=2, cols=8)
+    whole.feed("\u06001".encode())
+    split = libvt.Terminal(rows=2, cols=8)
+    split.feed("\u0600".encode())
+    split.feed(b"1")
+    assert split[0, 0].text == whole[0, 0].text
+    assert split.cursor == whole.cursor
+
+    # Curated narrow-BMP slice fast path preserves widths, wraps, styles, and REP.
+    bmp = libvt.Terminal(rows=3, cols=8)
+    bmp.feed("\x1b[32mcafé\x1b[2b ─│┌┐".encode())
+    assert bmp[0].text == "cafééé ─"
+    assert bmp[0].wrapped is True
+    assert bmp[1].text == "│┌┐"
+    assert bmp[0, 3].style.fg == AnsiColor.GREEN

From 182759702ef055b68929a722e940a51aa9627fbb Mon Sep 17 00:00:00 2001
From: Tony Narlock 
Date: Sun, 22 Nov 2026 14:13:57 -0600
Subject: [PATCH 17/29] exc(fix[timeout]): Put diagnostics in notes (#15)

why: Multi-line viewport and flight-recorder dumps in args[0] bloat log
lines, while a 2-tuple __reduce__ drops PEP 678 __notes__ and breaks
subclasses with custom constructors or __slots__.

what:
- Keep str(TerminalTimeoutError) single-line and attach diagnostics via
  add_note() when attach_note=True
- Reconstruct via OSError.__new__ and OSError.__init__ while preserving
  subclass __slots__, __dict__, and copied __notes__
- Add format_diagnostics() and wire attach_note through wait_for()
---
 src/libvt/aio.py               | 152 +++++++++++++++++++++++++-----
 src/libvt/exc.py               | 165 +++++++++++++++++++++++++--------
 tests/test_pr2_review_fixes.py |   4 +-
 3 files changed, 260 insertions(+), 61 deletions(-)

diff --git a/src/libvt/aio.py b/src/libvt/aio.py
index 40f1aec..997a2f7 100644
--- a/src/libvt/aio.py
+++ b/src/libvt/aio.py
@@ -117,6 +117,7 @@ def _make_timeout_error(
     header: str,
     *,
     eof: bool,
+    attach_note: bool = True,
 ) -> TerminalTimeoutError:
     from libvt.testing import format_flight_recorder, format_screen_box
 
@@ -124,13 +125,14 @@ def _make_timeout_error(
     recent = rec.tail(256) if rec is not None else b""
     box = format_screen_box(snap, rows=min(snap.rows, 12), cols=min(snap.cols, 80))
     diag = format_flight_recorder(terminal)
-    full_msg = f"{header}\n{box}\n{diag}"
     return TerminalTimeoutError(
-        full_msg,
+        header,
         parser_state=terminal.parser_state,
         screen_text=snap.text,
         recent_bytes=recent,
         eof=eof,
+        diagnostics=f"{box}\n{diag}",
+        attach_note=attach_note,
     )
 
 
@@ -267,8 +269,33 @@ async def wait_for(
         predicate: collections.abc.Callable[[Snapshot], bool] | str,
         *,
         timeout: float = 2.0,
+        attach_note: bool = True,
     ) -> Snapshot:
-        """Wait until *predicate* matches the committed :class:`Snapshot`."""
+        """Wait until *predicate* matches the committed :class:`Snapshot`.
+
+        Parameters
+        ----------
+        predicate : collections.abc.Callable[[Snapshot], bool] | str
+            Callable tested against each committed snapshot, or a substring
+            searched inside ``snapshot.text``.
+        timeout : float
+            Maximum wait duration in seconds before raising
+            :exc:`~libvt.exc.TerminalTimeoutError`.
+        attach_note : bool
+            When ``True`` (default), attach multi-line screen and flight
+            recorder diagnostics via PEP 678 ``__notes__``.
+
+        Returns
+        -------
+        Snapshot
+            First matching :class:`~libvt.terminal.Snapshot`.
+
+        Raises
+        ------
+        TerminalTimeoutError
+            If the stream reaches EOF before matching (``eof=True``) or
+            *timeout* expires (``eof=False``).
+        """
         check = (
             (lambda snap: predicate in snap.text)
             if isinstance(predicate, str)
@@ -276,14 +303,13 @@ async def wait_for(
         )
         deadline = time.monotonic() + timeout
         while True:
-            if (
-                self._task is not None
-                and self._task.done()
-                and not self._task.cancelled()
-            ):
-                task_exc = self._task.exception()
-                if task_exc is not None:
-                    raise task_exc
+            if self._task is not None and self._task.done():
+                if self._task.cancelled():
+                    self._task = None
+                else:
+                    task_exc = self._task.exception()
+                    if task_exc is not None:
+                        raise task_exc
             now = time.monotonic()
             if self.terminal.synchronized:
                 self._update_sync_timer(now)
@@ -296,6 +322,7 @@ async def wait_for(
                     snap,
                     "stream reached EOF before predicate matched",
                     eof=True,
+                    attach_note=attach_note,
                 )
             remaining = deadline - now
             if remaining <= 0:
@@ -307,13 +334,18 @@ async def wait_for(
                     live,
                     f"timed out after {timeout:.2f}s waiting for terminal state",
                     eof=False,
+                    attach_note=attach_note,
                 )
             self._frame_event.clear()
-            wait_slice = (
-                min(remaining, self.sync_timeout)
-                if self.terminal.synchronized
-                else remaining
-            )
+            if self.terminal.synchronized:
+                sync_rem = (
+                    self.sync_timeout
+                    if self._sync_started_at is None
+                    else max(0.0, self._sync_started_at + self.sync_timeout - now)
+                )
+                wait_slice = min(remaining, sync_rem)
+            else:
+                wait_slice = remaining
             if self._task is None:
                 with contextlib.suppress(TimeoutError):
                     await asyncio.wait_for(self.pump_once(), timeout=wait_slice)
@@ -448,8 +480,33 @@ async def wait_for(
         predicate: collections.abc.Callable[[Snapshot], bool] | str,
         *,
         timeout: float = 2.0,
+        attach_note: bool = True,
     ) -> Snapshot:
-        """Wait until *predicate* matches the committed :class:`Snapshot`."""
+        """Wait until *predicate* matches the committed :class:`Snapshot`.
+
+        Parameters
+        ----------
+        predicate : collections.abc.Callable[[Snapshot], bool] | str
+            Callable tested against each committed snapshot, or a substring
+            searched inside ``snapshot.text``.
+        timeout : float
+            Maximum wait duration in seconds before raising
+            :exc:`~libvt.exc.TerminalTimeoutError`.
+        attach_note : bool
+            When ``True`` (default), attach multi-line screen and flight
+            recorder diagnostics via PEP 678 ``__notes__``.
+
+        Returns
+        -------
+        Snapshot
+            First matching :class:`~libvt.terminal.Snapshot`.
+
+        Raises
+        ------
+        TerminalTimeoutError
+            If the PTY reaches EOF before matching (``eof=True``) or *timeout*
+            expires (``eof=False``).
+        """
         check = (
             (lambda snap: predicate in snap.text)
             if isinstance(predicate, str)
@@ -475,6 +532,7 @@ async def wait_for(
                     snap,
                     "PTY reached EOF before predicate matched",
                     eof=True,
+                    attach_note=attach_note,
                 )
             remaining = deadline - now
             if remaining <= 0:
@@ -486,13 +544,18 @@ async def wait_for(
                     live,
                     f"timed out after {timeout:.2f}s waiting for PTY state",
                     eof=False,
+                    attach_note=attach_note,
                 )
             self._frame_event.clear()
-            wait_slice = (
-                min(remaining, self.sync_timeout)
-                if self.terminal.synchronized
-                else remaining
-            )
+            if self.terminal.synchronized:
+                sync_rem = (
+                    self.sync_timeout
+                    if self._sync_started_at is None
+                    else max(0.0, self._sync_started_at + self.sync_timeout - now)
+                )
+                wait_slice = min(remaining, sync_rem)
+            else:
+                wait_slice = remaining
             with contextlib.suppress(TimeoutError):
                 await asyncio.wait_for(self._frame_event.wait(), timeout=wait_slice)
 
@@ -546,7 +609,50 @@ async def open_pty(
     limits: Limits = DEFAULT_LIMITS,
     sync_timeout: float = 1.0,
 ) -> collections.abc.AsyncGenerator[PtySession]:
-    """Spawn *argv* with a controlling POSIX PTY driven by :class:`Terminal`."""
+    """Spawn *argv* with a controlling POSIX PTY driven by :class:`Terminal`.
+
+    Parameters
+    ----------
+    argv : collections.abc.Sequence[str]
+        Command and arguments executed via ``os.execvp``.
+    rows : int
+        Initial PTY height in rows.
+    cols : int
+        Initial PTY width in columns.
+    scrollback : int
+        Primary-screen scrollback line capacity.
+    env : collections.abc.Mapping[str, str] | None
+        Environment variables passed to the child process (defaults to
+        ``os.environ`` with ``TERM=xterm-256color``).
+    cwd : str | os.PathLike[str] | None
+        Working directory for the child process.
+    tty_mode : TtyMode
+        Initial slave terminal mode (``"cooked"``, ``"cbreak"``, or ``"raw"``).
+    python_executable : str | os.PathLike[str] | None
+        Python interpreter used for the ``TIOCSCTTY`` pre-exec trampoline.
+    profile : Profile
+        Terminal compatibility profile.
+    policy : Policy
+        Host security and query policy.
+    limits : Limits
+        Parser and state resource ceilings.
+    sync_timeout : float
+        Watchdog timeout in seconds before expiring stalled ``?2026`` frames.
+
+    Yields
+    ------
+    PtySession
+        Active session connected to the child process and master PTY fd.
+
+    Raises
+    ------
+    NotImplementedError
+        On platforms lacking POSIX ``pty.openpty()`` (Windows).
+    ValueError
+        If *argv* is empty or *tty_mode* is invalid.
+    OSError
+        If PTY allocation or ``execvp`` fails.
+    """
     if sys.platform == "win32":
         msg = "open_pty requires POSIX pty.openpty()"
         raise NotImplementedError(msg)
diff --git a/src/libvt/exc.py b/src/libvt/exc.py
index 5b19d47..8920467 100644
--- a/src/libvt/exc.py
+++ b/src/libvt/exc.py
@@ -21,58 +21,149 @@ class UnsafePasteError(LibVtError):
     """Raised when pasted text contains control or bracket-escape bytes."""
 
 
-def _rebuild_terminal_timeout_error(
-    message: str,
-    parser_state: ParserState | None,
-    screen_text: str,
-    recent_bytes: bytes,
-    eof: bool,
+def _iter_slot_names(cls: type[BaseException]) -> list[str]:
+    names: list[str] = []
+    seen: set[str] = set()
+    for base in cls.__mro__:
+        raw = base.__dict__.get("__slots__")
+        if raw is None:
+            continue
+        slots = (raw,) if isinstance(raw, str) else raw
+        for slot in slots:
+            if slot in ("__dict__", "__weakref__"):
+                continue
+            attr = (
+                f"_{base.__name__.lstrip('_')}{slot}"
+                if slot.startswith("__") and not slot.endswith("__")
+                else slot
+            )
+            if attr not in seen:
+                seen.add(attr)
+                names.append(attr)
+    return names
+
+
+def _reconstruct_timeout_error(
+    cls: type[TerminalTimeoutError],
+    os_args: tuple[object, ...],
 ) -> TerminalTimeoutError:
-    return TerminalTimeoutError(
-        message,
-        parser_state=parser_state,
-        screen_text=screen_text,
-        recent_bytes=recent_bytes,
-        eof=eof,
-    )
+    obj = OSError.__new__(cls, *os_args)
+    if os_args:
+        OSError.__init__(obj, *os_args)
+    return obj
 
 
 class TerminalTimeoutError(LibVtError, TimeoutError):
-    """Raised when an async terminal stream wait exceeds its deadline."""
+    """Raised when an async terminal stream or PTY wait exceeds its deadline.
+
+    Parameters
+    ----------
+    message : str | None
+        Concise single-line error summary; omitted when ``None``.
+    parser_state : ParserState | None
+        Parser state at timeout or premature EOF.
+    screen_text : str
+        Visible screen text at failure time.
+    recent_bytes : collections.abc.Buffer
+        Trailing raw bytes from :class:`~libvt.terminal.FlightRecorder`.
+    eof : bool
+        ``True`` when the stream closed before the predicate matched.
+    diagnostics : str
+        Pre-rendered viewport box and flight-recorder diagnostic block.
+    attach_note : bool
+        When ``True`` (default), attach formatted diagnostics via PEP 678
+        :meth:`BaseException.add_note` while keeping ``str(exc)`` single-line.
+
+    Attributes
+    ----------
+    parser_state : ParserState | None
+        Parser state at timeout or premature EOF.
+    screen_text : str
+        Visible screen text at failure time.
+    recent_bytes : bytes
+        Trailing raw bytes recorded prior to failure.
+    eof : bool
+        ``True`` when end-of-stream occurred before matching.
+    diagnostics : str
+        Explicit multi-line diagnostic text, if supplied.
+    """
 
     def __init__(
         self,
-        message: str,
+        message: str | None = None,
         *,
         parser_state: ParserState | None = None,
         screen_text: str = "",
-        recent_bytes: bytes = b"",
+        recent_bytes: collections.abc.Buffer = b"",
         eof: bool = False,
+        diagnostics: str = "",
+        attach_note: bool = True,
     ) -> None:
-        super().__init__(message)
-        self._message = message
+        if message is None:
+            super().__init__()
+        else:
+            super().__init__(message)
         self.parser_state = parser_state
         self.screen_text = screen_text
-        self.recent_bytes = recent_bytes
+        self.recent_bytes = bytes(recent_bytes)
         self.eof = eof
-
-    def __reduce__(
-        self,
-    ) -> tuple[
-        collections.abc.Callable[..., TerminalTimeoutError],
-        tuple[str, ParserState | None, str, bytes, bool],
-    ]:
-        """Preserve message and diagnostic attributes across ``pickle``."""
-        return (
-            _rebuild_terminal_timeout_error,
-            (
-                self._message,
-                self.parser_state,
-                self.screen_text,
-                self.recent_bytes,
-                self.eof,
-            ),
-        )
+        self.diagnostics = diagnostics
+        if attach_note:
+            note = self.format_diagnostics()
+            if note:
+                self.add_note(note)
+
+    def format_diagnostics(self) -> str:
+        """Format structured terminal state and flight-recorder diagnostics.
+
+        Returns
+        -------
+        str
+            Multi-line diagnostic block, or ``""`` when no diagnostic fields are
+            populated.
+        """
+        if self.diagnostics:
+            return self.diagnostics
+        parts: list[str] = []
+        if self.parser_state is not None or self.eof:
+            st_name = (
+                self.parser_state.name if self.parser_state is not None else "UNKNOWN"
+            )
+            parts.append(f"parser_state={st_name} eof={self.eof}")
+        if self.screen_text:
+            parts.append(f"screen_text={self.screen_text!r}")
+        if self.recent_bytes:
+            parts.append(f"recent_bytes={self.recent_bytes!r}")
+        return "\n".join(parts)
+
+    def __reduce__(self) -> tuple[object, ...]:
+        """Serialize args, ``__dict__``, ``__notes__``, and subclass ``__slots__``."""
+        os_args = OSError.__reduce__(self)[1]
+        dict_state = dict(self.__dict__)
+        if isinstance(dict_state.get("__notes__"), list):
+            dict_state["__notes__"] = list(dict_state["__notes__"])
+        slot_state = {
+            name: getattr(self, name)
+            for name in _iter_slot_names(type(self))
+            if hasattr(self, name)
+        }
+        state: object = (dict_state, slot_state) if slot_state else dict_state
+        return (_reconstruct_timeout_error, (type(self), os_args), state)
+
+    def __setstate__(self, state: object) -> None:
+        """Restore instance ``__dict__``, ``__notes__`` copy, and ``__slots__``."""
+        if isinstance(state, tuple) and len(state) == 2:
+            dict_state, slot_state = state
+        else:
+            dict_state, slot_state = state, None
+        self.__dict__.clear()
+        if isinstance(dict_state, dict):
+            self.__dict__.update(dict_state)
+            if isinstance(self.__dict__.get("__notes__"), list):
+                self.__dict__["__notes__"] = list(self.__dict__["__notes__"])
+        if isinstance(slot_state, dict):
+            for key, val in slot_state.items():
+                setattr(self, key, val)
 
 
 class ScreenAssertionError(LibVtError, AssertionError):
diff --git a/tests/test_pr2_review_fixes.py b/tests/test_pr2_review_fixes.py
index ef30335..6399c8d 100644
--- a/tests/test_pr2_review_fixes.py
+++ b/tests/test_pr2_review_fixes.py
@@ -299,7 +299,9 @@ async def test_formatter_vt_bce_roundtrip_html_palette_and_timeout_diagnostics()
     err = exc_info.value
     assert err.parser_state == ParserState.OSC_STRING
     assert b"\x1b]0;stuck" in err.recent_bytes
-    assert "Flight Recorder:" in str(err)
+    assert "\n" not in str(err)
+    assert "Flight Recorder:" in err.format_diagnostics()
+    assert any("Flight Recorder:" in note for note in err.__notes__)
 
 
 def test_tmux_phantom_column_il_dl_and_version_factory() -> None:

From efc978ae54d3bead2f166a00898b68c29b1a70a1 Mon Sep 17 00:00:00 2001
From: Tony Narlock 
Date: Sun, 22 Nov 2026 14:14:02 -0600
Subject: [PATCH 18/29] ucd(perf[slice]): Add SAFE_NARROW_BMP_RE table (#16)

why: Printable narrow BMP runs such as box-drawing borders, Greek, and
Cyrillic fell back to per-character UAX #29 clustering because fast
slicing checked ASCII only.

what:
- Generate SAFE_NARROW_BMP_RE in scripts/generate_ucd.py across narrow
  BMP codepoints that neither join prior clusters nor take VS15/VS16
- Escape double quotes in generated character-class literals
- Include scripts/ in [tool.ty.src] and widen bench_vt._measure callable
  return typing
---
 pyproject.toml          |  1 +
 scripts/bench_vt.py     |  2 +-
 scripts/generate_ucd.py | 74 +++++++++++++++++++++++++++++++++++++++++
 src/libvt/_ucd.py       | 56 +++++++++++++++++++++++++++++++
 4 files changed, 132 insertions(+), 1 deletion(-)

diff --git a/pyproject.toml b/pyproject.toml
index ae24906..ed326ac 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -142,6 +142,7 @@ blanket-ignore-comment = "error"
 
 [tool.ty.src]
 include = [
+  "scripts",
   "src",
   "tests",
 ]
diff --git a/scripts/bench_vt.py b/scripts/bench_vt.py
index 8b69145..5ae47e3 100644
--- a/scripts/bench_vt.py
+++ b/scripts/bench_vt.py
@@ -120,7 +120,7 @@ def _build_synthetic_ansi_frame() -> bytes:
 
 def _measure(
     name: str,
-    fn: t.Callable[[], None],
+    fn: t.Callable[[], object],
     *,
     bytes_per_op: int,
     warmup: int,
diff --git a/scripts/generate_ucd.py b/scripts/generate_ucd.py
index e3966fb..e9a6c69 100644
--- a/scripts/generate_ucd.py
+++ b/scripts/generate_ucd.py
@@ -233,12 +233,80 @@ def build_tables(ucd_dir: pathlib.Path) -> tuple[bytes, bytes]:
     return stage1_bytes, stage2_bytes
 
 
+def _format_bmp_escape(cp: int) -> str:
+    if cp == ord('"'):
+        return r"\x22"
+    if cp in (ord("\\"), ord("-"), ord("]"), ord("^")):
+        return "\\" + chr(cp)
+    if 0x20 <= cp <= 0x7E:
+        return chr(cp)
+    if cp <= 0xFF:
+        return f"\\x{cp:02x}"
+    return f"\\u{cp:04x}"
+
+
+def build_safe_narrow_bmp_pattern(stage1: bytes, stage2: bytes) -> str:
+    """Build character-class regex pattern for bulk-sliceable narrow BMP runs."""
+    safe_cps: list[int] = []
+    for cp in range(0x0020, 0x10000):
+        if 0x007F <= cp <= 0x009F or 0xD800 <= cp <= 0xDFFF:
+            continue
+        b_idx = int.from_bytes(stage1[(cp >> 8) * 2 : (cp >> 8) * 2 + 2], "little")
+        off = ((b_idx << 8) | (cp & 0xFF)) * 2
+        entry = int.from_bytes(stage2[off : off + 2], "little")
+        width = entry & 0b11
+        gcb = (entry >> 2) & 0x0F
+        incb = (entry >> 6) & 0x03
+        ext_pict = bool(entry & (1 << 8))
+        emoji_mod = bool(entry & (1 << 9))
+        vs_base = bool(entry & (1 << 10))
+        bidi_spoof = bool(entry & (1 << 11))
+        if (
+            width == 1
+            and gcb == 0
+            and incb == 0
+            and not ext_pict
+            and not emoji_mod
+            and not bidi_spoof
+            and not (cp >= 0x80 and vs_base)
+        ):
+            safe_cps.append(cp)
+
+    parts: list[str] = []
+    idx = 0
+    total = len(safe_cps)
+    while idx < total:
+        start = safe_cps[idx]
+        end = start
+        while idx + 1 < total and safe_cps[idx + 1] == end + 1:
+            idx += 1
+            end = safe_cps[idx]
+        if start == end:
+            parts.append(_format_bmp_escape(start))
+        elif end == start + 1:
+            parts.append(_format_bmp_escape(start) + _format_bmp_escape(end))
+        else:
+            parts.append(f"{_format_bmp_escape(start)}-{_format_bmp_escape(end)}")
+        idx += 1
+    return "[" + "".join(parts) + "]+"
+
+
 def render_module(stage1: bytes, stage2: bytes) -> str:
     """Format ``src/libvt/_ucd.py`` source text."""
     blob = len(stage1).to_bytes(4, "little") + stage1 + stage2
     compressed = base64.b85encode(zlib.compress(blob, level=9)).decode("ascii")
     lines = [compressed[i : i + 76] for i in range(0, len(compressed), 76)]
     b85_literal = "\n".join(f'    "{ln}"' for ln in lines)
+    bmp_pat = build_safe_narrow_bmp_pattern(stage1, stage2)
+    pat_chunks: list[str] = []
+    p_idx = 0
+    while p_idx < len(bmp_pat):
+        end_p = min(len(bmp_pat), p_idx + 72)
+        while end_p < len(bmp_pat) and bmp_pat[end_p - 1] == "\\":
+            end_p -= 1
+        pat_chunks.append(bmp_pat[p_idx:end_p])
+        p_idx = end_p
+    bmp_pat_literal = "\n".join(f'    r"{chunk}"' for chunk in pat_chunks)
 
     return f'''"""Generated two-stage Unicode {UNICODE_VERSION} width and UAX #29 table.
 
@@ -259,6 +327,7 @@ def render_module(stage1: bytes, stage2: bytes) -> str:
 import array
 import base64
 import enum
+import re
 import sys
 import typing as t
 import zlib
@@ -306,6 +375,10 @@ class WidthRole(enum.IntEnum):
 
 UNICODE_VERSION = "{UNICODE_VERSION}"
 
+SAFE_NARROW_BMP_RE: t.Final[re.Pattern[str]] = re.compile(
+{bmp_pat_literal}
+)
+
 _PACKED_B85 = (
 {b85_literal}
 )
@@ -596,6 +669,7 @@ def sanitize_terminal_text(text: str) -> str:
 __all__ = [
     "BIDI_SPOOF_BIT",
     "CLUSTER_NONE",
+    "SAFE_NARROW_BMP_RE",
     "UNICODE_VERSION",
     "WidthRole",
     "char_width",
diff --git a/src/libvt/_ucd.py b/src/libvt/_ucd.py
index 95a9d14..f63e466 100644
--- a/src/libvt/_ucd.py
+++ b/src/libvt/_ucd.py
@@ -17,6 +17,7 @@
 import array
 import base64
 import enum
+import re
 import sys
 import typing as t
 import zlib
@@ -64,6 +65,60 @@ class WidthRole(enum.IntEnum):
 
 UNICODE_VERSION = "17.0.0"
 
+SAFE_NARROW_BMP_RE: t.Final[re.Pattern[str]] = re.compile(
+    r"[ -~\xa0-\xa8\xaa-\xac\xaf-\u02ff\u0370-\u0482\u048a-\u0590\u05be\u05c0"
+    r"\u05c3\u05c6\u05c8-\u05ff\u0606-\u060f\u061b\u061d-\u064a\u0660-\u066f\u"
+    r"0671-\u06d5\u06de\u06e5\u06e6\u06e9\u06ee-\u070e\u0710\u0712-\u072f\u074"
+    r"b-\u07a5\u07b1-\u07ea\u07f4-\u07fc\u07fe-\u0815\u081a\u0824\u0828\u082e-"
+    r"\u0858\u085c-\u088f\u0892-\u0896\u08a0-\u08c9\u0904-\u0914\u093d\u0950\u"
+    r"0960\u0961\u0964-\u0977\u0980\u0984-\u0994\u09a9\u09b1\u09b3-\u09b5\u09b"
+    r"a\u09bb\u09bd\u09c5\u09c6\u09c9\u09ca\u09ce-\u09d6\u09d8-\u09db\u09de\u0"
+    r"9e0\u09e1\u09e4-\u09ef\u09f2-\u09fd\u09ff\u0a00\u0a04-\u0a3b\u0a3d\u0a43"
+    r"-\u0a46\u0a49\u0a4a\u0a4e-\u0a50\u0a52-\u0a6f\u0a72-\u0a74\u0a76-\u0a80"
+    r"\u0a84-\u0a94\u0aa9\u0ab1\u0ab4\u0aba\u0abb\u0abd\u0ac6\u0aca\u0ace-\u0a"
+    r"e1\u0ae4-\u0af8\u0b00\u0b04-\u0b14\u0b29\u0b31\u0b34\u0b3a\u0b3b\u0b3d\u"
+    r"0b45\u0b46\u0b49\u0b4a\u0b4e-\u0b54\u0b58-\u0b5b\u0b5e\u0b60\u0b61\u0b64"
+    r"-\u0b70\u0b72-\u0b81\u0b83-\u0bbd\u0bc3-\u0bc5\u0bc9\u0bce-\u0bd6\u0bd8-"
+    r"\u0bff\u0c05-\u0c14\u0c29\u0c3a\u0c3b\u0c3d\u0c45\u0c49\u0c4e-\u0c54\u0c"
+    r"57\u0c5b-\u0c61\u0c64-\u0c80\u0c84-\u0cbb\u0cbd\u0cc5\u0cc9\u0cce-\u0cd4"
+    r"\u0cd7-\u0ce1\u0ce4-\u0cf2\u0cf4-\u0cff\u0d04-\u0d14\u0d3d\u0d45\u0d49\u"
+    r"0d4f-\u0d56\u0d58-\u0d61\u0d64-\u0d80\u0d84-\u0dc9\u0dcb-\u0dce\u0dd5\u0"
+    r"dd7\u0de0-\u0df1\u0df4-\u0e30\u0e32\u0e3b-\u0e46\u0e4f-\u0eb0\u0eb2\u0eb"
+    r"d-\u0ec7\u0ecf-\u0f17\u0f1a-\u0f34\u0f36\u0f38\u0f3a-\u0f3d\u0f40-\u0f70"
+    r"\u0f85\u0f88-\u0f8c\u0f98\u0fbd-\u0fc5\u0fc7-\u0fff\u1040-\u104f\u1090-"
+    r"\u1099\u109e-\u10ff\u1200-\u135c\u1360-\u1711\u1716-\u1731\u1735-\u1751"
+    r"\u1754-\u1771\u1774-\u177f\u17d4-\u17dc\u17de-\u180a\u1810-\u1884\u1887-"
+    r"\u18a8\u18aa-\u191f\u192c-\u192f\u193c-\u1a16\u1a1c-\u1a1f\u1a5f\u1a7d\u"
+    r"1a7e\u1a80-\u1aaf\u1ade\u1adf\u1aec-\u1aff\u1b05-\u1b0a\u1b0d-\u1b12\u1b"
+    r"4d-\u1b6a\u1b74-\u1b7f\u1bb0-\u1bba\u1bbe-\u1be5\u1bf4-\u1c23\u1c38-\u1c"
+    r"cf\u1cd3\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa-\u1dbf\u1e00-\u200a"
+    r"\u2010-\u2027\u202f-\u203b\u203d-\u2048\u204a-\u205f\u2070-\u20cf\u20f1-"
+    r"\u2121\u2123-\u2138\u213a-\u2193\u219a-\u21a8\u21ab-\u2319\u231c-\u2327"
+    r"\u232b-\u23ce\u23d0-\u23e8\u23f4-\u23f7\u23fb-\u24c1\u24c3-\u25a9\u25ac-"
+    r"\u25b5\u25b7-\u25bf\u25c1-\u25fa\u25ff\u2605-\u260d\u260f\u2610\u2612\u2"
+    r"613\u2616\u2617\u2619-\u261c\u261e\u261f\u2621\u2624\u2625\u2627-\u2629"
+    r"\u262b-\u262d\u263b-\u263f\u2641\u2643-\u2647\u2654-\u265e\u2661\u2662\u"
+    r"2664\u2667\u2669-\u267a\u267c\u267d\u2680-\u2689\u2690\u2691\u2698\u269a"
+    r"\u269d-\u269f\u26a2-\u26a6\u26a8\u26a9\u26ac-\u26af\u26b2-\u26bc\u26bf-"
+    r"\u26c3\u26c6\u26c7\u26c9-\u26cd\u26d0\u26d2\u26d5-\u26e8\u26eb-\u26ef\u2"
+    r"6f6\u26fb\u26fc\u26fe-\u2701\u2703\u2704\u2706\u2707\u270e\u2710\u2711\u"
+    r"2713\u2715\u2717-\u271c\u271e-\u2720\u2722-\u2727\u2729-\u2732\u2735-\u2"
+    r"743\u2745\u2746\u2748-\u274b\u274d\u274f-\u2752\u2756\u2758-\u2762\u2765"
+    r"-\u2794\u2798-\u27a0\u27a2-\u27af\u27b1-\u27be\u27c0-\u2933\u2936-\u2b04"
+    r"\u2b08-\u2b1a\u2b1d-\u2b4f\u2b51-\u2b54\u2b56-\u2cee\u2cf2-\u2d7e\u2d80-"
+    r"\u2ddf\u2e00-\u2e7f\u2e9a\u2ef4-\u2eff\u2fd6-\u2fef\u303f\u3040\u3097\u3"
+    r"098\u3100-\u3104\u3130\u318f\u31e6-\u31ee\u321f\u3248-\u324f\ua48d-\ua48"
+    r"f\ua4c7-\ua66e\ua673\ua67e-\ua69d\ua6a0-\ua6ef\ua6f2-\ua801\ua803-\ua805"
+    r"\ua807-\ua80a\ua80c-\ua822\ua828-\ua82b\ua82d-\ua87f\ua882-\ua8b3\ua8c6-"
+    r"\ua8df\ua8f2-\ua8fe\ua900-\ua925\ua92e-\ua946\ua954-\ua95f\ua97d-\ua97f"
+    r"\ua984-\ua988\ua98c-\ua98e\ua9c1-\ua9df\ua9e6\ua9f0-\ua9f9\ua9ff-\uaa28"
+    r"\uaa37-\uaa42\uaa44-\uaa4b\uaa4e-\uaa5f\uaa70\uaa74-\uaa79\uaa80-\uaaaf"
+    r"\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2-\uaadf\uaaf0-\uaaf4\uaaf7-\u"
+    r"abbf\uabdb-\uabe2\uabeb\uabee-\uabff\ud7a4-\ud7af\ud7c7-\ud7ca\ud7fc-\ud"
+    r"7ff\ue000-\uf8ff\ufb00-\ufb1d\ufb1f-\ufdff\ufe1a-\ufe1f\ufe53\ufe67\ufe6"
+    r"c-\ufefe\uff00\uff61-\uff9d\uffa0-\uffdf\uffe7-\uffef\ufffc-\uffff]+"
+)
+
 _PACKED_B85 = (
     "c-rkJd{)sw??NpioGW^_Q8(d"
@@ -390,6 +445,7 @@ def sanitize_terminal_text(text: str) -> str:
 __all__ = [
     "BIDI_SPOOF_BIT",
     "CLUSTER_NONE",
+    "SAFE_NARROW_BMP_RE",
     "UNICODE_VERSION",
     "WidthRole",
     "char_width",

From 213ba0b8a5534082d9951d33aaa31d08590a93d4 Mon Sep 17 00:00:00 2001
From: Tony Narlock 
Date: Sun, 22 Nov 2026 14:14:10 -0600
Subject: [PATCH 19/29] config(feat[tmux]): Add profile and row-gen fields
 (#17)

why: tmux ignores DECSTR, scrolls primary ED 2 into history, and
requires monotonic row generations, DECSDM, and immutable event headers
for incremental deltas and graphics tracking.

what:
- Add decstr_enabled, ed2_scrolls_primary_to_history, cell pixel sizes,
  sixel_erase_policy, and Profile.linux_console() in libvt.config
- Support next-3.9, rc, and tmux-prefixed strings in Profile.tmux()
- Add Mode.DECSDM, freeze KittyCommand.control with MappingProxyType,
  and stamp monotonic _Row.content_gen counters across row mutations
---
 src/libvt/_grid.py  | 56 +++++++++++++++++++++++-------
 src/libvt/config.py | 84 +++++++++++++++++++++++++++++++++++++++++++--
 src/libvt/events.py | 15 ++++++--
 src/libvt/modes.py  |  1 +
 4 files changed, 138 insertions(+), 18 deletions(-)

diff --git a/src/libvt/_grid.py b/src/libvt/_grid.py
index dca378c..e6f76b5 100644
--- a/src/libvt/_grid.py
+++ b/src/libvt/_grid.py
@@ -30,6 +30,22 @@
     UnderlineStyle,
 )
 
+_GLOBAL_ROW_GEN: int = 0
+
+
+def bump_row_gen(row: _Row) -> int:
+    """Stamp *row* with the next strictly monotonic mutation generation."""
+    global _GLOBAL_ROW_GEN
+    _GLOBAL_ROW_GEN += 1
+    row.content_gen = _GLOBAL_ROW_GEN
+    return _GLOBAL_ROW_GEN
+
+
+def current_row_gen() -> int:
+    """Return the latest global row mutation generation without advancing it."""
+    return _GLOBAL_ROW_GEN
+
+
 _COLOR_MASK = (1 << 25) - 1
 _RGB_FLAG = 1 << 24
 _IDX_BASE = 256
@@ -271,11 +287,12 @@ def thaw(self, target_cols: int | None = None) -> _Row:
 
 
 class _Row:
-    """Mutableviewport row with lazy 64-bit ``array('Q')`` promotion."""
+    """Mutable viewport row with lazy 64-bit ``array('Q')`` promotion."""
 
     __slots__ = (
         "attrs",
         "chars",
+        "content_gen",
         "ext",
         "has_wide",
         "text_used",
@@ -293,6 +310,7 @@ def __init__(self, cols: int) -> None:
         self.used: int = 0
         self.text_used: int = 0
         self.wrapped: bool = False
+        self.content_gen: int = 0
 
     def _ensure_attrs(self) -> array.array[int]:
         if self.attrs is None:
@@ -339,6 +357,7 @@ def reset_blank(
             self.used = cols if bce_word != 0 else 0
         self.text_used = 0
         self.wrapped = False
+        bump_row_gen(self)
 
     def _set_raw(
         self,
@@ -391,15 +410,17 @@ def _heal_wide_boundary(self, col: int) -> None:
             if col - 1 >= 0:
                 self.chars[col - 1] = " "
                 self.attrs[col - 1] &= _WIDTH_CLEAR_MASK
-        if healed_pair_end != -1 and self.text_used == healed_pair_end:
-            pair_lo = max(0, healed_pair_end - 2)
-            self.text_used = pair_lo
-            if (
-                self.used == healed_pair_end
-                and self.attr_at(healed_pair_end - 1) == 0
-                and self.ext_at(healed_pair_end - 1) is None
-            ):
-                self.used = pair_lo
+        if healed_pair_end != -1:
+            if self.text_used == healed_pair_end:
+                pair_lo = max(0, healed_pair_end - 2)
+                self.text_used = pair_lo
+                if (
+                    self.used == healed_pair_end
+                    and self.attr_at(healed_pair_end - 1) == 0
+                    and self.ext_at(healed_pair_end - 1) is None
+                ):
+                    self.used = pair_lo
+            bump_row_gen(self)
 
     def write_narrow(
         self,
@@ -413,6 +434,7 @@ def write_narrow(
         self._set_raw(col, ch, pen_word, WidthRole.NARROW, cell_ext)
         self.used = max(self.used, col + 1)
         self.text_used = max(self.text_used, col + 1)
+        bump_row_gen(self)
 
     def write_spacer_head(
         self,
@@ -425,6 +447,7 @@ def write_spacer_head(
         self._set_raw(col, "", bce_word, WidthRole.SPACER_HEAD, bce_ext)
         self.used = max(self.used, col + 1)
         self.text_used = max(self.text_used, col + 1)
+        bump_row_gen(self)
 
     def write_ascii_slice(
         self,
@@ -469,6 +492,7 @@ def write_ascii_slice(
 
         self.used = max(self.used, end)
         self.text_used = max(self.text_used, end)
+        bump_row_gen(self)
 
     def write_wide(
         self,
@@ -484,6 +508,7 @@ def write_wide(
         self._set_raw(col + 1, "", pen_word, WidthRole.SPACER_TAIL, cell_ext)
         self.used = max(self.used, col + 2)
         self.text_used = max(self.text_used, col + 2)
+        bump_row_gen(self)
 
     def append_grapheme(
         self,
@@ -534,6 +559,7 @@ def append_grapheme(
                 self.text_used = target + 1
                 if self.used == target + 2 and pen_word == 0 and cell_ext is None:
                     self.used = target + 1
+        bump_row_gen(self)
 
     def clear_range(
         self,
@@ -570,6 +596,7 @@ def clear_range(
             if hi >= self.text_used:
                 while self.text_used > lo and not self.is_protected(self.text_used - 1):
                     self.text_used -= 1
+            bump_row_gen(self)
             return
 
         if lo == 0 and hi == cols:
@@ -603,10 +630,11 @@ def clear_range(
             if bce_word != 0:
                 self.used = max(self.used, hi)
             elif hi >= self.used:
-                # Clamp used to lo without erasing explicit spaces printed left of lo!
+                # Clamp used to lo without erasing explicit spaces left of lo.
                 self.used = min(self.used, lo)
         if hi >= self.text_used:
             self.text_used = min(self.text_used, lo)
+        bump_row_gen(self)
 
     def insert_blanks(
         self,
@@ -665,7 +693,7 @@ def insert_blanks(
                 else:
                     self.ext.pop(dst, None)
 
-        # 3. If shifting pushed a WIDE head onto right without its tail, clear right!
+        # Clear right when shifting pushes a WIDE head onto right without its tail.
         if (
             self.has_wide
             and attrs is not None
@@ -682,6 +710,7 @@ def insert_blanks(
             self.used = min(right + 1, max(self.used + shift, col + shift))
         if self.text_used <= right + 1 and self.text_used > col:
             self.text_used = min(right + 1, self.text_used + shift)
+        bump_row_gen(self)
 
     def delete_cells(
         self,
@@ -750,6 +779,7 @@ def delete_cells(
                 self.used = max(col, self.used - shift)
         if self.text_used <= right + 1 and self.text_used > col:
             self.text_used = max(col, self.text_used - shift)
+        bump_row_gen(self)
 
     def resize(self, cols: int) -> None:
         """Resize row in place to *cols* columns (non-reflow path)."""
@@ -782,6 +812,7 @@ def resize(self, cols: int) -> None:
                 attrs = array.array("Q", [self.uniform_attr]) * cur
                 attrs.extend([0] * pad)
                 self.attrs = attrs
+        bump_row_gen(self)
 
     def clone(self) -> _Row:
         """Return an independent copy of this row."""
@@ -794,6 +825,7 @@ def clone(self) -> _Row:
         dup.used = self.used
         dup.text_used = self.text_used
         dup.wrapped = self.wrapped
+        dup.content_gen = self.content_gen
         return dup
 
     def freeze(self) -> FrozenRow:
diff --git a/src/libvt/config.py b/src/libvt/config.py
index 72f0120..0e831d0 100644
--- a/src/libvt/config.py
+++ b/src/libvt/config.py
@@ -8,8 +8,11 @@
 from dataclasses import dataclass
 
 type Charset = t.Literal["B", "0", "A"]
+type SixelErasePolicy = t.Literal["cell_mask", "whole_image"]
 
-_TMUX_VERSION_RE = re.compile(r"^\s*(\d+)\.(\d+)[a-z]?\s*$")
+_TMUX_VERSION_RE = re.compile(
+    r"^\s*(?:tmux\s+)?(?:next-)?(\d+)\.(\d+)(?:[a-z]|-rc\d*)?\s*$",
+)
 
 
 class ColorScheme(enum.IntEnum):
@@ -81,6 +84,26 @@ class Profile:
     default_g1_charset : Charset
         Initial ``G1`` character-set designation on startup and ``RIS``
         (``"B"`` US-ASCII by default).
+    decstr_enabled : bool
+        When ``True`` (default), ``DECSTR`` (``CSI ! p``) performs a soft
+        terminal reset; when ``False`` (``TMUX_PROFILE``), ``CSI ! p`` is
+        ignored, matching ``tmux``'s ``input.c``.
+    ed2_scrolls_primary_to_history : bool
+        When ``True`` (``TMUX_PROFILE``), primary-screen ``CSI 2 J`` (and
+        ``CSI J`` with cursor at ``(0, 0)``) scrolls rows up to the last
+        non-empty or image-bearing row into scrollback before clearing with
+        ``BCE``, matching ``tmux``'s ``scroll-on-clear`` default.
+    cell_width_px : int
+        Nominal cell width in pixels used for ``CSI 14 t``, ``CSI 16 t``, and
+        ``SIXEL`` / Kitty cell-grid geometry (default ``8``).
+    cell_height_px : int
+        Nominal cell height in pixels used for ``CSI 14 t``, ``CSI 16 t``, and
+        ``SIXEL`` / Kitty cell-grid geometry (default ``16``).
+    sixel_erase_policy : SixelErasePolicy
+        How text overwrites and cell erases affect ``SIXEL`` placements:
+        ``"cell_mask"`` (default and ``tmux >= 3.9``) clears individual cells;
+        ``"whole_image"`` (``tmux <= 3.8``) deletes any intersected ``SIXEL``
+        placement.
     """
 
     name: str = "libvt"
@@ -103,17 +126,40 @@ class Profile:
     il_dl_resets_col: bool = True
     rep_wraps: bool = True
     default_g1_charset: Charset = "B"
+    decstr_enabled: bool = True
+    ed2_scrolls_primary_to_history: bool = False
+    cell_width_px: int = 8
+    cell_height_px: int = 16
+    sixel_erase_policy: SixelErasePolicy = "cell_mask"
 
     @classmethod
     def tmux(cls, version: tuple[int, int] | str = "3.8a") -> Profile:
-        """Build a version-specific ``tmux`` compatibility :class:`Profile`."""
+        """Build a version-specific ``tmux`` compatibility :class:`Profile`.
+
+        Parameters
+        ----------
+        version : tuple[int, int] | str
+            ``(major, minor)`` tuple or ``tmux -V`` version string such as
+            ``"3.8a"``, ``"tmux 3.8-rc3"``, or ``"next-3.9"``.
+
+        Returns
+        -------
+        Profile
+            Configured ``tmux`` compatibility profile.
+
+        Raises
+        ------
+        ValueError
+            If *version* cannot be parsed as a ``tmux`` version identifier.
+        """
         if isinstance(version, tuple):
             major, minor = version
         else:
             m = _TMUX_VERSION_RE.match(version)
             if m is None:
                 msg = (
-                    f"invalid tmux version {version!r}; expected e.g. '3.8a' or (3, 8)"
+                    f"invalid tmux version {version!r}; expected e.g. "
+                    "'3.8a', 'next-3.9', or (3, 8)"
                 )
                 raise ValueError(msg)
             major, minor = int(m.group(1)), int(m.group(2))
@@ -128,6 +174,19 @@ def tmux(cls, version: tuple[int, int] | str = "3.8a") -> Profile:
             hpr_vpr_enabled=False,
             il_dl_resets_col=False,
             rep_wraps=at_least_3_9,
+            decstr_enabled=False,
+            ed2_scrolls_primary_to_history=True,
+            sixel_erase_policy="cell_mask" if at_least_3_9 else "whole_image",
+        )
+
+    @classmethod
+    def linux_console(cls) -> Profile:
+        """Build a Linux virtual-console compatibility :class:`Profile`."""
+        return cls(
+            name="linux",
+            osc_7501_capabilities="",
+            reflow_on_resize=False,
+            default_g1_charset="0",
         )
 
 
@@ -177,6 +236,9 @@ class Policy:
         Raise :exc:`~libvt.exc.ProtocolError` on unrecognized or overflowing
         escape sequences instead of ignoring or recording
         :class:`~libvt.events.UnhandledSequence` (default ``False``).
+    track_graphics : bool
+        Track sans-I/O ``SIXEL`` and Kitty ``APC G`` image metadata and grid
+        placements (default ``True``).
     """
 
     allow_title_report: bool = False
@@ -190,6 +252,7 @@ class Policy:
     abort_dispatch_osc: bool = False
     osc7_hosts: frozenset[str] | None = None
     strict: bool = False
+    track_graphics: bool = True
 
 
 @dataclass(frozen=True, slots=True, kw_only=True)
@@ -229,6 +292,15 @@ class Limits:
         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`.
+    max_images : int
+        Maximum stored Kitty / ``SIXEL`` image metadata entries per screen
+        (default ``256``).
+    max_placements : int
+        Maximum active + scrollback image placements retained per screen
+        (default ``1_024``).
+    max_image_dimension : int
+        Maximum pixel width or height accepted for ``SIXEL`` or Kitty images
+        (default ``10_000``).
     """
 
     max_grapheme_codepoints: int = 32
@@ -244,6 +316,9 @@ class Limits:
     max_event_bytes: int = 16_777_216
     max_keyboard_stack: int = 8
     max_recorder_bytes: int = 4_096
+    max_images: int = 256
+    max_placements: int = 1_024
+    max_image_dimension: int = 10_000
 
 
 DEFAULT_PROFILE = Profile()
@@ -254,6 +329,7 @@ class Limits:
     ed3_clears_scrollback_on_alt=True,
 )
 TMUX_PROFILE = Profile.tmux("3.8a")
+LINUX_CONSOLE_PROFILE = Profile.linux_console()
 DEFAULT_POLICY = Policy()
 TMUX_CAPTURE_POLICY = Policy(allow_passthrough=True)
 DEFAULT_LIMITS = Limits()
@@ -263,6 +339,7 @@ class Limits:
     "DEFAULT_OSC7_HOSTS",
     "DEFAULT_POLICY",
     "DEFAULT_PROFILE",
+    "LINUX_CONSOLE_PROFILE",
     "TMUX_CAPTURE_POLICY",
     "TMUX_PROFILE",
     "XTERM_PROFILE",
@@ -271,4 +348,5 @@ class Limits:
     "Limits",
     "Policy",
     "Profile",
+    "SixelErasePolicy",
 ]
diff --git a/src/libvt/events.py b/src/libvt/events.py
index f2e1ecb..3fdfa5d 100644
--- a/src/libvt/events.py
+++ b/src/libvt/events.py
@@ -2,7 +2,9 @@
 
 from __future__ import annotations
 
+import collections.abc
 import enum
+import types
 import typing as t
 from dataclasses import dataclass
 
@@ -112,17 +114,24 @@ class KittyCommand:
         Zero-based cursor row when the command arrived.
     col : int
         Zero-based cursor column when the command arrived.
-    control : dict[str, str]
-        Key-value control header pairs before ``;``.
+    control : collections.abc.Mapping[str, str]
+        Immutable key-value control header pairs before ``;``.
     payload : bytes
         Encoded payload bytes following ``;``.
     """
 
     row: int
     col: int
-    control: dict[str, str]
+    control: collections.abc.Mapping[str, str]
     payload: bytes
 
+    def __post_init__(self) -> None:
+        """Freeze ``control`` inside a :class:`types.MappingProxyType`."""
+        if not isinstance(self.control, types.MappingProxyType):
+            object.__setattr__(
+                self, "control", types.MappingProxyType(dict(self.control))
+            )
+
 
 @dataclass(frozen=True, slots=True)
 class Bell:
diff --git a/src/libvt/modes.py b/src/libvt/modes.py
index b9d5bda..6b214a6 100644
--- a/src/libvt/modes.py
+++ b/src/libvt/modes.py
@@ -21,6 +21,7 @@ class Mode(enum.IntEnum):
     REVERSE_WRAP = DEC_PRIVATE_MASK | 45
     ALT_SCREEN_47 = DEC_PRIVATE_MASK | 47
     DECLRMM = DEC_PRIVATE_MASK | 69
+    DECSDM = DEC_PRIVATE_MASK | 80
     MOUSE_VT200 = DEC_PRIVATE_MASK | 1000
     MOUSE_BUTTON_EVENT = DEC_PRIVATE_MASK | 1002
     MOUSE_ANY_EVENT = DEC_PRIVATE_MASK | 1003

From 6f2d40b7ce9dcc2ae27cf11bf9ff711e7d3e0973 Mon Sep 17 00:00:00 2001
From: Tony Narlock 
Date: Sun, 22 Nov 2026 14:14:42 -0600
Subject: [PATCH 20/29] graphics(feat[vt]): Add SIXEL and Kitty tracker (#14)

why: Terminal callers need zero-dependency SIXEL and Kitty APC G image
metadata and grid placement tracking across scroll regions and erase
policies without decoding full pixel buffers.

what:
- Add GraphicsTracker, ImageMeta, ImagePlacement, GraphicsProtocol, and
  ZLayer in libvt.graphics with bounded LRU caps and 64 KiB zlib steps
- Support scroll-before-place SIXEL and Kitty C=0 placement, silent
  unnumbered uploads, relative P=/Q=/H=/V= placements, and orphan pruning
- Add docs/api/graphics.md API reference page
---
 docs/api/graphics.md  |    6 +
 src/libvt/graphics.py | 1613 +++++++++++++++++++++++++++++++++++++++++
 2 files changed, 1619 insertions(+)
 create mode 100644 docs/api/graphics.md
 create mode 100644 src/libvt/graphics.py

diff --git a/docs/api/graphics.md b/docs/api/graphics.md
new file mode 100644
index 0000000..ebdb42a
--- /dev/null
+++ b/docs/api/graphics.md
@@ -0,0 +1,6 @@
+# `libvt.graphics`
+
+```{eval-rst}
+.. automodule:: libvt.graphics
+   :members:
+```
diff --git a/src/libvt/graphics.py b/src/libvt/graphics.py
new file mode 100644
index 0000000..ba112b7
--- /dev/null
+++ b/src/libvt/graphics.py
@@ -0,0 +1,1613 @@
+"""Zero-dependency sans-I/O ``SIXEL`` and Kitty ``APC G`` placement tracker."""
+
+from __future__ import annotations
+
+import base64
+import binascii
+import collections
+import collections.abc
+import enum
+import struct
+import typing as t
+import zlib
+from dataclasses import dataclass
+
+if t.TYPE_CHECKING:
+    from libvt.config import SixelErasePolicy
+
+_PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
+_Z_BELOW_BG_THRESHOLD = -(1 << 30)
+_MAX_UPLOAD_CHUNKS = 4_096
+_MAX_UPLOAD_BYTES = 16_777_216
+_MAX_ZLIB_INFLATE_BYTES = 16_777_216
+_ZLIB_STEP_BYTES = 65_536
+_MAX_MASK_CELLS = 16_384
+_MAX_PARENT_DEPTH = 8
+
+
+class GraphicsProtocol(enum.StrEnum):
+    """Terminal graphics protocol family."""
+
+    SIXEL = "sixel"
+    KITTY = "kitty"
+
+
+class ZLayer(enum.StrEnum):
+    """Kitty graphics z-ordering plane relative to cell background and text."""
+
+    BELOW_BG = "below_bg"
+    BELOW_TEXT = "below_text"
+    ABOVE_TEXT = "above_text"
+
+
+@dataclass(frozen=True, slots=True)
+class ImageMeta:
+    """Stored sans-I/O image metadata without buffered pixel bitmaps.
+
+    Attributes
+    ----------
+    protocol : GraphicsProtocol
+        Originating graphics protocol (``SIXEL`` or ``KITTY``).
+    image_id : int
+        Protocol image identifier (auto-assigned positive integer for ``SIXEL``
+        or unnumbered Kitty uploads).
+    image_number : int
+        Optional Kitty ``I=`` non-unique image number (``0`` when unset).
+    width_px : int
+        Decoded or declared image width in pixels.
+    height_px : int
+        Decoded or declared image height in pixels.
+    format_code : int
+        Kitty ``f=`` pixel format (``8``, ``16``, ``24``, ``32``, or ``100``
+        PNG), or ``0`` for ``SIXEL``.
+    compressed : bool
+        ``True`` when transmitted with Kitty ``o=z`` zlib compression.
+    byte_len : int
+        Total encoded payload byte count observed across upload chunks.
+    """
+
+    protocol: GraphicsProtocol
+    image_id: int
+    image_number: int = 0
+    width_px: int = 0
+    height_px: int = 0
+    format_code: int = 32
+    compressed: bool = False
+    byte_len: int = 0
+
+
+@dataclass(frozen=True, slots=True)
+class ImagePlacement:
+    """Immutable snapshot of a ``SIXEL`` or Kitty image placement on a screen.
+
+    Attributes
+    ----------
+    protocol : GraphicsProtocol
+        Originating graphics protocol.
+    image_id : int
+        Referenced :attr:`ImageMeta.image_id`.
+    placement_id : int
+        Kitty ``p=`` placement identifier (``0`` when default/unnumbered).
+    row : int
+        Zero-based viewport row (negative when scrolled into history).
+    col : int
+        Zero-based starting column.
+    rows : int
+        Height in terminal cells.
+    cols : int
+        Width in terminal cells.
+    abs_row : int
+        Absolute grid row anchor (``scrolled_total + row``).
+    z_index : int
+        Signed 32-bit z-index (``0`` default).
+    virtual : bool
+        ``True`` for Kitty ``U=1`` Unicode-placeholder virtual placements.
+    parent_image_id : int
+        Parent image ID for Kitty ``P=`` relative placements (``0`` when none).
+    parent_placement_id : int
+        Parent placement ID for Kitty ``Q=`` relative placements.
+    source_x : int
+        Cropped source rectangle X origin in pixels.
+    source_y : int
+        Cropped source rectangle Y origin in pixels.
+    source_width : int
+        Cropped source rectangle width in pixels.
+    source_height : int
+        Cropped source rectangle height in pixels.
+    cell_offset_x : int
+        Sub-cell pixel X offset within the anchor cell.
+    cell_offset_y : int
+        Sub-cell pixel Y offset within the anchor cell.
+    visible_mask : int | None
+        Bitmask of ``rows * cols`` visible cells for ``SIXEL`` under
+        ``"cell_mask"`` erase policy (bit ``r * cols + c`` is ``1`` when
+        intact); ``None`` when all cells in ``(rows, cols)`` are intact.
+    """
+
+    protocol: GraphicsProtocol
+    image_id: int
+    placement_id: int
+    row: int
+    col: int
+    rows: int
+    cols: int
+    abs_row: int
+    z_index: int = 0
+    virtual: bool = False
+    parent_image_id: int = 0
+    parent_placement_id: int = 0
+    source_x: int = 0
+    source_y: int = 0
+    source_width: int = 0
+    source_height: int = 0
+    cell_offset_x: int = 0
+    cell_offset_y: int = 0
+    visible_mask: int | None = None
+
+    @property
+    def layer(self) -> ZLayer:
+        """Return rendering plane derived from :attr:`z_index`."""
+        if self.virtual:
+            return ZLayer.BELOW_TEXT
+        if self.z_index < _Z_BELOW_BG_THRESHOLD:
+            return ZLayer.BELOW_BG
+        if self.z_index < 0:
+            return ZLayer.BELOW_TEXT
+        return ZLayer.ABOVE_TEXT
+
+    def occupies_cell(self, row: int, col: int) -> bool:
+        """Return ``True`` when viewport cell ``(row, col)`` is covered."""
+        if self.virtual:
+            return False
+        if not (
+            self.row <= row < self.row + self.rows
+            and self.col <= col < self.col + self.cols
+        ):
+            return False
+        if self.visible_mask is None:
+            return True
+        bit = (row - self.row) * self.cols + (col - self.col)
+        return bool((self.visible_mask >> bit) & 1)
+
+
+def extract_png_dimensions(header_bytes: bytes) -> tuple[int, int] | None:
+    """Extract ``(width_px, height_px)`` from the first 24 bytes of a PNG stream.
+
+    Parameters
+    ----------
+    header_bytes : bytes
+        Leading uncompressed bytes of a PNG payload (at least 24 bytes).
+
+    Returns
+    -------
+    tuple[int, int] | None
+        ``(width_px, height_px)`` when the PNG signature and ``IHDR`` chunk
+        header are valid and positive, else ``None``.
+    """
+    if len(header_bytes) < 24 or header_bytes[:8] != _PNG_SIGNATURE:
+        return None
+    ihdr_len, chunk_type = struct.unpack(">I4s", header_bytes[8:16])
+    if chunk_type != b"IHDR" or ihdr_len < 13:
+        return None
+    width_px, height_px = struct.unpack(">II", header_bytes[16:24])
+    if width_px <= 0 or height_px <= 0:
+        return None
+    return width_px, height_px
+
+
+def scan_sixel_geometry(
+    payload: bytes,
+    *,
+    max_dimension: int = 10_000,
+) -> tuple[int, int]:
+    """Compute ``(width_px, height_px)`` of a ``SIXEL`` payload in ``O(n)`` time.
+
+    Parameters
+    ----------
+    payload : bytes
+        Raw ``SIXEL`` data stream following ``DCS Ps... q``.
+    max_dimension : int
+        Upper bound applied to raster attributes and ``!Pn`` repeat counts.
+
+    Returns
+    -------
+    tuple[int, int]
+        Clamped ``(width_px, height_px)`` in pixels.
+    """
+    n = len(payload)
+    idx = 0
+    raster_w = 0
+    raster_h = 0
+    cur_x = 0
+    cur_y = 0
+    max_x = 0
+    max_y = 0
+
+    while idx < n:
+        b = payload[idx]
+        if 0x3F <= b <= 0x7E:
+            cur_x = min(max_dimension, cur_x + 1)
+            max_x = max(max_x, cur_x)
+            max_y = max(max_y, min(max_dimension, cur_y + 6))
+            idx += 1
+        elif b == 0x21:  # '!' repeat introducer: !Pn
+            idx += 1
+            rep = 0
+            has_digits = False
+            while idx < n and 0x30 <= payload[idx] <= 0x39:
+                has_digits = True
+                rep = min(max_dimension, rep * 10 + (payload[idx] - 0x30))
+                idx += 1
+            if idx < n and 0x3F <= payload[idx] <= 0x7E:
+                count = max(1, rep) if has_digits else 1
+                cur_x = min(max_dimension, cur_x + count)
+                max_x = max(max_x, cur_x)
+                max_y = max(max_y, min(max_dimension, cur_y + 6))
+                idx += 1
+        elif b == 0x22:  # '"' raster attributes: "Pan;Pad;Ph;Pv
+            idx += 1
+            nums: list[int] = []
+            cur_num = 0
+            while idx < n and (0x30 <= payload[idx] <= 0x39 or payload[idx] == 0x3B):
+                if payload[idx] == 0x3B:
+                    nums.append(cur_num)
+                    cur_num = 0
+                else:
+                    cur_num = min(max_dimension, cur_num * 10 + (payload[idx] - 0x30))
+                idx += 1
+            nums.append(cur_num)
+            if len(nums) >= 4:
+                raster_w = min(max_dimension, nums[2])
+                raster_h = min(max_dimension, nums[3])
+        elif b == 0x23:  # '#' color introducer: #Pc or #Pc;Pu;Px;Py;Pz
+            idx += 1
+            while idx < n and (0x30 <= payload[idx] <= 0x39 or payload[idx] == 0x3B):
+                idx += 1
+        elif b == 0x24:  # '$' graphics carriage return
+            cur_x = 0
+            idx += 1
+        elif b == 0x2D:  # '-' graphics new line
+            cur_x = 0
+            cur_y = min(max_dimension, cur_y + 6)
+            idx += 1
+        else:
+            idx += 1
+
+    return min(max_dimension, max(raster_w, max_x)), min(
+        max_dimension, max(raster_h, max_y)
+    )
+
+
+@dataclass(slots=True)
+class _MutablePlacement:
+    protocol: GraphicsProtocol
+    image_id: int
+    placement_id: int
+    abs_row: int
+    col: int
+    rows: int
+    cols: int
+    z_index: int = 0
+    virtual: bool = False
+    parent_image_id: int = 0
+    parent_placement_id: int = 0
+    source_x: int = 0
+    source_y: int = 0
+    source_width: int = 0
+    source_height: int = 0
+    cell_offset_x: int = 0
+    cell_offset_y: int = 0
+    visible_mask: int | None = None
+
+    def freeze(self, scrolled_total: int) -> ImagePlacement:
+        return ImagePlacement(
+            protocol=self.protocol,
+            image_id=self.image_id,
+            placement_id=self.placement_id,
+            row=self.abs_row - scrolled_total,
+            col=self.col,
+            rows=self.rows,
+            cols=self.cols,
+            abs_row=self.abs_row,
+            z_index=self.z_index,
+            virtual=self.virtual,
+            parent_image_id=self.parent_image_id,
+            parent_placement_id=self.parent_placement_id,
+            source_x=self.source_x,
+            source_y=self.source_y,
+            source_width=self.source_width,
+            source_height=self.source_height,
+            cell_offset_x=self.cell_offset_x,
+            cell_offset_y=self.cell_offset_y,
+            visible_mask=self.visible_mask,
+        )
+
+
+class _Decompressor(t.Protocol):
+    @property
+    def eof(self) -> bool: ...
+
+    @property
+    def unconsumed_tail(self) -> bytes: ...
+
+    def decompress(self, data: bytes, /, max_length: int = 0) -> bytes: ...
+
+    def flush(self, length: int = ..., /) -> bytes: ...
+
+
+@dataclass(slots=True)
+class _PendingKittyUpload:
+    control: dict[str, str]
+    b64_rem: bytes
+    header_buf: bytearray
+    decompressor: _Decompressor | None
+    inflate_cap: int
+    encoded_bytes: int
+    decoded_bytes: int
+    decompressed_bytes: int
+    chunks: int
+    failed_error: str | None = None
+
+
+def _parse_int(control: dict[str, str], key: str, default: int = 0) -> int:
+    raw = control.get(key)
+    if raw is None or not raw:
+        return default
+    try:
+        return int(raw)
+    except ValueError:
+        return default
+
+
+def _kitty_reply(
+    control: dict[str, str],
+    status: str,
+    *,
+    is_error: bool,
+    reply_image_id: int | None = None,
+) -> bytes | None:
+    quiet = _parse_int(control, "q", 0)
+    if quiet == 2 or (quiet == 1 and not is_error):
+        return None
+    client_id = _parse_int(control, "i", 0)
+    client_num = _parse_int(control, "I", 0)
+    if client_id <= 0 and client_num <= 0:
+        return None
+    img_id = reply_image_id if reply_image_id is not None else client_id
+    pid = _parse_int(control, "p", 0)
+    tokens: list[str] = []
+    if img_id > 0:
+        tokens.append(f"i={img_id}")
+    if client_num > 0:
+        tokens.append(f"I={client_num}")
+    if pid > 0:
+        tokens.append(f"p={pid}")
+    head = ",".join(tokens)
+    return f"\x1b_G{head};{status}\x1b\\".encode("ascii")
+
+
+class GraphicsTracker:
+    """Per-screen sans-I/O ``SIXEL`` and Kitty ``APC G`` state machine.
+
+    Attributes
+    ----------
+    has_sixels : bool
+        ``True`` when at least one active or scrollback ``SIXEL`` placement is
+        present, gating cell-overwrite hooks in ``O(1)``.
+    revision : int
+        Monotonic counter incremented whenever stored placements change.
+    """
+
+    __slots__ = (
+        "_images",
+        "_max_dim",
+        "_max_images",
+        "_max_placements",
+        "_next_auto_id",
+        "_pending",
+        "_placements",
+        "has_sixels",
+        "revision",
+    )
+
+    def __init__(
+        self,
+        *,
+        max_images: int = 256,
+        max_placements: int = 1_024,
+        max_image_dimension: int = 10_000,
+    ) -> None:
+        self._max_images = max(1, max_images)
+        self._max_placements = max(1, max_placements)
+        self._max_dim = max(1, max_image_dimension)
+        self._images: collections.OrderedDict[int, ImageMeta] = (
+            collections.OrderedDict()
+        )
+        self._placements: list[_MutablePlacement] = []
+        self._pending: _PendingKittyUpload | None = None
+        self._next_auto_id: int = 0x8000_0001
+        self.has_sixels: bool = False
+        self.revision: int = 0
+
+    def _bump(self) -> None:
+        self.revision += 1
+        self.has_sixels = any(
+            p.protocol == GraphicsProtocol.SIXEL for p in self._placements
+        )
+
+    def clone(self) -> GraphicsTracker:
+        """Return an independent copy of this tracker."""
+        dup = GraphicsTracker(
+            max_images=self._max_images,
+            max_placements=self._max_placements,
+            max_image_dimension=self._max_dim,
+        )
+        dup._images = self._images.copy()
+        dup._placements = [
+            _MutablePlacement(
+                protocol=p.protocol,
+                image_id=p.image_id,
+                placement_id=p.placement_id,
+                abs_row=p.abs_row,
+                col=p.col,
+                rows=p.rows,
+                cols=p.cols,
+                z_index=p.z_index,
+                virtual=p.virtual,
+                parent_image_id=p.parent_image_id,
+                parent_placement_id=p.parent_placement_id,
+                source_x=p.source_x,
+                source_y=p.source_y,
+                source_width=p.source_width,
+                source_height=p.source_height,
+                cell_offset_x=p.cell_offset_x,
+                cell_offset_y=p.cell_offset_y,
+                visible_mask=p.visible_mask,
+            )
+            for p in self._placements
+        ]
+        dup._next_auto_id = self._next_auto_id
+        dup.has_sixels = self.has_sixels
+        dup.revision = self.revision
+        return dup
+
+    @property
+    def images(self) -> dict[int, ImageMeta]:
+        """Return shallow copy of stored :class:`ImageMeta` entries."""
+        return dict(self._images)
+
+    def snapshot_placements(self, scrolled_total: int) -> tuple[ImagePlacement, ...]:
+        """Freeze placements relative to *scrolled_total*."""
+        if not self._placements:
+            return ()
+        return tuple(p.freeze(scrolled_total) for p in self._placements)
+
+    def has_placement_on_row(self, row: int, scrolled_total: int) -> bool:
+        """Return ``True`` when any non-virtual placement covers viewport *row*."""
+        abs_y = scrolled_total + row
+        return any(
+            not p.virtual and p.abs_row <= abs_y < p.abs_row + p.rows
+            for p in self._placements
+        )
+
+    def _store_image(self, meta: ImageMeta) -> None:
+        had_placements = False
+        if meta.image_id in self._images:
+            self._images.move_to_end(meta.image_id)
+            before = len(self._placements)
+            self._placements = [
+                p for p in self._placements if p.image_id != meta.image_id
+            ]
+            had_placements = len(self._placements) != before
+        self._images[meta.image_id] = meta
+        evicted_any = False
+        while len(self._images) > self._max_images:
+            evicted_id, _ = self._images.popitem(last=False)
+            before = len(self._placements)
+            self._placements = [p for p in self._placements if p.image_id != evicted_id]
+            if len(self._placements) != before:
+                evicted_any = True
+        if had_placements or evicted_any:
+            self._prune_orphans()
+            self._bump()
+
+    def _append_placement(self, pl: _MutablePlacement) -> None:
+        if pl.protocol == GraphicsProtocol.KITTY and pl.placement_id > 0:
+            self._placements = [
+                p
+                for p in self._placements
+                if not (
+                    p.protocol == GraphicsProtocol.KITTY
+                    and p.image_id == pl.image_id
+                    and p.placement_id == pl.placement_id
+                )
+            ]
+        self._placements.append(pl)
+        if len(self._placements) > self._max_placements:
+            del self._placements[: len(self._placements) - self._max_placements]
+            self._prune_orphans()
+        self._bump()
+
+    def reset(self) -> None:
+        """Clear all stored images, placements, and in-progress uploads."""
+        if self._images or self._placements or self._pending is not None:
+            self._images.clear()
+            self._placements.clear()
+            self._pending = None
+            self.has_sixels = False
+            self.revision += 1
+
+    def clear_active_screen(self, scrolled_total: int, screen_rows: int) -> None:
+        """Delete non-virtual placements intersecting the active viewport."""
+        if not self._placements:
+            return
+        top_abs = scrolled_total
+        bot_abs = scrolled_total + screen_rows
+        kept = [
+            p
+            for p in self._placements
+            if p.virtual or p.abs_row + p.rows <= top_abs or p.abs_row >= bot_abs
+        ]
+        if len(kept) != len(self._placements):
+            self._placements = kept
+            self._prune_orphans()
+            self._bump()
+
+    def clear_history(self, scrolled_total: int) -> None:
+        """Delete placements located completely inside scrollback (``ED 3``)."""
+        if not self._placements:
+            return
+        kept = [
+            p
+            for p in self._placements
+            if p.virtual or p.abs_row + p.rows > scrolled_total
+        ]
+        if len(kept) != len(self._placements):
+            self._placements = kept
+            self._prune_orphans()
+            self._bump()
+
+    def reap_evicted_history(self, min_retained_abs_row: int) -> None:
+        """Reap non-virtual placements scrolled past *min_retained_abs_row*."""
+        if not self._placements:
+            return
+        kept = [
+            p
+            for p in self._placements
+            if p.virtual or p.abs_row + p.rows > min_retained_abs_row
+        ]
+        if len(kept) != len(self._placements):
+            self._placements = kept
+            self._prune_orphans()
+            self._bump()
+
+    def on_non_reflow_resize(
+        self,
+        *,
+        top_drop_without_history: int,
+        new_rows: int,
+        new_cols: int,
+        scrolled_total: int,
+    ) -> None:
+        """Adjust placements when a non-reflow ``resize()`` drops or clips rows."""
+        if not self._placements:
+            return
+        changed = False
+        kept: list[_MutablePlacement] = []
+        max_abs = scrolled_total + new_rows
+        for p in self._placements:
+            if p.virtual:
+                kept.append(p)
+                continue
+            if top_drop_without_history > 0:
+                p.abs_row -= top_drop_without_history
+                changed = True
+            if p.abs_row + p.rows <= scrolled_total or p.abs_row >= max_abs:
+                changed = True
+                continue
+            if p.col >= new_cols:
+                changed = True
+                continue
+            kept.append(p)
+        if changed:
+            self._placements = kept
+            self._prune_orphans()
+            self._bump()
+
+    def erase_sixel_rect(
+        self,
+        *,
+        row: int,
+        col: int,
+        rows: int,
+        cols: int,
+        scrolled_total: int,
+        policy: SixelErasePolicy,
+    ) -> None:
+        """Clip or remove ``SIXEL`` placements intersected by a cell edit/erase."""
+        if not self.has_sixels or rows <= 0 or cols <= 0:
+            return
+        r0 = scrolled_total + row
+        r1 = r0 + rows
+        c0 = col
+        c1 = col + cols
+        changed = False
+        kept: list[_MutablePlacement] = []
+        for p in self._placements:
+            if p.protocol != GraphicsProtocol.SIXEL:
+                kept.append(p)
+                continue
+            pr0, pr1 = p.abs_row, p.abs_row + p.rows
+            pc0, pc1 = p.col, p.col + p.cols
+            if r1 <= pr0 or r0 >= pr1 or c1 <= pc0 or c0 >= pc1:
+                kept.append(p)
+                continue
+            if policy == "whole_image" or p.rows * p.cols > _MAX_MASK_CELLS:
+                changed = True
+                continue
+            prev_mask = p.visible_mask
+            if prev_mask is None:
+                prev_mask = (1 << (p.rows * p.cols)) - 1
+            mask = prev_mask
+            ir0 = max(r0, pr0) - pr0
+            ir1 = min(r1, pr1) - pr0
+            ic0 = max(c0, pc0) - pc0
+            ic1 = min(c1, pc1) - pc0
+            if ic0 == 0 and ic1 == p.cols:
+                span = (ir1 - ir0) * p.cols
+                mask &= ~(((1 << span) - 1) << (ir0 * p.cols))
+            else:
+                row_clear = ((1 << (ic1 - ic0)) - 1) << ic0
+                for rr in range(ir0, ir1):
+                    mask &= ~(row_clear << (rr * p.cols))
+            if mask == 0:
+                changed = True
+                continue
+            if mask != prev_mask:
+                p.visible_mask = mask
+                changed = True
+            kept.append(p)
+        if changed:
+            self._placements = kept
+            self._bump()
+
+    def on_region_scroll(
+        self,
+        *,
+        top: int,
+        bottom: int,
+        left: int,
+        right: int,
+        delta_rows: int,
+        is_scroll: bool,
+        scrolled_total: int,
+        cell_height_px: int,
+        history_advanced: int = 0,
+    ) -> None:
+        """Adjust placements for bounded margin scroll or ``IL``/``DL``."""
+        if not self._placements or delta_rows == 0:
+            return
+        abs_top = scrolled_total + top
+        abs_bot = scrolled_total + bottom
+        changed = False
+        kept: list[_MutablePlacement] = []
+
+        for p in self._placements:
+            if p.virtual:
+                kept.append(p)
+                continue
+            p_top = p.abs_row
+            p_bot = p.abs_row + p.rows - 1
+            p_left = p.col
+            p_right = p.col + p.cols - 1
+
+            inside = (
+                p_top >= abs_top
+                and p_bot <= abs_bot
+                and p_left >= left
+                and p_right <= right
+            )
+
+            if p.protocol == GraphicsProtocol.KITTY or p.parent_image_id > 0:
+                if not is_scroll or not inside:
+                    if history_advanced > 0 and p_top >= scrolled_total:
+                        p.abs_row += history_advanced
+                        changed = True
+                    kept.append(p)
+                    continue
+                new_top = p_top + delta_rows + history_advanced
+                new_bot = p_bot + delta_rows + history_advanced
+                eff_top = abs_top + history_advanced
+                eff_bot = abs_bot + history_advanced
+                clip_top = max(0, eff_top - new_top)
+                clip_bot = max(0, new_bot - eff_bot)
+                if clip_top + clip_bot >= p.rows:
+                    changed = True
+                    continue
+                if clip_top > 0:
+                    crop_px = (
+                        (p.source_height * clip_top) // p.rows
+                        if p.rows > 0
+                        else cell_height_px * clip_top
+                    )
+                    p.source_y += crop_px
+                    p.source_height = max(0, p.source_height - crop_px)
+                    p.rows -= clip_top
+                    new_top = eff_top
+                    if p.source_height <= 0 or p.rows <= 0:
+                        changed = True
+                        continue
+                if clip_bot > 0:
+                    crop_px = (
+                        (p.source_height * clip_bot) // p.rows
+                        if p.rows > 0
+                        else cell_height_px * clip_bot
+                    )
+                    p.source_height = max(0, p.source_height - crop_px)
+                    p.rows -= clip_bot
+                    if p.source_height <= 0 or p.rows <= 0:
+                        changed = True
+                        continue
+                p.abs_row = new_top
+                changed = True
+                kept.append(p)
+            else:
+                if (
+                    p_bot < abs_top
+                    or p_top > abs_bot
+                    or p_right < left
+                    or p_left > right
+                ):
+                    if history_advanced > 0 and p_top > abs_bot:
+                        p.abs_row += history_advanced
+                        changed = True
+                    kept.append(p)
+                    continue
+                if not inside:
+                    if history_advanced > 0 and p_top >= scrolled_total:
+                        p.abs_row += history_advanced
+                        changed = True
+                    if p.rows * p.cols <= _MAX_MASK_CELLS:
+                        prev_mask = (
+                            (1 << (p.rows * p.cols)) - 1
+                            if p.visible_mask is None
+                            else p.visible_mask
+                        )
+                        ir0 = max(p_top, abs_top + history_advanced) - p.abs_row
+                        ir1 = min(p_bot, abs_bot + history_advanced) - p.abs_row + 1
+                        ic0 = max(p_left, left) - p_left
+                        ic1 = min(p_right, right) - p_left + 1
+                        if ir0 < ir1 and ic0 < ic1:
+                            row_clear = ((1 << (ic1 - ic0)) - 1) << ic0
+                            mask = prev_mask
+                            for rr in range(ir0, ir1):
+                                mask &= ~(row_clear << (rr * p.cols))
+                            if mask == 0:
+                                changed = True
+                                continue
+                            if mask != prev_mask:
+                                p.visible_mask = mask
+                                changed = True
+                    kept.append(p)
+                    continue
+
+                eff_top = abs_top + history_advanced
+                eff_bot = abs_bot + history_advanced
+                new_top = p_top + delta_rows + history_advanced
+                new_bot = p_bot + delta_rows + history_advanced
+                clip_top = max(0, eff_top - new_top)
+                clip_bot = max(0, new_bot - eff_bot)
+                if clip_top + clip_bot >= p.rows:
+                    changed = True
+                    continue
+                keep_rows = p.rows - clip_top - clip_bot
+                if (
+                    p.visible_mask is not None
+                    and (clip_top > 0 or clip_bot > 0)
+                    and keep_rows * p.cols <= _MAX_MASK_CELLS
+                ):
+                    shifted = p.visible_mask >> (clip_top * p.cols)
+                    p.visible_mask = shifted & ((1 << (keep_rows * p.cols)) - 1)
+                    if p.visible_mask == 0:
+                        changed = True
+                        continue
+                p.rows = keep_rows
+                p.abs_row = max(eff_top, new_top)
+                changed = True
+                kept.append(p)
+
+        if changed:
+            self._placements = kept
+            self._prune_orphans()
+            self._bump()
+
+    def prepare_sixel(
+        self,
+        payload: bytes,
+        *,
+        col: int,
+        screen_cols: int,
+        cell_width_px: int,
+        cell_height_px: int,
+    ) -> tuple[int, int, int, int] | None:
+        """Scan ``SIXEL`` geometry into ``(width_px, height_px, rows, cols)``."""
+        w_px, h_px = scan_sixel_geometry(payload, max_dimension=self._max_dim)
+        if w_px <= 0 or h_px <= 0:
+            return None
+        cw = max(1, cell_width_px)
+        ch = max(1, cell_height_px)
+        cols = min(max(1, screen_cols - col), max(1, (w_px + cw - 1) // cw))
+        rows = max(1, (h_px + ch - 1) // ch)
+        return w_px, h_px, rows, cols
+
+    def commit_sixel(
+        self,
+        *,
+        payload_len: int,
+        width_px: int,
+        height_px: int,
+        row: int,
+        col: int,
+        rows: int,
+        cols: int,
+        scrolled_total: int,
+    ) -> None:
+        """Record a scanned ``SIXEL`` image and placement at post-scroll *row*."""
+        eff_row = row
+        eff_rows = rows
+        if eff_row < 0 and scrolled_total == 0:
+            clip = -eff_row
+            if clip >= eff_rows:
+                return
+            eff_rows -= clip
+            eff_row = 0
+        img_id = self._next_auto_id
+        self._next_auto_id += 1
+        meta = ImageMeta(
+            protocol=GraphicsProtocol.SIXEL,
+            image_id=img_id,
+            width_px=width_px,
+            height_px=height_px,
+            format_code=0,
+            byte_len=payload_len,
+        )
+        self._store_image(meta)
+        self._append_placement(
+            _MutablePlacement(
+                protocol=GraphicsProtocol.SIXEL,
+                image_id=img_id,
+                placement_id=0,
+                abs_row=scrolled_total + eff_row,
+                col=col,
+                rows=eff_rows,
+                cols=cols,
+                source_width=width_px,
+                source_height=height_px,
+            ),
+        )
+
+    def _drain_decompressor(self, up: _PendingKittyUpload, data: bytes) -> None:
+        dec = up.decompressor
+        if dec is None:
+            need = 24 - len(up.header_buf)
+            if need > 0:
+                up.header_buf.extend(data[:need])
+            return
+        buf = data
+        while buf and up.decompressed_bytes < up.inflate_cap:
+            step = min(_ZLIB_STEP_BYTES, up.inflate_cap - up.decompressed_bytes)
+            try:
+                out = dec.decompress(buf, step)
+            except zlib.error:
+                up.failed_error = "EINVAL:invalid zlib stream"
+                return
+            if not out and not dec.eof:
+                break
+            need = 24 - len(up.header_buf)
+            if need > 0:
+                up.header_buf.extend(out[:need])
+            up.decompressed_bytes += len(out)
+            buf = dec.unconsumed_tail
+            if dec.eof:
+                break
+
+    def _feed_upload_chunk(self, up: _PendingKittyUpload, payload: bytes) -> None:
+        if up.failed_error is not None:
+            return
+        if up.encoded_bytes + len(payload) > _MAX_UPLOAD_BYTES:
+            up.failed_error = "ENOMEM:upload exceeds byte limit"
+            return
+        cleaned = b"".join(payload.split())
+        if not cleaned:
+            return
+        up.encoded_bytes += len(cleaned)
+        combined = up.b64_rem + cleaned
+        rem_len = len(combined) % 4
+        if rem_len:
+            decode_part = combined[:-rem_len]
+            up.b64_rem = combined[-rem_len:]
+        else:
+            decode_part = combined
+            up.b64_rem = b""
+        if not decode_part:
+            return
+        try:
+            raw = base64.b64decode(decode_part, validate=True)
+        except binascii.Error:
+            up.failed_error = "EINVAL:invalid base64 payload"
+            return
+        up.decoded_bytes += len(raw)
+        self._drain_decompressor(up, raw)
+
+    def _finalize_upload(self, up: _PendingKittyUpload) -> None:
+        if up.failed_error is not None:
+            return
+        if up.b64_rem:
+            padded = up.b64_rem + b"=" * ((4 - len(up.b64_rem)) % 4)
+            try:
+                raw = base64.b64decode(padded, validate=True)
+            except binascii.Error:
+                up.failed_error = "EINVAL:invalid base64 tail"
+                return
+            up.decoded_bytes += len(raw)
+            self._drain_decompressor(up, raw)
+            if up.failed_error is not None:
+                return
+        if up.decompressor is not None and up.decompressed_bytes < up.inflate_cap:
+            try:
+                tail = up.decompressor.flush(_ZLIB_STEP_BYTES)
+            except zlib.error:
+                up.failed_error = "EINVAL:invalid zlib stream"
+                return
+            need = 24 - len(up.header_buf)
+            if need > 0:
+                up.header_buf.extend(tail[:need])
+            up.decompressed_bytes += len(tail)
+            if not up.decompressor.eof and up.decompressed_bytes < up.inflate_cap:
+                up.failed_error = "EINVAL:truncated zlib stream"
+
+    def handle_kitty(
+        self,
+        control: dict[str, str],
+        payload: bytes,
+        *,
+        cursor_row: int,
+        cursor_col: int,
+        screen_rows: int,
+        screen_cols: int,
+        scrolled_total_getter: collections.abc.Callable[[], int] | None = None,
+        scrolled_total: int = 0,
+        cell_width_px: int = 8,
+        cell_height_px: int = 16,
+        advance_cursor: collections.abc.Callable[[int, int], int] | None = None,
+    ) -> bytes | None:
+        """Process one Kitty ``APC G`` packet and return optional reply bytes.
+
+        Parameters
+        ----------
+        control : dict[str, str]
+            Parsed ``key=value`` control header pairs.
+        payload : bytes
+            Base64 payload segment following ``;``.
+        cursor_row : int
+            Zero-based cursor row at packet arrival.
+        cursor_col : int
+            Zero-based cursor column at packet arrival.
+        screen_rows : int
+            Active screen height in rows.
+        screen_cols : int
+            Active screen width in columns.
+        scrolled_total_getter : collections.abc.Callable[[], int] | None
+            Optional callback returning live ``scrolled_total`` after
+            *advance_cursor* runs.
+        scrolled_total : int
+            Fallback ``scrolled_total`` when *scrolled_total_getter* is ``None``.
+        cell_width_px : int
+            Nominal cell width in pixels.
+        cell_height_px : int
+            Nominal cell height in pixels.
+        advance_cursor : collections.abc.Callable[[int, int], int] | None
+            Callback invoked with ``(rows, cols)`` prior to committing a
+            cursor-moving ``C=0`` placement, returning the post-scroll anchor
+            row.
+
+        Returns
+        -------
+        bytes | None
+            Sans-I/O ``APC G`` response packet, or ``None`` when silent.
+        """
+        explicit_action = control.get("a")
+        more = _parse_int(control, "m", 0) == 1
+        cur_scrolled = (
+            scrolled_total_getter()
+            if scrolled_total_getter is not None
+            else scrolled_total
+        )
+
+        if _parse_int(control, "i", 0) > 0 and _parse_int(control, "I", 0) > 0:
+            self._pending = None
+            return _kitty_reply(
+                control, "EINVAL:cannot specify both i and I", is_error=True
+            )
+
+        if explicit_action == "d":
+            self._pending = None
+            self._handle_kitty_delete(
+                control,
+                cursor_row=cursor_row,
+                cursor_col=cursor_col,
+                screen_rows=screen_rows,
+                scrolled_total=cur_scrolled,
+            )
+            return None
+
+        if self._pending is not None:
+            up = self._pending
+            in_id = _parse_int(control, "i", 0)
+            up_id = _parse_int(up.control, "i", 0)
+            stale = (
+                explicit_action in ("q", "p")
+                or ("t" in control and control.get("t", "d") != "d")
+                or (in_id > 0 and up_id > 0 and in_id != up_id)
+            )
+            if stale:
+                self._pending = None
+            elif explicit_action in (None, "t", "T"):
+                if _parse_int(control, "q", 0) >= 1:
+                    up.control["q"] = control["q"]
+                for k, v in control.items():
+                    if k not in ("m", "q"):
+                        up.control.setdefault(k, v)
+                up.chunks += 1
+                if up.chunks > _MAX_UPLOAD_CHUNKS:
+                    self._pending = None
+                    return _kitty_reply(
+                        up.control, "ENOMEM:too many chunks", is_error=True
+                    )
+                self._feed_upload_chunk(up, payload)
+                if more:
+                    return None
+                self._pending = None
+                self._finalize_upload(up)
+                return self._complete_kitty_upload(
+                    up,
+                    cursor_row=cursor_row,
+                    cursor_col=cursor_col,
+                    screen_cols=screen_cols,
+                    scrolled_total_getter=scrolled_total_getter,
+                    scrolled_total=cur_scrolled,
+                    cell_width_px=cell_width_px,
+                    cell_height_px=cell_height_px,
+                    advance_cursor=advance_cursor,
+                )
+
+        action = explicit_action or "t"
+        if action in ("t", "T", "q"):
+            if action == "q" and _parse_int(control, "i", 0) <= 0:
+                if _parse_int(control, "I", 0) > 0:
+                    return _kitty_reply(
+                        control, "EINVAL:image ID required for query", is_error=True
+                    )
+                return None
+            medium = control.get("t", "d")
+            if medium != "d":
+                self._pending = None
+                return _kitty_reply(
+                    control,
+                    f"EINVAL:unsupported transmission medium {medium!r}",
+                    is_error=True,
+                )
+            comp = control.get("o", "")
+            if comp not in ("", "z"):
+                return _kitty_reply(
+                    control,
+                    f"EINVAL:unsupported compression {comp!r}",
+                    is_error=True,
+                )
+            fmt = _parse_int(control, "f", 32)
+            if fmt == 100:
+                inflate_cap = _MAX_ZLIB_INFLATE_BYTES
+            else:
+                w_decl = min(self._max_dim + 1, max(0, _parse_int(control, "s", 0)))
+                h_decl = min(self._max_dim + 1, max(0, _parse_int(control, "v", 0)))
+                bpp = max(1, fmt // 8)
+                inflate_cap = min(
+                    _MAX_ZLIB_INFLATE_BYTES, max(24, w_decl * h_decl * bpp)
+                )
+            up = _PendingKittyUpload(
+                control=dict(control),
+                b64_rem=b"",
+                header_buf=bytearray(),
+                decompressor=zlib.decompressobj() if comp == "z" else None,
+                inflate_cap=inflate_cap,
+                encoded_bytes=0,
+                decoded_bytes=0,
+                decompressed_bytes=0,
+                chunks=1,
+            )
+            self._feed_upload_chunk(up, payload)
+            if more:
+                self._pending = up
+                return None
+            self._finalize_upload(up)
+            return self._complete_kitty_upload(
+                up,
+                cursor_row=cursor_row,
+                cursor_col=cursor_col,
+                screen_cols=screen_cols,
+                scrolled_total_getter=scrolled_total_getter,
+                scrolled_total=cur_scrolled,
+                cell_width_px=cell_width_px,
+                cell_height_px=cell_height_px,
+                advance_cursor=advance_cursor,
+            )
+
+        if action == "p":
+            return self._place_kitty_image(
+                control,
+                cursor_row=cursor_row,
+                cursor_col=cursor_col,
+                screen_cols=screen_cols,
+                scrolled_total_getter=scrolled_total_getter,
+                scrolled_total=cur_scrolled,
+                cell_width_px=cell_width_px,
+                cell_height_px=cell_height_px,
+                advance_cursor=advance_cursor,
+            )
+
+        return None
+
+    def _complete_kitty_upload(
+        self,
+        up: _PendingKittyUpload,
+        *,
+        cursor_row: int,
+        cursor_col: int,
+        screen_cols: int,
+        scrolled_total_getter: collections.abc.Callable[[], int] | None,
+        scrolled_total: int,
+        cell_width_px: int,
+        cell_height_px: int,
+        advance_cursor: collections.abc.Callable[[int, int], int] | None,
+    ) -> bytes | None:
+        ctrl = up.control
+        if up.failed_error is not None:
+            return _kitty_reply(ctrl, up.failed_error, is_error=True)
+
+        fmt = _parse_int(ctrl, "f", 32)
+        if fmt == 100:
+            dims = extract_png_dimensions(bytes(up.header_buf))
+            if dims is None:
+                return _kitty_reply(ctrl, "EINVAL:invalid PNG header", is_error=True)
+            w_px, h_px = dims
+        elif fmt in (8, 16, 24, 32):
+            w_px = _parse_int(ctrl, "s", 0)
+            h_px = _parse_int(ctrl, "v", 0)
+            if w_px <= 0 or h_px <= 0:
+                return _kitty_reply(
+                    ctrl, "EINVAL:missing raw s/v dimensions", is_error=True
+                )
+            if w_px > self._max_dim or h_px > self._max_dim:
+                return _kitty_reply(
+                    ctrl, "EINVAL:image dimensions exceed limit", is_error=True
+                )
+            expected = w_px * h_px * (fmt // 8)
+            if ctrl.get("o") == "z":
+                req = min(expected, _MAX_ZLIB_INFLATE_BYTES)
+                if up.decompressed_bytes < req:
+                    return _kitty_reply(
+                        ctrl, "EINVAL:truncated compressed payload", is_error=True
+                    )
+            elif up.decoded_bytes < expected:
+                return _kitty_reply(ctrl, "EINVAL:truncated raw payload", is_error=True)
+        else:
+            return _kitty_reply(
+                ctrl, f"EINVAL:unsupported format f={fmt}", is_error=True
+            )
+
+        if w_px > self._max_dim or h_px > self._max_dim:
+            return _kitty_reply(
+                ctrl, "EINVAL:image dimensions exceed limit", is_error=True
+            )
+
+        action = ctrl.get("a", "t")
+        if action == "q":
+            return _kitty_reply(ctrl, "OK", is_error=False)
+
+        client_id = _parse_int(ctrl, "i", 0)
+        client_num = _parse_int(ctrl, "I", 0)
+        if client_id > 0:
+            img_id = client_id
+        else:
+            img_id = self._next_auto_id
+            self._next_auto_id += 1
+        meta = ImageMeta(
+            protocol=GraphicsProtocol.KITTY,
+            image_id=img_id,
+            image_number=client_num,
+            width_px=w_px,
+            height_px=h_px,
+            format_code=fmt,
+            compressed=ctrl.get("o") == "z",
+            byte_len=up.encoded_bytes,
+        )
+        self._store_image(meta)
+        reply_id = img_id if (client_id > 0 or client_num > 0) else None
+        if action == "T":
+            return self._place_kitty_image(
+                ctrl,
+                cursor_row=cursor_row,
+                cursor_col=cursor_col,
+                screen_cols=screen_cols,
+                scrolled_total_getter=scrolled_total_getter,
+                scrolled_total=scrolled_total,
+                cell_width_px=cell_width_px,
+                cell_height_px=cell_height_px,
+                advance_cursor=advance_cursor,
+                target_meta=meta,
+                reply_image_id=reply_id,
+            )
+        return _kitty_reply(ctrl, "OK", is_error=False, reply_image_id=reply_id)
+
+    def _resolve_kitty_image(self, control: dict[str, str]) -> ImageMeta | None:
+        img_id = _parse_int(control, "i", 0)
+        if img_id > 0:
+            return self._images.get(img_id)
+        img_num = _parse_int(control, "I", 0)
+        if img_num > 0:
+            for meta in reversed(self._images.values()):
+                if meta.image_number == img_num:
+                    return meta
+        return None
+
+    def _find_parent_placement(
+        self,
+        parent_id: int,
+        parent_pid: int,
+    ) -> _MutablePlacement | None:
+        for p in reversed(self._placements):
+            if p.image_id == parent_id and (
+                parent_pid == 0 or p.placement_id == parent_pid
+            ):
+                return p
+        return None
+
+    def _validate_parent_chain(
+        self,
+        child_img_id: int,
+        child_pid: int,
+        parent: _MutablePlacement,
+    ) -> str | None:
+        if (
+            child_img_id == parent.image_id
+            and child_pid == parent.placement_id
+            and (child_pid > 0 or parent.placement_id == 0)
+        ):
+            return "ECYCLE:self-parented placement"
+        cur: _MutablePlacement | None = parent
+        depth = 1
+        while cur is not None and cur.parent_image_id > 0:
+            if depth >= _MAX_PARENT_DEPTH:
+                return "ETOODEEP:relative placement chain exceeds limit"
+            if cur.parent_image_id == child_img_id and (
+                cur.parent_placement_id in (0, child_pid)
+            ):
+                return "ECYCLE:cyclic relative placement"
+            cur = self._find_parent_placement(
+                cur.parent_image_id, cur.parent_placement_id
+            )
+            depth += 1
+        return None
+
+    def _place_kitty_image(
+        self,
+        control: dict[str, str],
+        *,
+        cursor_row: int,
+        cursor_col: int,
+        screen_cols: int,
+        scrolled_total_getter: collections.abc.Callable[[], int] | None,
+        scrolled_total: int,
+        cell_width_px: int,
+        cell_height_px: int,
+        advance_cursor: collections.abc.Callable[[int, int], int] | None,
+        target_meta: ImageMeta | None = None,
+        reply_image_id: int | None = None,
+    ) -> bytes | None:
+        meta = (
+            target_meta
+            if target_meta is not None
+            else self._resolve_kitty_image(control)
+        )
+        if meta is None:
+            return _kitty_reply(control, "ENOENT:image not found", is_error=True)
+
+        virtual = _parse_int(control, "U", 0) == 1
+        parent_id = _parse_int(control, "P", 0)
+        parent_pid = _parse_int(control, "Q", 0)
+        pid = _parse_int(control, "p", 0)
+        if virtual and parent_id > 0:
+            return _kitty_reply(
+                control,
+                "EINVAL:virtual placement cannot be relative",
+                is_error=True,
+            )
+
+        parent_pl: _MutablePlacement | None = None
+        if parent_id > 0:
+            if parent_id not in self._images:
+                return _kitty_reply(
+                    control, "ENOPARENT:parent image not found", is_error=True
+                )
+            parent_pl = self._find_parent_placement(parent_id, parent_pid)
+            if parent_pl is None or parent_pl.virtual:
+                return _kitty_reply(
+                    control, "ENOPARENT:parent placement not found", is_error=True
+                )
+            chain_err = self._validate_parent_chain(meta.image_id, pid, parent_pl)
+            if chain_err is not None:
+                return _kitty_reply(control, chain_err, is_error=True)
+
+        cw = max(1, cell_width_px)
+        ch = max(1, cell_height_px)
+        src_x = min(meta.width_px, max(0, _parse_int(control, "x", 0)))
+        src_y = min(meta.height_px, max(0, _parse_int(control, "y", 0)))
+        req_w = max(0, _parse_int(control, "w", 0))
+        req_h = max(0, _parse_int(control, "h", 0))
+        src_w = (
+            min(req_w, meta.width_px - src_x) if req_w > 0 else (meta.width_px - src_x)
+        )
+        src_h = (
+            min(req_h, meta.height_px - src_y)
+            if req_h > 0
+            else (meta.height_px - src_y)
+        )
+        off_x = min(cw - 1, max(0, _parse_int(control, "X", 0)))
+        off_y = min(ch - 1, max(0, _parse_int(control, "Y", 0)))
+        req_c = max(0, _parse_int(control, "c", 0))
+        req_r = max(0, _parse_int(control, "r", 0))
+
+        if req_c > 0 and req_r > 0:
+            cols, rows = req_c, req_r
+        elif req_c > 0:
+            cols = req_c
+            w_px = max(1, req_c * cw - off_x)
+            h_px = max(1, (w_px * max(1, src_h) + max(1, src_w) - 1) // max(1, src_w))
+            rows = max(1, (h_px + off_y + ch - 1) // ch)
+        elif req_r > 0:
+            rows = req_r
+            h_px = max(1, req_r * ch - off_y)
+            w_px = max(1, (h_px * max(1, src_w) + max(1, src_h) - 1) // max(1, src_h))
+            cols = max(1, (w_px + off_x + cw - 1) // cw)
+        else:
+            cols = max(1, (max(1, src_w) + off_x + cw - 1) // cw)
+            rows = max(1, (max(1, src_h) + off_y + ch - 1) // ch)
+
+        cols = min(max(1, screen_cols * 4), cols)
+        rows = min(max(1, self._max_dim), rows)
+        z_idx = _parse_int(control, "z", 0)
+        move_cursor = (
+            not virtual and parent_id == 0 and _parse_int(control, "C", 0) == 0
+        )
+
+        if parent_pl is not None:
+            abs_r = parent_pl.abs_row + _parse_int(control, "V", 0)
+            col_pos = max(
+                0, min(screen_cols - 1, parent_pl.col + _parse_int(control, "H", 0))
+            )
+        else:
+            anchor_r = cursor_row
+            if move_cursor and advance_cursor is not None:
+                anchor_r = advance_cursor(rows, cols)
+            post_scrolled = (
+                scrolled_total_getter()
+                if scrolled_total_getter is not None
+                else scrolled_total
+            )
+            abs_r = post_scrolled + anchor_r
+            col_pos = cursor_col
+
+        self._append_placement(
+            _MutablePlacement(
+                protocol=GraphicsProtocol.KITTY,
+                image_id=meta.image_id,
+                placement_id=pid,
+                abs_row=abs_r,
+                col=col_pos,
+                rows=rows,
+                cols=cols,
+                z_index=z_idx,
+                virtual=virtual,
+                parent_image_id=parent_id,
+                parent_placement_id=parent_pid,
+                source_x=src_x,
+                source_y=src_y,
+                source_width=src_w,
+                source_height=src_h,
+                cell_offset_x=off_x,
+                cell_offset_y=off_y,
+            ),
+        )
+        eff_reply_id = (
+            reply_image_id
+            if target_meta is not None
+            else (
+                meta.image_id
+                if (_parse_int(control, "i", 0) > 0 or _parse_int(control, "I", 0) > 0)
+                else None
+            )
+        )
+        return _kitty_reply(control, "OK", is_error=False, reply_image_id=eff_reply_id)
+
+    def _prune_orphans(self, *, free_images: bool = False) -> None:
+        if not self._placements:
+            return
+        children_by_key: dict[tuple[int, int], list[int]] = {}
+        children_by_img: dict[int, list[int]] = {}
+        reachable: list[bool] = [False] * len(self._placements)
+        queue: collections.deque[int] = collections.deque()
+
+        for idx, p in enumerate(self._placements):
+            if p.parent_image_id <= 0:
+                reachable[idx] = True
+                queue.append(idx)
+            elif p.parent_placement_id > 0:
+                children_by_key.setdefault(
+                    (p.parent_image_id, p.parent_placement_id), []
+                ).append(idx)
+            else:
+                children_by_img.setdefault(p.parent_image_id, []).append(idx)
+
+        if len(queue) == len(self._placements):
+            return
+
+        while queue:
+            cur_idx = queue.popleft()
+            cur_p = self._placements[cur_idx]
+            for child_idx in children_by_key.get(
+                (cur_p.image_id, cur_p.placement_id), ()
+            ):
+                if not reachable[child_idx]:
+                    reachable[child_idx] = True
+                    queue.append(child_idx)
+            for child_idx in children_by_img.get(cur_p.image_id, ()):
+                if not reachable[child_idx]:
+                    reachable[child_idx] = True
+                    queue.append(child_idx)
+
+        kept: list[_MutablePlacement] = []
+        removed_ids: set[int] = set()
+        for idx, p in enumerate(self._placements):
+            if reachable[idx]:
+                kept.append(p)
+            else:
+                removed_ids.add(p.image_id)
+        self._placements = kept
+        if free_images and removed_ids:
+            still_used = {p.image_id for p in self._placements}
+            for rid in removed_ids - still_used:
+                self._images.pop(rid, None)
+
+    def _handle_kitty_delete(
+        self,
+        control: dict[str, str],
+        *,
+        cursor_row: int,
+        cursor_col: int,
+        screen_rows: int,
+        scrolled_total: int,
+    ) -> None:
+        raw_sel = control.get("d", "a") or "a"
+        sel = raw_sel[0]
+        free_images = sel.isupper()
+        kind = sel.lower()
+        pid_filter = _parse_int(control, "p", 0)
+        top_abs = scrolled_total
+        bot_abs = scrolled_total + screen_rows
+
+        candidates: set[int] = set()
+        kept: list[_MutablePlacement] = []
+
+        if kind == "a":
+            for p in self._placements:
+                if (
+                    p.virtual
+                    or p.parent_image_id > 0
+                    or p.abs_row + p.rows <= top_abs
+                    or p.abs_row >= bot_abs
+                ):
+                    kept.append(p)
+                else:
+                    candidates.add(p.image_id)
+        elif kind in ("i", "n"):
+            target = (
+                _parse_int(control, "i", 0)
+                if kind == "i"
+                else (
+                    meta.image_id
+                    if (meta := self._resolve_kitty_image(control)) is not None
+                    else 0
+                )
+            )
+            if target > 0 and pid_filter == 0:
+                candidates.add(target)
+            for p in self._placements:
+                if p.image_id == target and (
+                    pid_filter == 0 or p.placement_id == pid_filter
+                ):
+                    candidates.add(p.image_id)
+                else:
+                    kept.append(p)
+        elif kind == "r":
+            lo = _parse_int(control, "x", 0)
+            hi = _parse_int(control, "y", 0)
+            for p in self._placements:
+                if lo <= p.image_id <= hi:
+                    candidates.add(p.image_id)
+                else:
+                    kept.append(p)
+            if free_images:
+                for img_id in [k for k in self._images if lo <= k <= hi]:
+                    candidates.add(img_id)
+        elif kind in ("c", "p", "q", "x", "y", "z"):
+            cell_c = cursor_col if kind == "c" else (_parse_int(control, "x", 0) - 1)
+            cell_r = cursor_row if kind == "c" else (_parse_int(control, "y", 0) - 1)
+            if kind in ("p", "q", "x") and cell_c < 0:
+                return
+            if kind in ("p", "q", "y") and not (0 <= cell_r < screen_rows):
+                return
+            abs_cell_r = scrolled_total + cell_r
+            z_target = _parse_int(control, "z", 0)
+            for p in self._placements:
+                if p.virtual:
+                    kept.append(p)
+                    continue
+                if kind == "z":
+                    match = p.z_index == z_target
+                elif kind in ("c", "p"):
+                    match = (
+                        p.abs_row <= abs_cell_r < p.abs_row + p.rows
+                        and p.col <= cell_c < p.col + p.cols
+                    )
+                elif kind == "q":
+                    match = (
+                        p.z_index == z_target
+                        and p.abs_row <= abs_cell_r < p.abs_row + p.rows
+                        and p.col <= cell_c < p.col + p.cols
+                    )
+                elif kind == "x":
+                    match = (
+                        p.abs_row + p.rows > top_abs
+                        and p.abs_row < bot_abs
+                        and p.col <= cell_c < p.col + p.cols
+                    )
+                else:  # kind == "y"
+                    match = p.abs_row <= abs_cell_r < p.abs_row + p.rows
+                if match:
+                    candidates.add(p.image_id)
+                else:
+                    kept.append(p)
+        else:
+            return
+
+        changed = len(kept) != len(self._placements)
+        self._placements = kept
+        self._prune_orphans(free_images=free_images)
+        if free_images and candidates:
+            still_used = {p.image_id for p in self._placements}
+            for cid in candidates - still_used:
+                if self._images.pop(cid, None) is not None:
+                    changed = True
+        if changed:
+            self._bump()
+
+
+__all__ = [
+    "GraphicsProtocol",
+    "GraphicsTracker",
+    "ImageMeta",
+    "ImagePlacement",
+    "ZLayer",
+    "extract_png_dimensions",
+    "scan_sixel_geometry",
+]

From e85c42c19bd0902f616769204087ea116b1c9c21 Mon Sep 17 00:00:00 2001
From: Tony Narlock 
Date: Sun, 22 Nov 2026 14:14:47 -0600
Subject: [PATCH 21/29] terminal(feat[sync]): Add deltas and graphics hooks
 (#13)

why: Polling consumers need non-destructive multi-consumer screen deltas,
and print/erase/scroll handlers must preserve wide-wrap invariants, O(1)
?7l slice overwrites, and batched graphics scroll-before-place.

what:
- Add SyncToken, ScreenDelta, ResyncReason, Terminal.sync_token(), and
  Terminal.changes_since() across committed and working views
- Freeze Snapshot attributes and mappings, and add sound 4-way __getitem__
  overloads on Screen, Snapshot, and Terminal
- Fix right-margin VS16 wrap SGR/margins, GB4 ZWSP breaks, O(cols) ?7l
  slicing, primary ED 2/ED 0 scroll-on-clear, and batched _advance_rows
---
 src/libvt/screen.py   |  214 ++++++-
 src/libvt/terminal.py | 1235 +++++++++++++++++++++++++++++++++++++----
 2 files changed, 1339 insertions(+), 110 deletions(-)

diff --git a/src/libvt/screen.py b/src/libvt/screen.py
index b34d929..2a35f55 100644
--- a/src/libvt/screen.py
+++ b/src/libvt/screen.py
@@ -14,11 +14,13 @@
     RowLike,
     _CellExt,
     _Row,
+    bump_row_gen,
     raw_width_bits,
     unpack_style,
     unpack_width_role,
 )
 from libvt._ucd import WidthRole
+from libvt.graphics import GraphicsTracker, ImageMeta, ImagePlacement
 from libvt.input import KittyKeyboardStack
 from libvt.style import DEFAULT_STYLE, Hyperlink, Style
 
@@ -431,13 +433,21 @@ class Screen:
     """Mutable 2D character grid with ``FrozenRow`` RLE scrollback and reflow."""
 
     __slots__ = (
+        "_cell_height_px",
         "_cols",
         "_cur_blinking",
         "_cur_col",
         "_cur_row",
         "_cur_shape",
         "_cur_visible",
+        "_evicted_total",
+        "_gfx",
         "_history",
+        "_history_clear_at",
+        "_history_clear_seq",
+        "_max_image_dimension",
+        "_max_images",
+        "_max_placements",
         "_pending_wrap",
         "_rows",
         "_scrolled_total",
@@ -454,6 +464,10 @@ def __init__(
         cols: int = 80,
         scrollback: int = 2_000,
         keyboard_stack_depth: int = 8,
+        cell_height_px: int = 16,
+        max_images: int = 256,
+        max_placements: int = 1_024,
+        max_image_dimension: int = 10_000,
     ) -> None:
         if rows < 1 or cols < 1:
             msg = f"rows and cols must be >= 1, got ({rows}, {cols})"
@@ -464,6 +478,14 @@ def __init__(
             maxlen=max(0, scrollback),
         )
         self._scrolled_total: int = 0
+        self._evicted_total: int = 0
+        self._history_clear_at: int = 0
+        self._history_clear_seq: int = 0
+        self._cell_height_px: int = max(1, cell_height_px)
+        self._max_images: int = max_images
+        self._max_placements: int = max_placements
+        self._max_image_dimension: int = max_image_dimension
+        self._gfx: GraphicsTracker | None = None
         self._cur_row: int = 0
         self._cur_col: int = 0
         self._cur_visible: bool = True
@@ -546,6 +568,39 @@ def clear_all_tabstops(self) -> None:
     def clear_history(self) -> None:
         """Clear all sealed scrollback rows (``ED 3``)."""
         self._history.clear()
+        self._history_clear_at = self._scrolled_total
+        self._history_clear_seq += 1
+        if self._gfx is not None:
+            self._gfx.clear_history(self._scrolled_total)
+
+    def ensure_graphics(self) -> GraphicsTracker:
+        """Return (lazily creating) this screen's :class:`GraphicsTracker`."""
+        if self._gfx is None:
+            self._gfx = GraphicsTracker(
+                max_images=self._max_images,
+                max_placements=self._max_placements,
+                max_image_dimension=self._max_image_dimension,
+            )
+        return self._gfx
+
+    @property
+    def images(self) -> dict[int, ImageMeta]:
+        """Return stored ``SIXEL`` / Kitty :class:`ImageMeta` records."""
+        return self._gfx.images if self._gfx is not None else {}
+
+    @property
+    def placements(self) -> tuple[ImagePlacement, ...]:
+        """Return active + scrollback :class:`ImagePlacement` records."""
+        if self._gfx is None:
+            return ()
+        return self._gfx.snapshot_placements(self._scrolled_total)
+
+    def _append_history(self, frozen: FrozenRow) -> None:
+        maxlen = self._history.maxlen
+        if maxlen is not None and maxlen > 0:
+            if len(self._history) == maxlen:
+                self._evicted_total += 1
+            self._history.append(frozen)
 
     def _clear_row_spacer_head(self, row_obj: _Row) -> bool:
         if not row_obj.has_wide or row_obj.attrs is None:
@@ -570,6 +625,7 @@ def _clear_row_spacer_head(self, row_obj: _Row) -> bool:
                 and row_obj.ext_at(row_obj.used - 1) is None
             ):
                 row_obj.used -= 1
+            bump_row_gen(row_obj)
             return True
         return False
 
@@ -625,9 +681,15 @@ def __getitem__(self, key: tuple[int, int]) -> Cell: ...
     @t.overload
     def __getitem__(
         self,
-        key: slice | tuple[slice | int, slice | int],
+        key: slice | tuple[int, slice] | tuple[slice, int] | tuple[slice, slice],
     ) -> RegionView: ...
 
+    @t.overload
+    def __getitem__(
+        self,
+        key: tuple[slice | int, slice | int],
+    ) -> Cell | RegionView: ...
+
     def __getitem__(
         self,
         key: int | slice | tuple[slice | int, slice | int],
@@ -646,6 +708,7 @@ def scroll_up(
         save_history: bool = True,
         bce_word: int = 0,
         bce_ext: _CellExt | None = None,
+        is_line_op: bool = False,
     ) -> None:
         """Scroll region ``[top..bottom, left..right]`` upward by *count* lines."""
         t_row = self.scroll_region.top if top is None else top
@@ -655,13 +718,18 @@ def scroll_up(
             return
         shift = min(count, b_row - t_row + 1)
         full_width = left == 0 and r_col == self._cols - 1
+        full_screen = full_width and t_row == 0 and b_row == len(self._rows) - 1
 
         if full_width:
             if t_row > 0:
-                self._rows[t_row - 1].wrapped = False
+                if self._rows[t_row - 1].wrapped:
+                    self._rows[t_row - 1].wrapped = False
+                    bump_row_gen(self._rows[t_row - 1])
                 self._clear_row_spacer_head(self._rows[t_row - 1])
             if b_row < len(self._rows) - 1:
-                self._rows[b_row].wrapped = False
+                if self._rows[b_row].wrapped:
+                    self._rows[b_row].wrapped = False
+                    bump_row_gen(self._rows[b_row])
                 self._clear_row_spacer_head(self._rows[b_row])
             can_save = (
                 save_history
@@ -669,18 +737,63 @@ def scroll_up(
                 and self._history.maxlen is not None
                 and self._history.maxlen > 0
             )
+            hist_adv = shift if (can_save and not full_screen) else 0
+            if self._gfx is not None and not (full_screen and can_save):
+                self._gfx.on_region_scroll(
+                    top=t_row,
+                    bottom=b_row,
+                    left=left,
+                    right=r_col,
+                    delta_rows=-count,
+                    is_scroll=not is_line_op,
+                    scrolled_total=self._scrolled_total,
+                    cell_height_px=self._cell_height_px,
+                    history_advanced=(count if (can_save and not full_screen) else 0),
+                )
             evicted = self._rows[t_row : t_row + shift]
             if can_save:
                 for row_ev in evicted:
-                    self._history.append(row_ev.freeze())
-            if t_row == 0:
-                self._scrolled_total += shift
+                    self._append_history(row_ev.freeze())
+                extra = count - shift
+                if extra > 0:
+                    maxlen = self._history.maxlen or 0
+                    blank_row = _Row(self._cols)
+                    blank_row.reset_blank(self._cols, bce_word, bce_ext)
+                    blank_frozen = blank_row.freeze()
+                    skip_evict = max(0, extra - maxlen)
+                    if skip_evict > 0:
+                        dropped_existing = min(len(self._history), skip_evict)
+                        for _ in range(dropped_existing):
+                            self._history.popleft()
+                        self._evicted_total += skip_evict
+                    for _ in range(extra - skip_evict):
+                        self._append_history(blank_frozen)
+                self._scrolled_total += count
+                if self._gfx is not None:
+                    self._gfx.reap_evicted_history(
+                        self._scrolled_total - len(self._history),
+                    )
             del self._rows[t_row : t_row + shift]
             for row_ev in evicted:
                 row_ev.reset_blank(self._cols, bce_word, bce_ext)
             self._rows[b_row - shift + 1 : b_row - shift + 1] = evicted
+            if not (full_screen and can_save):
+                stamp_end = len(self._rows) if hist_adv > 0 else (b_row + 1)
+                for idx_s in range(t_row, stamp_end):
+                    bump_row_gen(self._rows[idx_s])
             return
 
+        if self._gfx is not None:
+            self._gfx.on_region_scroll(
+                top=t_row,
+                bottom=b_row,
+                left=left,
+                right=r_col,
+                delta_rows=-count,
+                is_scroll=not is_line_op,
+                scrolled_total=self._scrolled_total,
+                cell_height_px=self._cell_height_px,
+            )
         for dst_r in range(t_row, b_row - shift + 1):
             src_row = self._rows[dst_r + shift]
             dst_row = self._rows[dst_r]
@@ -698,6 +811,7 @@ def scroll_up(
                 base = word & _WIDTH_CLEAR_MASK
                 dst_row._set_raw(c, src_row.chars[c], base, role, src_row.ext_at(c))
             _sync_partial_scroll_bounds(dst_row, src_row, left, r_col)
+            bump_row_gen(dst_row)
 
         for clr_r in range(b_row - shift + 1, b_row + 1):
             self._rows[clr_r].wrapped = False
@@ -716,6 +830,7 @@ def scroll_down(
         right: int | None = None,
         bce_word: int = 0,
         bce_ext: _CellExt | None = None,
+        is_line_op: bool = False,
     ) -> None:
         """Scroll region ``[top..bottom, left..right]`` downward by *count* lines."""
         t_row = self.scroll_region.top if top is None else top
@@ -726,9 +841,23 @@ def scroll_down(
         shift = min(count, b_row - t_row + 1)
         full_width = left == 0 and r_col == self._cols - 1
 
+        if self._gfx is not None:
+            self._gfx.on_region_scroll(
+                top=t_row,
+                bottom=b_row,
+                left=left,
+                right=r_col,
+                delta_rows=count,
+                is_scroll=not is_line_op,
+                scrolled_total=self._scrolled_total,
+                cell_height_px=self._cell_height_px,
+            )
+
         if full_width:
             if t_row > 0:
-                self._rows[t_row - 1].wrapped = False
+                if self._rows[t_row - 1].wrapped:
+                    self._rows[t_row - 1].wrapped = False
+                    bump_row_gen(self._rows[t_row - 1])
                 self._clear_row_spacer_head(self._rows[t_row - 1])
             recycled = self._rows[b_row - shift + 1 : b_row + 1]
             del self._rows[b_row - shift + 1 : b_row + 1]
@@ -736,8 +865,12 @@ def scroll_down(
                 row_ev.reset_blank(self._cols, bce_word, bce_ext)
             self._rows[t_row:t_row] = recycled
             if b_row < len(self._rows) - 1:
-                self._rows[b_row].wrapped = False
+                if self._rows[b_row].wrapped:
+                    self._rows[b_row].wrapped = False
+                    bump_row_gen(self._rows[b_row])
                 self._clear_row_spacer_head(self._rows[b_row])
+            for idx_s in range(t_row, b_row + 1):
+                bump_row_gen(self._rows[idx_s])
             return
 
         for dst_r in range(b_row, t_row + shift - 1, -1):
@@ -757,6 +890,7 @@ def scroll_down(
                 base = word & _WIDTH_CLEAR_MASK
                 dst_row._set_raw(c, src_row.chars[c], base, role, src_row.ext_at(c))
             _sync_partial_scroll_bounds(dst_row, src_row, left, r_col)
+            bump_row_gen(dst_row)
 
         for clr_r in range(t_row, t_row + shift):
             self._rows[clr_r].wrapped = False
@@ -769,11 +903,21 @@ def push_scrollback_and_clear(
         self,
         bce_word: int = 0,
         bce_ext: _CellExt | None = None,
+        *,
+        include_cursor_row: bool = True,
     ) -> None:
-        """Push active lines up to last non-blank row into history (``CSI 22 J``)."""
+        """Push active lines up to last non-blank row into history."""
         last_used = -1
         for idx in range(len(self._rows) - 1, -1, -1):
-            if self._rows[idx].used > 0 or idx == self._cur_row:
+            has_img = self._gfx is not None and self._gfx.has_placement_on_row(
+                idx,
+                self._scrolled_total,
+            )
+            if (
+                self._rows[idx].used > 0
+                or (include_cursor_row and idx == self._cur_row)
+                or has_img
+            ):
                 last_used = idx
                 break
         if (
@@ -782,8 +926,14 @@ def push_scrollback_and_clear(
             and self._history.maxlen > 0
         ):
             for idx in range(last_used + 1):
-                self._history.append(self._rows[idx].freeze())
+                self._append_history(self._rows[idx].freeze())
             self._scrolled_total += last_used + 1
+            if self._gfx is not None:
+                self._gfx.reap_evicted_history(
+                    self._scrolled_total - len(self._history),
+                )
+        elif self._gfx is not None:
+            self._gfx.clear_active_screen(self._scrolled_total, len(self._rows))
         for r in self._rows:
             r.reset_blank(self._cols, bce_word, bce_ext)
 
@@ -921,14 +1071,20 @@ def _reflow_primary(self, *, rows: int, cols: int) -> None:
         hist_cut = min(hist_cut, new_cur_abs)
 
         self._history.clear()
+        self._evicted_total = 0
         if self._history.maxlen is not None and self._history.maxlen > 0:
             for r_h in new_all[:hist_cut]:
-                self._history.append(r_h.freeze())
+                self._append_history(r_h.freeze())
+        self._scrolled_total = len(self._history)
 
         viewport = new_all[hist_cut : hist_cut + rows]
         while len(viewport) < rows:
             viewport.append(_Row(cols))
+        for r_v in viewport:
+            bump_row_gen(r_v)
         self._rows = viewport
+        if self._gfx is not None:
+            self._gfx.reset()
         self._cols = cols
         self._cur_row = max(0, min(rows - 1, new_cur_abs - hist_cut))
         self._cur_col = max(0, min(cols - 1, new_cur_col))
@@ -954,6 +1110,7 @@ def resize(self, *, rows: int, cols: int, reflow: bool = True) -> None:
                 self._cols = cols
 
             cur_rows = len(self._rows)
+            top_drop_no_hist = 0
             if rows < cur_rows:
                 drop_needed = cur_rows - rows
                 # Keep cursor visible by scrolling excess top rows into history first.
@@ -962,8 +1119,14 @@ def resize(self, *, rows: int, cols: int, reflow: bool = True) -> None:
                 if top_drop > 0:
                     if self._history.maxlen is not None and self._history.maxlen > 0:
                         for r_ev in self._rows[:top_drop]:
-                            self._history.append(r_ev.freeze())
+                            self._append_history(r_ev.freeze())
                         self._scrolled_total += top_drop
+                        if self._gfx is not None:
+                            self._gfx.reap_evicted_history(
+                                self._scrolled_total - len(self._history),
+                            )
+                    else:
+                        top_drop_no_hist = top_drop
                     del self._rows[:top_drop]
                     self._cur_row -= top_drop
                 if len(self._rows) > rows:
@@ -971,6 +1134,17 @@ def resize(self, *, rows: int, cols: int, reflow: bool = True) -> None:
             elif rows > cur_rows:
                 self._rows.extend(_Row(cols) for _ in range(rows - cur_rows))
 
+            if self._gfx is not None:
+                self._gfx.on_non_reflow_resize(
+                    top_drop_without_history=top_drop_no_hist,
+                    new_rows=rows,
+                    new_cols=cols,
+                    scrolled_total=self._scrolled_total,
+                )
+
+            for r_v in self._rows:
+                bump_row_gen(r_v)
+
             self._cur_row = min(self._cur_row, rows - 1)
             self._cur_col = min(self._cur_col, cols - 1)
             self._pending_wrap = self._pending_wrap and old_cur_col < cols
@@ -1008,6 +1182,8 @@ def reset(self) -> None:
         self._tabstops = set(range(8, self._cols, 8))
         self._tabstops_sorted = sorted(self._tabstops)
         self.keyboard_stack.reset()
+        if self._gfx is not None:
+            self._gfx.reset()
 
 
 def _sync_partial_scroll_bounds(
@@ -1055,18 +1231,30 @@ def __init__(
         cols: int = 80,
         scrollback: int = 2_000,
         keyboard_stack_depth: int = 8,
+        cell_height_px: int = 16,
+        max_images: int = 256,
+        max_placements: int = 1_024,
+        max_image_dimension: int = 10_000,
     ) -> None:
         self.primary = Screen(
             rows=rows,
             cols=cols,
             scrollback=scrollback,
             keyboard_stack_depth=keyboard_stack_depth,
+            cell_height_px=cell_height_px,
+            max_images=max_images,
+            max_placements=max_placements,
+            max_image_dimension=max_image_dimension,
         )
         self.alternate = Screen(
             rows=rows,
             cols=cols,
             scrollback=0,
             keyboard_stack_depth=keyboard_stack_depth,
+            cell_height_px=cell_height_px,
+            max_images=max_images,
+            max_placements=max_placements,
+            max_image_dimension=max_image_dimension,
         )
         self.active_is_alt: bool = False
 
diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py
index 6a66582..415bdc2 100644
--- a/src/libvt/terminal.py
+++ b/src/libvt/terminal.py
@@ -10,14 +10,18 @@
 import html
 import os
 import re
+import types
 import typing as t
 import urllib.parse
 from dataclasses import dataclass
 
 from libvt._grid import (
+    _WIDTH_CLEAR_MASK,
     FrozenRow,
     _CellExt,
     _Row,
+    bump_row_gen,
+    current_row_gen,
     make_cell_ext,
     pack_pen_base,
     raw_width_bits,
@@ -26,6 +30,7 @@
 from libvt._ucd import (
     CLUSTER_NONE,
     GCB_PREPEND,
+    SAFE_NARROW_BMP_RE,
     WidthRole,
     char_width,
     init_cluster_state,
@@ -38,6 +43,9 @@
     DEFAULT_OSC7_HOSTS,
     DEFAULT_POLICY,
     DEFAULT_PROFILE,
+    TMUX_CAPTURE_POLICY,
+    TMUX_PROFILE,
+    Charset,
     Limits,
     Policy,
     Profile,
@@ -67,6 +75,7 @@
     WorkingDirectoryChanged,
 )
 from libvt.exc import ProtocolError
+from libvt.graphics import ImageMeta, ImagePlacement
 from libvt.input import InputEvent, KittyKeyboardFlags, encode_input
 from libvt.modes import (
     ALT_SCREEN_MODES,
@@ -100,6 +109,9 @@
     _resolve_color_rgb,
 )
 
+if t.TYPE_CHECKING:
+    from libvt.tmux import CaptureInput, TmuxPaneMetadata
+
 # DEC Special Graphics ('0') mapping for 0x5F..0x7E (VT100 / xterm / tmux tty-acs.c).
 _DEC_SPECIAL_GRAPHICS = str.maketrans(
     {
@@ -144,10 +156,215 @@
 _PRINT_ASCII_RE = re.compile(rb"[\x20-\x7e]+")
 _STR_BODY_UTF8_RE = re.compile(rb"[^\x07\x18\x1a\x1b\x7f]+")
 _STR_BODY_LATIN1_RE = re.compile(rb"[^\x07\x18\x1a\x1b\x7f\x80-\x9f]+")
-# BMP blocks where every codepoint has width 1, GCB_OTHER, and INCB_NONE.
-_SAFE_NARROW_BMP_RE = re.compile(
-    r"[\x20-\x7e\xa0-\xa8\xaa-\xac\xaf-\u02ff\u0391-\u03a1\u03a3-\u03ff\u0400-\u0482\u2500-\u259f]+",
-)
+
+_NEXT_TERMINAL_ID: int = 0
+
+
+def _alloc_terminal_id() -> int:
+    global _NEXT_TERMINAL_ID
+    _NEXT_TERMINAL_ID += 1
+    return _NEXT_TERMINAL_ID
+
+
+type SyncView = t.Literal["working", "committed"]
+
+
+class ResyncReason(enum.StrEnum):
+    """Reason :meth:`Terminal.changes_since` emitted a full resynchronization."""
+
+    NONE = "none"
+    INITIAL = "initial"
+    TERMINAL_MISMATCH = "terminal_mismatch"
+    EPOCH_CHANGED = "epoch_changed"
+    HISTORY_EVICTED = "history_evicted"
+
+
+@dataclass(frozen=True, slots=True)
+class SyncToken:
+    """Opaque monotonic watermark passed to :meth:`Terminal.changes_since`.
+
+    Attributes
+    ----------
+    terminal_id : int
+        Identity cookie of the originating :class:`Terminal`.
+    view : SyncView
+        Tracked view (``"committed"`` or ``"working"``).
+    epoch : int
+        Structural epoch incremented on ``resize()``, ``RIS``, and ``?1049``
+        alternate-screen transitions.
+    revision : int
+        Monotonic row-content mutation watermark.
+    scrolled_total : int
+        Cumulative primary-screen lines scrolled into history.
+    evicted_total : int
+        Cumulative primary-screen history lines evicted by ``maxlen``.
+    history_clear_at : int
+        ``scrolled_total`` value at the most recent ``ED 3`` history clear.
+    history_clear_seq : int
+        Monotonic counter of ``ED 3`` history clears.
+    cursor : Cursor
+        Cursor state at watermark capture.
+    modes : frozenset[Mode]
+        Enabled terminal modes at watermark capture.
+    title : str
+        Window title at watermark capture.
+    cwd : str
+        Working directory at watermark capture.
+    cwd_uri : str
+        Raw ``OSC 7`` / ``OSC 9;9`` working directory URI at watermark capture.
+    aux_revision : int
+        Monotonic counter of prompt-zone, program-status, and window-metadata
+        updates.
+    graphics_revision : int
+        Monotonic graphics placement revision on the active screen.
+    """
+
+    terminal_id: int
+    view: SyncView
+    epoch: int
+    revision: int
+    scrolled_total: int
+    evicted_total: int
+    history_clear_at: int
+    history_clear_seq: int
+    cursor: Cursor
+    modes: frozenset[Mode]
+    title: str
+    cwd: str
+    cwd_uri: str = ""
+    aux_revision: int = 0
+    graphics_revision: int = 0
+
+
+@dataclass(frozen=True, slots=True)
+class ScreenDelta:
+    """Multi-consumer incremental screen update from :meth:`Terminal.changes_since`.
+
+    Attributes
+    ----------
+    token : SyncToken
+        New watermark representing *snapshot*.
+    from_token : SyncToken | None
+        Previous watermark supplied by the caller.
+    resync_reason : ResyncReason
+        ``ResyncReason.NONE`` for an incremental delta, or the reason a full
+        resynchronization was required.
+    viewport_scroll_up : int
+        Count of rows the primary viewport scrolled up into history since
+        *from_token* (``0`` on full resync or non-history scroll).
+    dirty_rows : tuple[int, ...]
+        Sorted zero-based viewport row indices modified after shifting the
+        previous viewport upward by :attr:`viewport_scroll_up`.
+    new_history : tuple[RowView, ...]
+        Newly sealed scrollback rows appended since *from_token*, ordered
+        oldest to newest.
+    history_evicted : int
+        Count of oldest scrollback rows evicted by scrollback capacity since
+        *from_token* when :attr:`history_cleared` is ``False``.
+    history_cleared : bool
+        ``True`` when ``ED 3`` cleared scrollback since *from_token*.
+    cursor_changed : bool
+        ``True`` when cursor position, visibility, shape, or ``pending_wrap``
+        changed.
+    modes_changed : bool
+        ``True`` when enabled ANSI/DEC modes changed.
+    metadata_changed : bool
+        ``True`` when ``title`` or ``cwd`` changed.
+    graphics_changed : bool
+        ``True`` when ``SIXEL`` or Kitty placements mutated.
+    snapshot : Snapshot
+        Immutable target :class:`Snapshot` corresponding to :attr:`token`.
+    """
+
+    token: SyncToken
+    from_token: SyncToken | None
+    resync_reason: ResyncReason
+    viewport_scroll_up: int
+    dirty_rows: tuple[int, ...]
+    new_history: tuple[RowView, ...]
+    history_evicted: int
+    history_cleared: bool
+    cursor_changed: bool
+    modes_changed: bool
+    metadata_changed: bool
+    graphics_changed: bool
+    snapshot: Snapshot
+
+    @property
+    def full_resync(self) -> bool:
+        """Return ``True`` when the consumer must replace cached state."""
+        return self.resync_reason is not ResyncReason.NONE
+
+    @property
+    def has_changes(self) -> bool:
+        """Return ``True`` when any grid, history, cursor, mode, or metadata changed."""
+        return (
+            self.full_resync
+            or self.viewport_scroll_up > 0
+            or bool(self.dirty_rows)
+            or bool(self.new_history)
+            or self.history_evicted > 0
+            or self.history_cleared
+            or self.cursor_changed
+            or self.modes_changed
+            or self.metadata_changed
+            or self.graphics_changed
+        )
+
+    def apply_lines(self, history: list[str], viewport: list[str]) -> None:
+        """Apply this delta in place to mutable *history* and *viewport* line lists.
+
+        Parameters
+        ----------
+        history : list[str]
+            Cached scrollback text lines maintained by the consumer.
+        viewport : list[str]
+            Cached visible-viewport text lines maintained by the consumer.
+        """
+        if self.full_resync or len(viewport) != self.snapshot.rows:
+            history[:] = [r.text for r in self.snapshot.history]
+            viewport[:] = list(self.snapshot.lines)
+            return
+        if self.history_cleared:
+            history.clear()
+        elif self.history_evicted > 0:
+            del history[: self.history_evicted]
+        if self.new_history:
+            history.extend(r.text for r in self.new_history)
+        if self.viewport_scroll_up > 0:
+            shift = min(len(viewport), self.viewport_scroll_up)
+            del viewport[:shift]
+            viewport.extend([""] * shift)
+        for r_idx in self.dirty_rows:
+            viewport[r_idx] = self.snapshot[r_idx].text
+
+    def apply_rows(self, history: list[RowView], viewport: list[RowView]) -> None:
+        """Apply this delta in place to mutable *history* and *viewport* row views.
+
+        Parameters
+        ----------
+        history : list[RowView]
+            Cached scrollback :class:`~libvt.screen.RowView` entries.
+        viewport : list[RowView]
+            Cached visible :class:`~libvt.screen.RowView` entries.
+        """
+        if self.full_resync or len(viewport) != self.snapshot.rows:
+            history[:] = list(self.snapshot.history)
+            viewport[:] = [self.snapshot[r] for r in range(self.snapshot.rows)]
+            return
+        if self.history_cleared:
+            history.clear()
+        elif self.history_evicted > 0:
+            del history[: self.history_evicted]
+        if self.new_history:
+            history.extend(self.new_history)
+        if self.viewport_scroll_up > 0:
+            shift = min(len(viewport), self.viewport_scroll_up)
+            del viewport[:shift]
+            base = len(viewport)
+            viewport.extend([self.snapshot[base + i] for i in range(shift)])
+        for r_idx in self.dirty_rows:
+            viewport[r_idx] = self.snapshot[r_idx]
 
 
 class StopOn(enum.IntFlag):
@@ -243,7 +460,7 @@ class _SavedCursor:
         Saved SGR pen.
     decom : bool
         Saved ``DECOM`` origin-mode flag.
-    g_sets : tuple[str, str, str, str]
+    g_sets : tuple[Charset, Charset, Charset, Charset]
         Saved ``G0``..``G3`` character-set designations.
     gl : int
         Saved active locking-shift slot index (``0..3``).
@@ -256,16 +473,45 @@ class _SavedCursor:
     pending_wrap: bool = False
     style: Style = DEFAULT_STYLE
     decom: bool = False
-    g_sets: tuple[str, str, str, str] = ("B", "B", "B", "B")
+    g_sets: tuple[Charset, Charset, Charset, Charset] = ("B", "B", "B", "B")
     gl: int = 0
     protected: bool = False
 
 
 class Snapshot:
-    """Immutable point-in-time capture of terminal screen, history, and metadata."""
+    """Immutable point-in-time capture of terminal screen, history, and metadata.
+
+    Attributes
+    ----------
+    cursor : Cursor
+        Zero-based cursor position, shape, visibility, and ``pending_wrap``.
+    title : str
+        Window title set via ``OSC 0`` / ``OSC 2``.
+    cwd : str
+        Local working directory accepted under ``Policy.osc7_hosts``.
+    cwd_uri : str
+        Raw ``OSC 7`` / ``OSC 9;9`` working directory URI.
+    modes : frozenset[Mode]
+        Enabled ANSI and DEC private modes.
+    active_is_alt : bool
+        ``True`` when the alternate screen buffer is active.
+    prompt_zones : tuple[PromptZone, ...]
+        Recorded ``OSC 133`` semantic prompt zones adjusted to this viewport.
+    program_status : ProgramStatus | None
+        Highest-urgency active ``OSC 7501`` / ``OSC 9;4`` status record.
+    program_statuses : collections.abc.Mapping[str, ProgramStatus]
+        Read-only mapping of active ``OSC 7501`` task records keyed by ``id``.
+    generation : int
+        Terminal mutation generation when this snapshot was captured.
+    images : collections.abc.Mapping[int, ImageMeta]
+        Read-only mapping of stored ``SIXEL`` / Kitty :class:`ImageMeta` items.
+    placements : tuple[ImagePlacement, ...]
+        Immutable active + scrollback :class:`ImagePlacement` records.
+    """
 
     __slots__ = (
         "_cols",
+        "_frozen",
         "_history",
         "_rows",
         "active_is_alt",
@@ -273,7 +519,9 @@ class Snapshot:
         "cwd",
         "cwd_uri",
         "generation",
+        "images",
         "modes",
+        "placements",
         "program_status",
         "program_statuses",
         "prompt_zones",
@@ -294,9 +542,12 @@ def __init__(
         active_is_alt: bool,
         prompt_zones: tuple[PromptZone, ...],
         program_status: ProgramStatus | None,
-        program_statuses: dict[str, ProgramStatus],
+        program_statuses: collections.abc.Mapping[str, ProgramStatus],
         generation: int,
+        images: collections.abc.Mapping[int, ImageMeta] | None = None,
+        placements: tuple[ImagePlacement, ...] = (),
     ) -> None:
+        object.__setattr__(self, "_frozen", False)
         self._rows = rows
         self._history = history
         self._cols = cols
@@ -308,8 +559,57 @@ def __init__(
         self.active_is_alt = active_is_alt
         self.prompt_zones = prompt_zones
         self.program_status = program_status
-        self.program_statuses = program_statuses
+        self.program_statuses: collections.abc.Mapping[str, ProgramStatus] = (
+            types.MappingProxyType(dict(program_statuses))
+        )
         self.generation = generation
+        self.images: collections.abc.Mapping[int, ImageMeta] = types.MappingProxyType(
+            dict(images) if images is not None else {}
+        )
+        self.placements = placements
+        object.__setattr__(self, "_frozen", True)
+
+    def __setattr__(self, name: str, value: object) -> None:
+        """Reject attribute mutation once snapshot initialization completes."""
+        if getattr(self, "_frozen", False):
+            msg = f"Snapshot is immutable; cannot assign {name!r}"
+            raise AttributeError(msg)
+        object.__setattr__(self, name, value)
+
+    @classmethod
+    def from_tmux_capture(
+        cls,
+        captured: CaptureInput,
+        *,
+        metadata: TmuxPaneMetadata | str | None = None,
+        rows: int = 24,
+        cols: int = 80,
+        scrollback: int | None = None,
+        flagged: bool = False,
+        joined_capture: CaptureInput | None = None,
+        saved_primary_capture: CaptureInput | None = None,
+        saved_primary_flagged: bool | None = None,
+        profile: Profile = TMUX_PROFILE,
+        policy: Policy = TMUX_CAPTURE_POLICY,
+        limits: Limits = DEFAULT_LIMITS,
+    ) -> Snapshot:
+        """Decode ``tmux capture-pane`` output directly into a :class:`Snapshot`."""
+        from libvt.tmux import decode_tmux_capture
+
+        return decode_tmux_capture(
+            captured,
+            metadata=metadata,
+            rows=rows,
+            cols=cols,
+            scrollback=scrollback,
+            flagged=flagged,
+            joined_capture=joined_capture,
+            saved_primary_capture=saved_primary_capture,
+            saved_primary_flagged=saved_primary_flagged,
+            profile=profile,
+            policy=policy,
+            limits=limits,
+        ).snapshot
 
     @property
     def rows(self) -> int:
@@ -345,9 +645,15 @@ def __getitem__(self, key: tuple[int, int]) -> Cell: ...
     @t.overload
     def __getitem__(
         self,
-        key: slice | tuple[slice | int, slice | int],
+        key: slice | tuple[int, slice] | tuple[slice, int] | tuple[slice, slice],
     ) -> RegionView: ...
 
+    @t.overload
+    def __getitem__(
+        self,
+        key: tuple[slice | int, slice | int],
+    ) -> Cell | RegionView: ...
+
     def __getitem__(
         self,
         key: int | slice | tuple[slice | int, slice | int],
@@ -394,6 +700,12 @@ def to_dict(self) -> dict[str, t.Any]:
                     "state": self.program_status.state.value,
                     "id": self.program_status.id,
                     "progress": self.program_status.progress,
+                    "kind": (
+                        self.program_status.kind.value
+                        if self.program_status.kind is not None
+                        else None
+                    ),
+                    "app": self.program_status.app,
                     "effective_app": self.program_status.effective_app,
                     "title": self.program_status.title,
                     "msg": self.program_status.msg,
@@ -401,6 +713,20 @@ def to_dict(self) -> dict[str, t.Any]:
                 if self.program_status is not None
                 else None
             ),
+            "placements": [
+                {
+                    "protocol": p.protocol.value,
+                    "image_id": p.image_id,
+                    "placement_id": p.placement_id,
+                    "row": p.row,
+                    "col": p.col,
+                    "rows": p.rows,
+                    "cols": p.cols,
+                    "z_index": p.z_index,
+                    "virtual": p.virtual,
+                }
+                for p in self.placements
+            ],
         }
 
 
@@ -781,6 +1107,10 @@ def __init__(
             cols=cols,
             scrollback=scrollback,
             keyboard_stack_depth=limits.max_keyboard_stack,
+            cell_height_px=profile.cell_height_px,
+            max_images=limits.max_images,
+            max_placements=limits.max_placements,
+            max_image_dimension=limits.max_image_dimension,
         )
         self._modes = ModeState()
         if newline_mode:
@@ -799,8 +1129,13 @@ def __init__(
         self._pen_word: int = 0
         self._hyperlink: Hyperlink | None = None
         self._cell_ext: _CellExt | None = None
-        def_g = ("B", profile.default_g1_charset, "B", "B")
-        self._g_sets: list[str] = list(def_g)
+        def_g: tuple[Charset, Charset, Charset, Charset] = (
+            "B",
+            profile.default_g1_charset,
+            "B",
+            "B",
+        )
+        self._g_sets: list[Charset] = list(def_g)
         self._gl: int = 0
         self._single_shift: int | None = None
         self._saved_primary = _SavedCursor(g_sets=def_g)
@@ -824,11 +1159,15 @@ def __init__(
             max_records=limits.max_status_records,
         )
         self._replies = bytearray()
+        self._terminal_id: int = _alloc_terminal_id()
         self._generation: int = 0
+        self._epoch: int = 0
+        self._aux_revision: int = 0
         self._sync_generation: int = 0
         self._sync_hold_pending: bool = False
         self._cached_snapshot: Snapshot | None = None
         self._held_snapshot: Snapshot | None = None
+        self._held_sync_token: SyncToken | None = None
         self._step_event: StopOn = StopOn.NONE
         self._passthrough_depth: int = 0
 
@@ -852,6 +1191,41 @@ def from_size(
             limits=limits,
         )
 
+    @classmethod
+    def from_tmux_capture(
+        cls,
+        captured: CaptureInput,
+        *,
+        metadata: TmuxPaneMetadata | str | None = None,
+        rows: int = 24,
+        cols: int = 80,
+        scrollback: int | None = None,
+        flagged: bool = False,
+        joined_capture: CaptureInput | None = None,
+        saved_primary_capture: CaptureInput | None = None,
+        saved_primary_flagged: bool | None = None,
+        profile: Profile = TMUX_PROFILE,
+        policy: Policy = TMUX_CAPTURE_POLICY,
+        limits: Limits = DEFAULT_LIMITS,
+    ) -> Terminal:
+        """Reconstruct a live :class:`Terminal` from ``tmux capture-pane`` output."""
+        from libvt.tmux import decode_tmux_capture
+
+        return decode_tmux_capture(
+            captured,
+            metadata=metadata,
+            rows=rows,
+            cols=cols,
+            scrollback=scrollback,
+            flagged=flagged,
+            joined_capture=joined_capture,
+            saved_primary_capture=saved_primary_capture,
+            saved_primary_flagged=saved_primary_flagged,
+            profile=profile,
+            policy=policy,
+            limits=limits,
+        ).terminal
+
     @property
     def rows(self) -> int:
         """Return active screen height in rows."""
@@ -972,6 +1346,20 @@ def program_statuses(self) -> dict[str, ProgramStatus]:
         """Return all active ``OSC 7501`` task records keyed by ``id``."""
         return self._status_store.records
 
+    @property
+    def images(self) -> dict[int, ImageMeta]:
+        """Return active screen's stored :class:`~libvt.graphics.ImageMeta` map."""
+        return self._screens.active.images
+
+    @property
+    def placements(self) -> tuple[ImagePlacement, ...]:
+        """Return active screen's :class:`~libvt.graphics.ImagePlacement` records."""
+        return self._screens.active.placements
+
+    def _tabstops_from_list(self, scr: Screen, stops: tuple[int, ...]) -> None:
+        scr._tabstops = {c for c in stops if 0 <= c < scr.cols}
+        scr._tabstops_sorted = sorted(scr._tabstops)
+
     @property
     def lines(self) -> tuple[str, ...]:
         """Return right-trimmed visible lines of the active screen."""
@@ -1019,6 +1407,38 @@ def _build_snapshot(
             program_status=self._status_store.most_urgent,
             program_statuses=self._status_store.records,
             generation=self._generation,
+            images=scr.images,
+            placements=scr.placements,
+        )
+
+    def _live_sync_token(
+        self,
+        *,
+        view: SyncView,
+        exclude_modes: frozenset[Mode] = frozenset(),
+    ) -> SyncToken:
+        scr = self._screens.active
+        prim = self._screens.primary
+        modes = self._modes.enabled_modes()
+        if exclude_modes:
+            modes = modes - exclude_modes
+        gfx_rev = scr._gfx.revision if scr._gfx is not None else 0
+        return SyncToken(
+            terminal_id=self._terminal_id,
+            view=view,
+            epoch=self._epoch,
+            revision=current_row_gen(),
+            scrolled_total=prim._scrolled_total,
+            evicted_total=prim._evicted_total,
+            history_clear_at=prim._history_clear_at,
+            history_clear_seq=prim._history_clear_seq,
+            cursor=scr.cursor,
+            modes=modes,
+            title=self._title,
+            cwd=self._cwd,
+            cwd_uri=self._cwd_uri,
+            aux_revision=self._aux_revision,
+            graphics_revision=gfx_rev,
         )
 
     def _ensure_sync_snapshot(self) -> None:
@@ -1026,8 +1446,153 @@ def _ensure_sync_snapshot(self) -> None:
             self._held_snapshot = self._build_snapshot(
                 exclude_modes=TRANSIENT_SNAPSHOT_MODES,
             )
+            self._held_sync_token = self._live_sync_token(
+                view="committed",
+                exclude_modes=TRANSIENT_SNAPSHOT_MODES,
+            )
             self._sync_hold_pending = False
 
+    def sync_token(self, *, view: SyncView = "committed") -> SyncToken:
+        """Return an immutable watermark token for :meth:`changes_since`.
+
+        Parameters
+        ----------
+        view : SyncView
+            ``"committed"`` (default, respecting ``?2026`` frame holds) or
+            ``"working"`` (live in-progress buffer).
+
+        Returns
+        -------
+        SyncToken
+            Opaque watermark capturing current state without mutating the
+            terminal.
+        """
+        if view == "committed":
+            if self._sync_hold_pending:
+                self._ensure_sync_snapshot()
+            if self._held_sync_token is not None:
+                return self._held_sync_token
+        return self._live_sync_token(view=view)
+
+    def changes_since(
+        self,
+        token: SyncToken | None = None,
+        *,
+        view: SyncView = "committed",
+    ) -> ScreenDelta:
+        """Compute incremental changes relative to *token* without mutating state.
+
+        Parameters
+        ----------
+        token : SyncToken | None
+            Previous watermark from :meth:`sync_token` or
+            :attr:`ScreenDelta.token`; ``None`` requests an initial full sync.
+        view : SyncView
+            ``"committed"`` (default) or ``"working"``.
+
+        Returns
+        -------
+        ScreenDelta
+            Incremental row/scrollback delta or full resynchronization record.
+        """
+        cur_snap = self.committed if view == "committed" else self.snapshot()
+        cur_tok = self.sync_token(view=view)
+
+        def _full(reason: ResyncReason) -> ScreenDelta:
+            return ScreenDelta(
+                token=cur_tok,
+                from_token=token,
+                resync_reason=reason,
+                viewport_scroll_up=0,
+                dirty_rows=tuple(range(cur_snap.rows)),
+                new_history=cur_snap.history,
+                history_evicted=0,
+                history_cleared=False,
+                cursor_changed=True,
+                modes_changed=True,
+                metadata_changed=True,
+                graphics_changed=bool(cur_snap.placements),
+                snapshot=cur_snap,
+            )
+
+        if token is None:
+            return _full(ResyncReason.INITIAL)
+        if token.terminal_id != self._terminal_id or token.view != view:
+            return _full(ResyncReason.TERMINAL_MISMATCH)
+        if token.epoch != cur_tok.epoch:
+            return _full(ResyncReason.EPOCH_CHANGED)
+
+        if token == cur_tok:
+            return ScreenDelta(
+                token=cur_tok,
+                from_token=token,
+                resync_reason=ResyncReason.NONE,
+                viewport_scroll_up=0,
+                dirty_rows=(),
+                new_history=(),
+                history_evicted=0,
+                history_cleared=False,
+                cursor_changed=False,
+                modes_changed=False,
+                metadata_changed=False,
+                graphics_changed=False,
+                snapshot=cur_snap,
+            )
+
+        hist_cleared = cur_tok.history_clear_seq != token.history_clear_seq
+        hist_len = len(cur_snap._history)
+        if hist_cleared:
+            post_clear = max(0, cur_tok.scrolled_total - cur_tok.history_clear_at)
+            if post_clear > hist_len:
+                return _full(ResyncReason.HISTORY_EVICTED)
+            new_hist = (
+                tuple(RowView(fr) for fr in cur_snap._history[hist_len - post_clear :])
+                if post_clear > 0
+                else ()
+            )
+            evicted_cnt = 0
+        else:
+            added = max(0, cur_tok.scrolled_total - token.scrolled_total)
+            if added > hist_len:
+                return _full(ResyncReason.HISTORY_EVICTED)
+            new_hist = (
+                tuple(RowView(fr) for fr in cur_snap._history[hist_len - added :])
+                if added > 0
+                else ()
+            )
+            evicted_cnt = max(0, cur_tok.evicted_total - token.evicted_total)
+
+        v_scroll = (
+            0
+            if cur_snap.active_is_alt
+            else max(0, cur_tok.scrolled_total - token.scrolled_total)
+        )
+        dirty = tuple(
+            idx
+            for idx, r in enumerate(cur_snap._rows)
+            if r.content_gen > token.revision
+        )
+        return ScreenDelta(
+            token=cur_tok,
+            from_token=token,
+            resync_reason=ResyncReason.NONE,
+            viewport_scroll_up=v_scroll,
+            dirty_rows=dirty,
+            new_history=new_hist,
+            history_evicted=evicted_cnt,
+            history_cleared=hist_cleared,
+            cursor_changed=cur_tok.cursor != token.cursor,
+            modes_changed=cur_tok.modes != token.modes,
+            metadata_changed=(
+                cur_tok.title != token.title
+                or cur_tok.cwd != token.cwd
+                or cur_tok.cwd_uri != token.cwd_uri
+                or cur_tok.aux_revision != token.aux_revision
+            ),
+            graphics_changed=cur_tok.graphics_revision != token.graphics_revision,
+            snapshot=cur_snap,
+        )
+
     def snapshot(self) -> Snapshot:
         """Capture an immutable :class:`Snapshot` of live terminal state."""
         if (
@@ -1048,9 +1613,15 @@ def __getitem__(self, key: tuple[int, int]) -> Cell: ...
     @t.overload
     def __getitem__(
         self,
-        key: slice | tuple[slice | int, slice | int],
+        key: slice | tuple[int, slice] | tuple[slice, int] | tuple[slice, slice],
     ) -> RegionView: ...
 
+    @t.overload
+    def __getitem__(
+        self,
+        key: tuple[slice | int, slice | int],
+    ) -> Cell | RegionView: ...
+
     def __getitem__(
         self,
         key: int | slice | tuple[slice | int, slice | int],
@@ -1123,6 +1694,7 @@ def expire_synchronized_output(
         self._modes.set_mode(Mode.SYNCHRONIZED_OUTPUT, enabled=False)
         self._sync_hold_pending = False
         self._held_snapshot = None
+        self._held_sync_token = None
         self._cached_snapshot = None
         self._generation += 1
         self._emit_event(
@@ -1138,6 +1710,7 @@ def notify_process_exit(self) -> None:
         """Prune transient ``working`` / ``blocked`` ``OSC 7501`` status records."""
         self._before_mutate()
         if self._status_store.on_process_exit():
+            self._aux_revision += 1
             self._generation += 1
             self._emit_event(
                 ProgramStatusChanged(status=self._status_store.most_urgent),
@@ -1212,6 +1785,7 @@ def resize(
                 protected=self._saved_primary.protected,
             )
         self._generation += 1
+        self._epoch += 1
         if self._modes.is_set(Mode.IN_BAND_RESIZE):
             self._emit_reply(f"\x1b[48;{rows};{cols};0;0t".encode("ascii"))
             self._emit_event(InBandResize(rows=rows, cols=cols))
@@ -1225,7 +1799,12 @@ def reset(self, *, soft: bool = False) -> None:
         self._sync_pen_cache()
         self._last_printed = ""
         self._clear_cluster_anchor()
-        def_g = ("B", self._profile.default_g1_charset, "B", "B")
+        def_g: tuple[Charset, Charset, Charset, Charset] = (
+            "B",
+            self._profile.default_g1_charset,
+            "B",
+            "B",
+        )
         self._g_sets = list(def_g)
         self._gl = 0
         self._single_shift = None
@@ -1236,6 +1815,7 @@ def reset(self, *, soft: bool = False) -> None:
             self._modes.set_mode(Mode.LNM, enabled=True)
         self._sync_hold_pending = False
         self._held_snapshot = None
+        self._held_sync_token = None
         if soft:
             if was_alt:
                 self._modes.sync_alt_screen(active_is_alt=True)
@@ -1250,6 +1830,7 @@ def reset(self, *, soft: bool = False) -> None:
             scr._pending_wrap = False
             scr.keyboard_stack.reset()
         else:
+            self._epoch += 1
             self._parser.reset()
             self._passthrough_parser = None
             self._screens.active_is_alt = False
@@ -1266,6 +1847,7 @@ def reset(self, *, soft: bool = False) -> None:
             self._cwd_uri = ""
             self._prompt_zones.clear()
             self._status_store.reset()
+            self._aux_revision += 1
             self._notify_erase(
                 Rect(0, 0, self.rows, self.cols),
                 EraseCause.RESET,
@@ -1400,6 +1982,36 @@ def _set_cursor(
         if clear_cluster:
             self._clear_cluster_anchor()
 
+    def _shift_prompt_zones_below(
+        self,
+        prev_scrolled: int,
+        bottom: int,
+        count: int,
+    ) -> None:
+        if not self._prompt_zones or count <= 0:
+            return
+        cutoff = prev_scrolled + bottom
+        changed = False
+        updated: list[PromptZone] = []
+        for z in self._prompt_zones:
+            if z.abs_row > cutoff:
+                updated.append(
+                    PromptZone(
+                        kind=z.kind,
+                        row=z.row,
+                        col=z.col,
+                        exit_code=z.exit_code,
+                        abs_row=z.abs_row + count,
+                    ),
+                )
+                changed = True
+            else:
+                updated.append(z)
+        if changed:
+            self._prompt_zones.clear()
+            self._prompt_zones.extend(updated)
+            self._aux_revision += 1
+
     def _linefeed(self, scr: Screen, *, carriage_return: bool = False) -> None:
         self._before_mutate()
         top, bottom, left, right = self._effective_margins(scr)
@@ -1410,17 +2022,28 @@ def _linefeed(self, scr: Screen, *, carriage_return: bool = False) -> None:
             and scr._pending_wrap
         )
         if scr._cur_row == bottom and left <= scr._cur_col <= right:
+            prev_scrolled = scr._scrolled_total
             bce_word, bce_ext = self._bce_pair()
+            save_hist = not self._screens.active_is_alt
             scr.scroll_up(
                 1,
                 top=top,
                 bottom=bottom,
                 left=left,
                 right=right,
-                save_history=not self._screens.active_is_alt,
+                save_history=save_hist,
                 bce_word=bce_word,
                 bce_ext=bce_ext,
             )
+            hist_delta = scr._scrolled_total - prev_scrolled
+            if (
+                hist_delta > 0
+                and top == 0
+                and bottom < scr.rows - 1
+                and left == 0
+                and right == scr.cols - 1
+            ):
+                self._shift_prompt_zones_below(prev_scrolled, bottom, hist_delta)
             self._notify_erase(
                 Rect(bottom, left, 1, right - left + 1),
                 EraseCause.SCROLL,
@@ -1431,6 +2054,61 @@ def _linefeed(self, scr: Screen, *, carriage_return: bool = False) -> None:
         else:
             self._set_cursor(scr, scr._cur_row, col, pending_wrap=keep_wrap)
 
+    def _advance_rows(
+        self,
+        scr: Screen,
+        steps: int,
+        *,
+        final_col: int,
+    ) -> int:
+        self._before_mutate()
+        orig_row = scr._cur_row
+        orig_col = scr._cur_col
+        if steps <= 0:
+            self._set_cursor(scr, orig_row, final_col, pending_wrap=False)
+            return orig_row
+        top, bottom, left, right = self._effective_margins(scr)
+        if orig_col < left or orig_col > right or orig_row > bottom:
+            new_r = min(scr.rows - 1, orig_row + steps)
+            self._set_cursor(scr, new_r, final_col, pending_wrap=False)
+            return orig_row
+        to_bottom = min(steps, bottom - orig_row)
+        scroll_cnt = steps - to_bottom
+        if scroll_cnt <= 0:
+            self._set_cursor(scr, orig_row + to_bottom, final_col, pending_wrap=False)
+            return orig_row
+        prev_scrolled = scr._scrolled_total
+        bce_word, bce_ext = self._bce_pair()
+        save_hist = not self._screens.active_is_alt
+        scr.scroll_up(
+            scroll_cnt,
+            top=top,
+            bottom=bottom,
+            left=left,
+            right=right,
+            save_history=save_hist,
+            bce_word=bce_word,
+            bce_ext=bce_ext,
+        )
+        hist_delta = scr._scrolled_total - prev_scrolled
+        if (
+            hist_delta > 0
+            and top == 0
+            and bottom < scr.rows - 1
+            and left == 0
+            and right == scr.cols - 1
+        ):
+            self._shift_prompt_zones_below(prev_scrolled, bottom, hist_delta)
+        erase_h = min(scroll_cnt, bottom - top + 1)
+        self._notify_erase(
+            Rect(bottom - erase_h + 1, left, erase_h, right - left + 1),
+            EraseCause.SCROLL,
+        )
+        self._set_cursor(scr, bottom, final_col, pending_wrap=False)
+        if orig_row < top:
+            return orig_row
+        return orig_row - scroll_cnt
+
     def _map_charset(self, text: str) -> str:
         if self._single_shift is not None:
             ch0_cs = self._g_sets[self._single_shift]
@@ -1453,6 +2131,99 @@ def _map_charset(self, text: str) -> str:
             return text.translate(_UK_CHARSET)
         return text
 
+    def _write_slice_run(
+        self,
+        scr: Screen,
+        text: str,
+        start: int,
+        end: int,
+        *,
+        autowrap: bool,
+        bottom: int,
+        left: int,
+        right: int,
+        mode_2027: bool,
+    ) -> None:
+        pos = start
+        sixel_pol = self._profile.sixel_erase_policy
+        gfx = scr._gfx
+        has_sixels = gfx is not None and gfx.has_sixels
+        while pos < end:
+            c_col = scr._cur_col
+            max_col = right if c_col <= right else scr.cols - 1
+            min_col = left if c_col >= left else 0
+            if scr._pending_wrap and autowrap:
+                prev_row = scr._cur_row
+                can_advance = prev_row < scr.rows - 1 or (
+                    prev_row == bottom and left <= c_col <= right
+                )
+                set_wrap = can_advance and min_col == 0 and c_col == scr.cols - 1
+                if set_wrap and prev_row == 0 and bottom == 0:
+                    scr._rows[0].wrapped = True
+                    bump_row_gen(scr._rows[0])
+                self._linefeed(scr)
+                if set_wrap and not (prev_row == 0 and bottom == 0):
+                    wrap_idx = prev_row - 1 if prev_row == bottom else prev_row
+                    if 0 <= wrap_idx < scr.rows:
+                        scr._rows[wrap_idx].wrapped = True
+                        bump_row_gen(scr._rows[wrap_idx])
+                self._set_cursor(scr, scr._cur_row, min_col, pending_wrap=False)
+                c_col = scr._cur_col
+            avail = max_col - c_col + 1
+            rem = end - pos
+            if not autowrap and rem > avail:
+                seg = (
+                    text[pos : pos + avail - 1] + text[end - 1]
+                    if avail > 1
+                    else text[end - 1]
+                )
+                consumed = rem
+            else:
+                seg = text[pos : min(end, pos + avail)]
+                consumed = len(seg)
+            seg_len = len(seg)
+            scr.heal_before_edit(scr._cur_row, c_col, c_col + seg_len)
+            scr._rows[scr._cur_row].write_ascii_slice(
+                c_col,
+                seg,
+                self._pen_word,
+                self._cell_ext,
+            )
+            if has_sixels and gfx is not None:
+                gfx.erase_sixel_rect(
+                    row=scr._cur_row,
+                    col=c_col,
+                    rows=1,
+                    cols=seg_len,
+                    scrolled_total=scr._scrolled_total,
+                    policy=sixel_pol,
+                )
+            pos += consumed
+            end_col = c_col + seg_len - 1
+            if c_col + seg_len > max_col:
+                self._set_cursor(
+                    scr,
+                    scr._cur_row,
+                    max_col,
+                    pending_wrap=autowrap,
+                    clear_cluster=False,
+                )
+            else:
+                self._set_cursor(
+                    scr,
+                    scr._cur_row,
+                    c_col + seg_len,
+                    pending_wrap=False,
+                    clear_cluster=False,
+                )
+            self._last_printed = seg[-1]
+            self._last_printed_pos = (scr._cur_row, end_col)
+            self._cluster_state = init_cluster_state(
+                ord(seg[-1]),
+                mode_2027=mode_2027,
+            )
+            self._cluster_len = 1
+
     def _handle_print(self, text: str) -> None:
         self._before_mutate()
         if self._single_shift is not None or self._g_sets[self._gl] != "B":
@@ -1464,70 +2235,59 @@ def _handle_print(self, text: str) -> None:
         _, bottom, left, right = self._effective_margins(scr)
 
         mode_2027 = self._modes.is_set(Mode.GRAPHEME_CLUSTERING)
-        can_slice = (
+        total = len(text)
+        if (
             not insert_mode
             and not self._pending_prepend
             and (not mode_2027 or ((self._cluster_state >> 1) & 0x0F) != GCB_PREPEND)
-            and (text.isascii() or _SAFE_NARROW_BMP_RE.fullmatch(text) is not None)
-        )
-        if can_slice:
-            pos = 0
-            total = len(text)
-            while pos < total:
-                c_col = scr._cur_col
-                max_col = right if c_col <= right else scr.cols - 1
-                min_col = left if c_col >= left else 0
-                if scr._pending_wrap and autowrap:
-                    can_advance = scr._cur_row < scr.rows - 1 or (
-                        scr._cur_row == bottom and left <= c_col <= right
-                    )
-                    if can_advance and min_col == 0 and c_col == scr.cols - 1:
-                        scr._rows[scr._cur_row].wrapped = True
-                    self._linefeed(scr)
-                    self._set_cursor(scr, scr._cur_row, min_col, pending_wrap=False)
-                    c_col = scr._cur_col
-                avail = max_col - c_col + 1
-                seg = text[pos : pos + avail]
-                seg_len = len(seg)
-                scr.heal_before_edit(scr._cur_row, c_col, c_col + seg_len)
-                scr._rows[scr._cur_row].write_ascii_slice(
-                    c_col,
-                    seg,
-                    self._pen_word,
-                    self._cell_ext,
-                )
-                pos += seg_len
-                end_col = c_col + seg_len - 1
-                if c_col + seg_len > max_col:
-                    self._set_cursor(
-                        scr,
-                        scr._cur_row,
-                        max_col,
-                        pending_wrap=autowrap,
-                        clear_cluster=False,
-                    )
-                else:
-                    self._set_cursor(
-                        scr,
-                        scr._cur_row,
-                        c_col + seg_len,
-                        pending_wrap=False,
-                        clear_cluster=False,
-                    )
-                self._last_printed = seg[-1]
-                self._last_printed_pos = (scr._cur_row, end_col)
-                self._cluster_state = init_cluster_state(
-                    ord(seg[-1]),
-                    mode_2027=mode_2027,
-                )
-                self._cluster_len = 1
+            and text.isascii()
+        ):
+            self._write_slice_run(
+                scr,
+                text,
+                0,
+                total,
+                autowrap=autowrap,
+                bottom=bottom,
+                left=left,
+                right=right,
+                mode_2027=mode_2027,
+            )
             return
 
         vs15_narrows = self._profile.vs15_narrows_wide_emoji
         vs16_wide = self._profile.vs16_always_wide
         max_cluster = self._limits.max_grapheme_codepoints
+        sixel_pol = self._profile.sixel_erase_policy
+
+        t_idx = 0
+        while t_idx < total:
+            if (
+                not insert_mode
+                and not self._pending_prepend
+                and (
+                    not mode_2027 or ((self._cluster_state >> 1) & 0x0F) != GCB_PREPEND
+                )
+            ):
+                safe_m = SAFE_NARROW_BMP_RE.match(text, t_idx)
+                if safe_m is not None and safe_m.end() > t_idx:
+                    self._write_slice_run(
+                        scr,
+                        text,
+                        t_idx,
+                        safe_m.end(),
+                        autowrap=autowrap,
+                        bottom=bottom,
+                        left=left,
+                        right=right,
+                        mode_2027=mode_2027,
+                    )
+                    t_idx = safe_m.end()
+                    if t_idx >= total:
+                        return
 
-        for ch in text:
+            ch = text[t_idx]
+            t_idx += 1
             cp = ord(ch)
             if self._pending_prepend:
                 extends, next_state, _ = step_cluster(
@@ -1582,22 +2342,56 @@ def _handle_print(self, text: str) -> None:
                             and can_wrap_row
                             and eff_right - eff_left >= 1
                         ):
+                            prev_cluster_len = self._cluster_len
                             combined = row_obj.chars[pc] + ch
+                            base_pen = row_obj.attr_at(pc) & _WIDTH_CLEAR_MASK
+                            base_ext = row_obj.ext_at(pc)
                             bce_w, bce_e = self._bce_pair()
-                            if eff_left == 0 and eff_right == scr.cols - 1:
+                            full_row_wrap = eff_left == 0 and eff_right == scr.cols - 1
+                            if full_row_wrap and pr == 0 and bottom == 0:
                                 row_obj.write_spacer_head(pc, bce_w, bce_e)
                                 row_obj.wrapped = True
                             else:
                                 row_obj.write_narrow(pc, " ", bce_w, bce_e)
                             self._linefeed(scr)
+                            if full_row_wrap and not (pr == 0 and bottom == 0):
+                                wrap_idx = pr - 1 if pr == bottom else pr
+                                if 0 <= wrap_idx < scr.rows:
+                                    scr._rows[wrap_idx].write_spacer_head(
+                                        pc, bce_w, bce_e
+                                    )
+                                    scr._rows[wrap_idx].wrapped = True
                             nr = scr._cur_row
+                            if not full_row_wrap:
+                                scr.heal_before_edit(nr, eff_left, eff_left + 2)
+                            if insert_mode:
+                                scr._rows[nr].insert_blanks(
+                                    eff_left,
+                                    2,
+                                    left=eff_left,
+                                    right=eff_right,
+                                    bce_word=bce_w,
+                                    bce_ext=bce_e,
+                                )
                             scr._rows[nr].write_wide(
                                 eff_left,
                                 combined,
-                                self._pen_word,
-                                self._cell_ext,
+                                base_pen,
+                                base_ext,
                             )
-                            self._cluster_len += 1
+                            if scr._gfx is not None and scr._gfx.has_sixels:
+                                scr._gfx.erase_sixel_rect(
+                                    row=nr,
+                                    col=eff_left,
+                                    rows=1,
+                                    cols=(
+                                        (eff_right - eff_left + 1) if insert_mode else 2
+                                    ),
+                                    scrolled_total=scr._scrolled_total,
+                                    policy=sixel_pol,
+                                )
+                            self._cluster_state = next_state
+                            self._cluster_len = prev_cluster_len + 1
                             self._last_printed = combined
                             self._last_printed_pos = (nr, eff_left)
                             if eff_left + 1 >= eff_right:
@@ -1633,6 +2427,25 @@ def _handle_print(self, text: str) -> None:
                             and pc + 1 < scr.cols
                         ):
                             scr.heal_before_edit(pr, pc, pc + 2)
+                            if insert_mode and pc + 1 <= eff_right:
+                                bce_w, bce_e = self._bce_pair()
+                                row_obj.insert_blanks(
+                                    pc + 1,
+                                    1,
+                                    left=eff_left,
+                                    right=eff_right,
+                                    bce_word=bce_w,
+                                    bce_ext=bce_e,
+                                )
+                            if scr._gfx is not None and scr._gfx.has_sixels:
+                                scr._gfx.erase_sixel_rect(
+                                    row=pr,
+                                    col=pc,
+                                    rows=1,
+                                    cols=(eff_right - pc + 1) if insert_mode else 2,
+                                    scrolled_total=scr._scrolled_total,
+                                    policy=sixel_pol,
+                                )
                         row_obj.append_grapheme(
                             pc,
                             ch,
@@ -1694,6 +2507,8 @@ def _handle_print(self, text: str) -> None:
                     self._last_printed_pos = None
                     self._pending_prepend = ch
                     self._cluster_state = next_state
+                else:
+                    self._clear_cluster_anchor()
                 continue
 
             c_row = scr._cur_row
@@ -1706,9 +2521,16 @@ def _handle_print(self, text: str) -> None:
                 can_advance = c_row < scr.rows - 1 or (
                     c_row == bottom and left <= c_col <= right
                 )
-                if can_advance and min_col == 0 and c_col == scr.cols - 1:
-                    scr._rows[c_row].wrapped = True
+                set_wrap = can_advance and min_col == 0 and c_col == scr.cols - 1
+                if set_wrap and c_row == 0 and bottom == 0:
+                    scr._rows[0].wrapped = True
+                    bump_row_gen(scr._rows[0])
                 self._linefeed(scr)
+                if set_wrap and not (c_row == 0 and bottom == 0):
+                    wrap_idx = c_row - 1 if c_row == bottom else c_row
+                    if 0 <= wrap_idx < scr.rows:
+                        scr._rows[wrap_idx].wrapped = True
+                        bump_row_gen(scr._rows[wrap_idx])
                 self._set_cursor(scr, scr._cur_row, min_col, pending_wrap=False)
                 c_row = scr._cur_row
                 c_col = scr._cur_col
@@ -1719,13 +2541,20 @@ def _handle_print(self, text: str) -> None:
                 )
                 if autowrap and can_advance and max_col - min_col >= 1:
                     bce_w, bce_e = self._bce_pair()
-                    if min_col == 0 and max_col == scr.cols - 1:
-                        scr._rows[c_row].write_spacer_head(c_col, bce_w, bce_e)
-                        scr._rows[c_row].wrapped = True
+                    full_row_wrap = min_col == 0 and max_col == scr.cols - 1
+                    if full_row_wrap and c_row == 0 and bottom == 0:
+                        scr._rows[0].write_spacer_head(c_col, bce_w, bce_e)
+                        scr._rows[0].wrapped = True
                         just_wrapped_wide = True
                     else:
                         scr._rows[c_row].write_narrow(c_col, " ", bce_w, bce_e)
                     self._linefeed(scr)
+                    if full_row_wrap and not (c_row == 0 and bottom == 0):
+                        wrap_idx = c_row - 1 if c_row == bottom else c_row
+                        if 0 <= wrap_idx < scr.rows:
+                            scr._rows[wrap_idx].write_spacer_head(c_col, bce_w, bce_e)
+                            scr._rows[wrap_idx].wrapped = True
+                        just_wrapped_wide = True
                     self._set_cursor(scr, scr._cur_row, min_col, pending_wrap=False)
                     c_row = scr._cur_row
                     c_col = scr._cur_col
@@ -1755,6 +2584,7 @@ def _handle_print(self, text: str) -> None:
                     self._pen_word,
                     self._cell_ext,
                 )
+                written_cols = 2
                 placed_col = c_col
                 if c_col + 1 >= max_col:
                     self._set_cursor(
@@ -1779,6 +2609,7 @@ def _handle_print(self, text: str) -> None:
                     self._pen_word,
                     self._cell_ext,
                 )
+                written_cols = 1
                 placed_col = c_col
                 if c_col >= max_col:
                     self._set_cursor(
@@ -1797,6 +2628,16 @@ def _handle_print(self, text: str) -> None:
                         clear_cluster=False,
                     )
 
+            if scr._gfx is not None and scr._gfx.has_sixels:
+                scr._gfx.erase_sixel_rect(
+                    row=c_row,
+                    col=placed_col,
+                    rows=1,
+                    cols=(max_col - placed_col + 1) if insert_mode else written_cols,
+                    scrolled_total=scr._scrolled_total,
+                    policy=sixel_pol,
+                )
+
             self._last_printed = ch_full
             self._last_printed_pos = (c_row, placed_col)
             self._cluster_state = next_state
@@ -2005,10 +2846,12 @@ def _apply_mode(self, code: int, *, private: bool, enabled: bool) -> None:
                 self._sync_generation += 1
                 self._sync_hold_pending = True
                 self._held_snapshot = None
+                self._held_sync_token = None
                 self._step_event |= StopOn.SYNC_START
             else:
                 self._sync_hold_pending = False
                 self._held_snapshot = None
+                self._held_sync_token = None
                 self._step_event |= StopOn.SYNC_END
             self._emit_event(
                 RenderHoldChanged(
@@ -2026,11 +2869,13 @@ def _apply_mode(self, code: int, *, private: bool, enabled: bool) -> None:
                     self._save_cursor()
                 self._screens.alternate.reset()
                 self._screens.active_is_alt = True
+                self._epoch += 1
                 self._modes.sync_alt_screen(active_is_alt=True, entered_via=mode)
             elif not enabled and self._screens.active_is_alt:
                 if mode in (Mode.ALT_SCREEN_1047, Mode.ALT_SCREEN):
                     self._screens.alternate.reset()
                 self._screens.active_is_alt = False
+                self._epoch += 1
                 self._modes.sync_alt_screen(active_is_alt=False)
                 if mode == Mode.ALT_SCREEN:
                     self._restore_cursor()
@@ -2093,6 +2938,23 @@ def _erase_display(
         c_row = scr._cur_row
         c_col = scr._cur_col
         phantom = self._profile.pending_wrap_phantom_col and scr._pending_wrap
+        sixel_pol = self._profile.sixel_erase_policy
+        scroll_clear = (
+            not selective
+            and self._profile.ed2_scrolls_primary_to_history
+            and not self._screens.active_is_alt
+            and (mode == 2 or (mode == 0 and c_row == 0 and c_col == 0 and not phantom))
+        )
+        if scroll_clear:
+            scr.push_scrollback_and_clear(
+                bce_w,
+                bce_e,
+                include_cursor_row=False,
+            )
+            self._notify_erase(Rect(0, 0, scr.rows, scr.cols), cause)
+            self._set_cursor(scr, c_row, c_col, pending_wrap=phantom)
+            return
+
         if mode == 0:
             if not phantom:
                 scr.heal_before_edit(c_row, c_col, scr.cols)
@@ -2104,10 +2966,28 @@ def _erase_display(
                     selective=selective,
                 )
                 scr._rows[c_row].wrapped = False
+                if not selective and scr._gfx is not None and scr._gfx.has_sixels:
+                    scr._gfx.erase_sixel_rect(
+                        row=c_row,
+                        col=c_col,
+                        rows=1,
+                        cols=scr.cols - c_col,
+                        scrolled_total=scr._scrolled_total,
+                        policy=sixel_pol,
+                    )
                 self._notify_erase(Rect(c_row, c_col, 1, scr.cols - c_col), cause)
             for r in range(c_row + 1, scr.rows):
                 scr._rows[r].clear_range(0, scr.cols, bce_w, bce_e, selective=selective)
             if c_row + 1 < scr.rows:
+                if not selective and scr._gfx is not None and scr._gfx.has_sixels:
+                    scr._gfx.erase_sixel_rect(
+                        row=c_row + 1,
+                        col=0,
+                        rows=scr.rows - c_row - 1,
+                        cols=scr.cols,
+                        scrolled_total=scr._scrolled_total,
+                        policy=sixel_pol,
+                    )
                 self._notify_erase(
                     Rect(c_row + 1, 0, scr.rows - c_row - 1, scr.cols),
                     cause,
@@ -2124,12 +3004,32 @@ def _erase_display(
                 bce_e,
                 selective=selective,
             )
+            if not selective and scr._gfx is not None and scr._gfx.has_sixels:
+                if c_row > 0:
+                    scr._gfx.erase_sixel_rect(
+                        row=0,
+                        col=0,
+                        rows=c_row,
+                        cols=scr.cols,
+                        scrolled_total=scr._scrolled_total,
+                        policy=sixel_pol,
+                    )
+                scr._gfx.erase_sixel_rect(
+                    row=c_row,
+                    col=0,
+                    rows=1,
+                    cols=end_c,
+                    scrolled_total=scr._scrolled_total,
+                    policy=sixel_pol,
+                )
             if c_row > 0:
                 self._notify_erase(Rect(0, 0, c_row, scr.cols), cause)
             self._notify_erase(Rect(c_row, 0, 1, end_c), cause)
         elif mode == 2:
             for r in range(scr.rows):
                 scr._rows[r].clear_range(0, scr.cols, bce_w, bce_e, selective=selective)
+            if not selective and scr._gfx is not None:
+                scr._gfx.clear_active_screen(scr._scrolled_total, scr.rows)
             self._notify_erase(Rect(0, 0, scr.rows, scr.cols), cause)
         elif mode == 22 and not selective:
             if not self._screens.active_is_alt:
@@ -2137,6 +3037,8 @@ def _erase_display(
             else:
                 for r in range(scr.rows):
                     scr._rows[r].clear_range(0, scr.cols, bce_w, bce_e)
+                if scr._gfx is not None:
+                    scr._gfx.clear_active_screen(scr._scrolled_total, scr.rows)
             self._notify_erase(Rect(0, 0, scr.rows, scr.cols), cause)
         self._set_cursor(scr, c_row, c_col, pending_wrap=phantom)
 
@@ -2157,6 +3059,7 @@ def _erase_line(
         cause = EraseCause.DECSEL if selective else EraseCause.EL
         c_row = scr._cur_row
         c_col = scr._cur_col
+        sixel_pol = self._profile.sixel_erase_policy
         if mode == 0:
             scr.heal_before_edit(c_row, c_col, scr.cols)
             scr._rows[c_row].clear_range(
@@ -2167,6 +3070,15 @@ def _erase_line(
                 selective=selective,
             )
             scr._rows[c_row].wrapped = False
+            if not selective and scr._gfx is not None and scr._gfx.has_sixels:
+                scr._gfx.erase_sixel_rect(
+                    row=c_row,
+                    col=c_col,
+                    rows=1,
+                    cols=scr.cols - c_col,
+                    scrolled_total=scr._scrolled_total,
+                    policy=sixel_pol,
+                )
             self._notify_erase(Rect(c_row, c_col, 1, scr.cols - c_col), cause)
         elif mode == 1:
             end_c = scr.cols if phantom else c_col + 1
@@ -2180,6 +3092,15 @@ def _erase_line(
             )
             if end_c >= scr.cols:
                 scr._rows[c_row].wrapped = False
+            if not selective and scr._gfx is not None and scr._gfx.has_sixels:
+                scr._gfx.erase_sixel_rect(
+                    row=c_row,
+                    col=0,
+                    rows=1,
+                    cols=end_c,
+                    scrolled_total=scr._scrolled_total,
+                    policy=sixel_pol,
+                )
             self._notify_erase(Rect(c_row, 0, 1, end_c), cause)
         elif mode == 2:
             scr.heal_before_edit(c_row, 0, scr.cols)
@@ -2190,6 +3111,15 @@ def _erase_line(
                 bce_e,
                 selective=selective,
             )
+            if not selective and scr._gfx is not None and scr._gfx.has_sixels:
+                scr._gfx.erase_sixel_rect(
+                    row=c_row,
+                    col=0,
+                    rows=1,
+                    cols=scr.cols,
+                    scrolled_total=scr._scrolled_total,
+                    policy=sixel_pol,
+                )
             self._notify_erase(Rect(c_row, 0, 1, scr.cols), cause)
         self._set_cursor(scr, c_row, c_col, pending_wrap=phantom)
 
@@ -2255,7 +3185,8 @@ def _handle_csi(
 
         # DECSTR: CSI ! p
         if prefix == 0 and intermediates == b"!" and final == ord("p"):
-            self.reset(soft=True)
+            if self._profile.decstr_enabled:
+                self.reset(soft=True)
             return
 
         # DECSCUSR: CSI Ps SP q
@@ -2442,6 +3373,15 @@ def _handle_csi(
             scr._rows[c_row].clear_range(c_col, c_col + n, bce_w, bce_e)
             if c_col + n >= scr.cols:
                 scr._rows[c_row].wrapped = False
+            if scr._gfx is not None and scr._gfx.has_sixels:
+                scr._gfx.erase_sixel_rect(
+                    row=c_row,
+                    col=c_col,
+                    rows=1,
+                    cols=n,
+                    scrolled_total=scr._scrolled_total,
+                    policy=self._profile.sixel_erase_policy,
+                )
             self._notify_erase(Rect(c_row, c_col, 1, n), EraseCause.ECH)
             self._set_cursor(scr, c_row, c_col, pending_wrap=False)
         elif ch_final == "@":  # ICH
@@ -2459,6 +3399,15 @@ def _handle_csi(
                 bce_word=bce_w,
                 bce_ext=bce_e,
             )
+            if scr._gfx is not None and scr._gfx.has_sixels and left <= c_col <= right:
+                scr._gfx.erase_sixel_rect(
+                    row=c_row,
+                    col=c_col,
+                    rows=1,
+                    cols=right - c_col + 1,
+                    scrolled_total=scr._scrolled_total,
+                    policy=self._profile.sixel_erase_policy,
+                )
             self._set_cursor(scr, c_row, c_col, pending_wrap=False)
         elif ch_final == "P":  # DCH
             if self._profile.pending_wrap_phantom_col and scr._pending_wrap:
@@ -2467,8 +3416,9 @@ def _handle_csi(
             n = params.get(0, 1)
             bce_w, bce_e = self._bce_pair()
             scr.heal_before_edit(c_row, c_col, right + 1)
-            if c_col == 0 and left == 0 and c_row > 0:
+            if c_col == 0 and left == 0 and c_row > 0 and scr._rows[c_row - 1].wrapped:
                 scr._rows[c_row - 1].wrapped = False
+                bump_row_gen(scr._rows[c_row - 1])
             scr._rows[c_row].delete_cells(
                 c_col,
                 n,
@@ -2479,6 +3429,15 @@ def _handle_csi(
             )
             if right == scr.cols - 1:
                 scr._rows[c_row].wrapped = False
+            if scr._gfx is not None and scr._gfx.has_sixels and left <= c_col <= right:
+                scr._gfx.erase_sixel_rect(
+                    row=c_row,
+                    col=c_col,
+                    rows=1,
+                    cols=right - c_col + 1,
+                    scrolled_total=scr._scrolled_total,
+                    policy=self._profile.sixel_erase_policy,
+                )
             self._set_cursor(scr, c_row, c_col, pending_wrap=False)
         elif ch_final == "L":  # IL
             if top <= c_row <= bottom and left <= c_col <= right:
@@ -2498,6 +3457,7 @@ def _handle_csi(
                     right=right,
                     bce_word=bce_w,
                     bce_ext=bce_e,
+                    is_line_op=True,
                 )
                 self._notify_erase(
                     Rect(c_row, left, min(n, bottom - c_row + 1), right - left + 1),
@@ -2524,6 +3484,7 @@ def _handle_csi(
                     save_history=False,
                     bce_word=bce_w,
                     bce_ext=bce_e,
+                    is_line_op=True,
                 )
                 self._notify_erase(
                     Rect(
@@ -2670,9 +3631,15 @@ def _handle_csi(
             op = params.raw_or_default(0, 0)
             if op == 18:  # report text area size in chars
                 self._emit_reply(f"\x1b[8;{scr.rows};{scr.cols}t".encode("ascii"))
-            elif op == 14:  # report text area size in pixels (16x8 nominal cell)
+            elif op == 14:  # report text area size in pixels
+                px_h = scr.rows * self._profile.cell_height_px
+                px_w = scr.cols * self._profile.cell_width_px
+                self._emit_reply(f"\x1b[4;{px_h};{px_w}t".encode("ascii"))
+            elif op == 16:  # report cell size in pixels
                 self._emit_reply(
-                    f"\x1b[4;{scr.rows * 16};{scr.cols * 8}t".encode("ascii"),
+                    f"\x1b[6;{self._profile.cell_height_px};{self._profile.cell_width_px}t".encode(
+                        "ascii"
+                    ),
                 )
             elif op == 21 and self._policy.allow_title_report:
                 safe_title = "".join(
@@ -2685,6 +3652,7 @@ def _handle_csi(
             elif op == 23 and self._title_stack:  # pop title from stack
                 self._before_mutate()
                 self._title = self._title_stack.pop()
+                self._aux_revision += 1
                 self._emit_event(TitleChanged(title=self._title))
         else:
             self._unhandled("csi", f"CSI {ch_final}")
@@ -2695,7 +3663,9 @@ def _handle_window_rename(self, raw: bytes) -> None:
             name = raw.decode("utf-8", errors="strict")
         except UnicodeDecodeError:
             return
+        self._before_mutate()
         self._window_name = name
+        self._aux_revision += 1
         self._emit_event(WindowRenamed(name=name))
 
     def _update_cwd(self, raw_uri: str, *, from_osc7: bool = True) -> None:
@@ -2780,6 +3750,7 @@ def _handle_osc(self, code: int, data: bytes, terminator: bytes) -> None:
                 prog = int(parts[2]) if len(parts) >= 3 and parts[2].isdigit() else None
                 changed, status = self._status_store.apply_osc_9_4(sub, prog)
                 if changed:
+                    self._aux_revision += 1
                     self._emit_event(ProgramStatusChanged(status=status, task_id=""))
             elif len(parts) >= 2 and parts[0] == "9":
                 self._update_cwd(";".join(parts[1:]), from_osc7=False)
@@ -2847,6 +3818,7 @@ def _handle_osc(self, code: int, data: bytes, terminator: bytes) -> None:
                     abs_row=abs_r,
                 )
                 self._prompt_zones.append(zone)
+                self._aux_revision += 1
                 self._step_event |= StopOn.PROMPT_MARK
                 self._emit_event(PromptMark(zone=zone))
                 if (
@@ -2866,6 +3838,7 @@ def _handle_osc(self, code: int, data: bytes, terminator: bytes) -> None:
             self._before_mutate()
             changed, rec = self._status_store.apply_osc_7501(data)
             if changed:
+                self._aux_revision += 1
                 tid = rec.id if rec is not None else ""
                 self._emit_event(ProgramStatusChanged(status=rec, task_id=tid))
         else:
@@ -2979,13 +3952,45 @@ def _handle_dcs(
 
         # SIXEL: DCS Ps... q  ST
         if prefix == 0 and not intermediates and final == ord("q"):
+            scr = self._screens.active
+            orig_row, orig_col = scr._cur_row, scr._cur_col
+            if self._policy.track_graphics:
+                self._before_mutate()
+                decsdm = self._modes.is_set(Mode.DECSDM)
+                anchor_r = 0 if decsdm else orig_row
+                anchor_c = 0 if decsdm else orig_col
+                gfx = scr.ensure_graphics()
+                prepared = gfx.prepare_sixel(
+                    data,
+                    col=anchor_c,
+                    screen_cols=scr.cols,
+                    cell_width_px=self._profile.cell_width_px,
+                    cell_height_px=self._profile.cell_height_px,
+                )
+                if prepared is not None:
+                    w_px, h_px, s_rows, s_cols = prepared
+                    if decsdm:
+                        post_r = anchor_r
+                        eff_rows = max(1, min(s_rows, scr.rows - anchor_r))
+                    else:
+                        post_r = self._advance_rows(scr, s_rows, final_col=0)
+                        eff_rows = min(s_rows, max(1, scr.rows - post_r))
+                    gfx.commit_sixel(
+                        payload_len=len(data),
+                        width_px=w_px,
+                        height_px=h_px,
+                        row=post_r,
+                        col=anchor_c,
+                        rows=eff_rows,
+                        cols=s_cols,
+                        scrolled_total=scr._scrolled_total,
+                    )
             if self._record_events or self._on_event is not None:
-                scr = self._screens.active
                 self._emit_event(
                     SixelGraphic(
                         data=SixelData(
-                            row=scr._cur_row,
-                            col=scr._cur_col,
+                            row=orig_row,
+                            col=orig_col,
                             params=params.values,
                             payload=data,
                         ),
@@ -2999,7 +4004,14 @@ def _handle_dcs(
     def _handle_apc(self, data: bytes) -> None:
         self._last_printed = ""
         if data.startswith(b"G"):
-            if self._record_events or self._on_event is not None:
+            scr = self._screens.active
+            orig_row, orig_col = scr._cur_row, scr._cur_col
+            need_parse = (
+                self._policy.track_graphics
+                or self._record_events
+                or self._on_event is not None
+            )
+            if need_parse:
                 body = data[1:]
                 sep = body.find(b";")
                 ctrl_bytes = body if sep == -1 else body[:sep]
@@ -3009,17 +4021,42 @@ def _handle_apc(self, data: bytes) -> None:
                     if "=" in pair:
                         k, v = pair.split("=", 1)
                         control[k] = v
-                scr = self._screens.active
-                self._emit_event(
-                    KittyGraphic(
-                        command=KittyCommand(
-                            row=scr._cur_row,
-                            col=scr._cur_col,
-                            control=control,
-                            payload=payload,
+                if self._policy.track_graphics:
+                    self._before_mutate()
+
+                    def _advance_kitty(p_rows: int, p_cols: int) -> int:
+                        target_x = orig_col + p_cols
+                        wraps = target_x >= scr.cols
+                        lf_count = max(0, p_rows - 1) + (1 if wraps else 0)
+                        final_c = 0 if wraps else target_x
+                        return self._advance_rows(scr, lf_count, final_col=final_c)
+
+                    reply = scr.ensure_graphics().handle_kitty(
+                        control,
+                        payload,
+                        cursor_row=orig_row,
+                        cursor_col=orig_col,
+                        screen_rows=scr.rows,
+                        screen_cols=scr.cols,
+                        scrolled_total_getter=lambda: scr._scrolled_total,
+                        scrolled_total=scr._scrolled_total,
+                        cell_width_px=self._profile.cell_width_px,
+                        cell_height_px=self._profile.cell_height_px,
+                        advance_cursor=_advance_kitty,
+                    )
+                    if reply is not None:
+                        self._emit_reply(reply)
+                if self._record_events or self._on_event is not None:
+                    self._emit_event(
+                        KittyGraphic(
+                            command=KittyCommand(
+                                row=orig_row,
+                                col=orig_col,
+                                control=control,
+                                payload=payload,
+                            ),
                         ),
-                    ),
-                )
+                    )
             return
         self._unhandled("apc", f"APC len={len(data)}")
 
@@ -3104,9 +4141,13 @@ def strip(data: collections.abc.Buffer | str, /) -> str:
     "FlightRecorder",
     "Formatter",
     "OutputFormat",
+    "ResyncReason",
+    "ScreenDelta",
     "Snapshot",
     "StepResult",
     "StopOn",
+    "SyncToken",
+    "SyncView",
     "Terminal",
     "render",
     "strip",

From 852eeb5961e88749a7d1f9790948d63a60971b46 Mon Sep 17 00:00:00 2001
From: Tony Narlock 
Date: Sun, 22 Nov 2026 14:17:26 -0600
Subject: [PATCH 22/29] tmux(feat[capture]): Add capture-pane decoder (#18)

why: Attaching to an already-running tmux pane requires reconstructing
live Terminal and Snapshot state from capture-pane output and format
metadata without losing ACS borders, tabstops, wraps, or pending_wrap.

what:
- Add decode_tmux_capture(), TmuxPaneMetadata, parse_flagged_line(), and
  unescape_tmux_control_output() in libvt.tmux and docs/api/tmux.md
- Re-export graphics, incremental sync, and tmux capture APIs from libvt
- Add tests/test_incremental_tmux_and_graphics.py and update CHANGES
---
 CHANGES                                     |  23 +
 docs/api/index.md                           |  14 +
 docs/api/tmux.md                            |   6 +
 src/libvt/__init__.py                       |  42 +
 src/libvt/tmux.py                           | 930 ++++++++++++++++++++
 tests/test_incremental_tmux_and_graphics.py | 705 +++++++++++++++
 6 files changed, 1720 insertions(+)
 create mode 100644 docs/api/tmux.md
 create mode 100644 src/libvt/tmux.py
 create mode 100644 tests/test_incremental_tmux_and_graphics.py

diff --git a/CHANGES b/CHANGES
index 35089b2..380c3bc 100644
--- a/CHANGES
+++ b/CHANGES
@@ -78,6 +78,29 @@ and `vt_pty` fixtures alongside {func}`~libvt.testing.assert_screen`,
 {class}`~libvt.terminal.FlightRecorder` ring buffers. See
 {doc}`topics/sync-and-asyncio` for details.
 
+#### Incremental sync deltas, `tmux` capture reconstruction, and graphics (#13–#18)
+
+{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
+`"committed"` (`?2026`-held) and `"working"` views, paired with
+{meth}`~libvt.terminal.ScreenDelta.apply_lines` and
+{meth}`~libvt.terminal.ScreenDelta.apply_rows`.
+
+{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`
+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).
+{mod}`libvt.graphics` tracks zero-dependency `SIXEL` and Kitty `APC G`
+image metadata ({class}`~libvt.graphics.ImageMeta`) and grid placements
+({class}`~libvt.graphics.ImagePlacement`) across scroll regions and
+profile-specific erase policies. {exc}`~libvt.exc.TerminalTimeoutError`
+attaches multi-line viewport and flight-recorder diagnostics via PEP 678
+`__notes__` while keeping `str(exc)` single-line.
+
 ### Documentation
 
 - Add Architecture Decision Records `0001`–`0010` documenting clean-room
diff --git a/docs/api/index.md b/docs/api/index.md
index 4cf7b57..7bc9310 100644
--- a/docs/api/index.md
+++ b/docs/api/index.md
@@ -57,6 +57,18 @@ Mode-aware `KeyEvent`, `MouseEvent`, `PasteEvent`, and VT sequence `explain`.
 `AsyncTerminalStream`, POSIX `open_pty`, `assert_screen`, and `vt_*` fixtures.
 :::
 
+:::{grid-item-card} `libvt.graphics`
+:link: graphics
+:link-type: doc
+Zero-dependency `SIXEL` and Kitty `APC G` `ImageMeta` and `ImagePlacement`.
+:::
+
+:::{grid-item-card} `libvt.tmux`
+:link: tmux
+:link-type: doc
+`decode_tmux_capture`, `TmuxPaneMetadata`, and `-CC` `%output` unescaping.
+:::
+
 ::::
 
 ## Policy and Guarantees
@@ -99,6 +111,8 @@ events
 status
 input
 codec
+graphics
+tmux
 aio
 testing
 pytest_plugin
diff --git a/docs/api/tmux.md b/docs/api/tmux.md
new file mode 100644
index 0000000..c70d87d
--- /dev/null
+++ b/docs/api/tmux.md
@@ -0,0 +1,6 @@
+# `libvt.tmux`
+
+```{eval-rst}
+.. automodule:: libvt.tmux
+   :members:
+```
diff --git a/src/libvt/__init__.py b/src/libvt/__init__.py
index 5d7301b..c4e28e2 100644
--- a/src/libvt/__init__.py
+++ b/src/libvt/__init__.py
@@ -30,6 +30,7 @@
     DEFAULT_OSC7_HOSTS,
     DEFAULT_POLICY,
     DEFAULT_PROFILE,
+    LINUX_CONSOLE_PROFILE,
     TMUX_CAPTURE_POLICY,
     TMUX_PROFILE,
     XTERM_PROFILE,
@@ -38,6 +39,7 @@
     Limits,
     Policy,
     Profile,
+    SixelErasePolicy,
 )
 from libvt.events import (
     Bell,
@@ -70,6 +72,12 @@
     TerminalTimeoutError,
     UnsafePasteError,
 )
+from libvt.graphics import (
+    GraphicsProtocol,
+    ImageMeta,
+    ImagePlacement,
+    ZLayer,
+)
 from libvt.input import (
     FocusEvent,
     InputEvent,
@@ -114,13 +122,28 @@
     FlightRecorder,
     Formatter,
     OutputFormat,
+    ResyncReason,
+    ScreenDelta,
     Snapshot,
     StepResult,
     StopOn,
+    SyncToken,
+    SyncView,
     Terminal,
     render,
     strip,
 )
+from libvt.tmux import (
+    TMUX_METADATA_FORMAT,
+    CaptureCompleteness,
+    CaptureInput,
+    TmuxCaptureResult,
+    TmuxLineFlags,
+    TmuxPaneMetadata,
+    decode_tmux_capture,
+    parse_flagged_line,
+    unescape_tmux_control_output,
+)
 
 logging.getLogger(__name__).addHandler(logging.NullHandler())
 
@@ -131,13 +154,17 @@
     "DEFAULT_POLICY",
     "DEFAULT_PROFILE",
     "DEFAULT_STYLE",
+    "LINUX_CONSOLE_PROFILE",
     "TMUX_CAPTURE_POLICY",
+    "TMUX_METADATA_FORMAT",
     "TMUX_PROFILE",
     "UNICODE_VERSION",
     "XTERM_PROFILE",
     "AnsiColor",
     "Bell",
     "BlockKind",
+    "CaptureCompleteness",
+    "CaptureInput",
     "Cell",
     "Charset",
     "ClipboardWrite",
@@ -154,7 +181,10 @@
     "FlightRecorder",
     "FocusEvent",
     "Formatter",
+    "GraphicsProtocol",
     "Hyperlink",
+    "ImageMeta",
+    "ImagePlacement",
     "InBandResize",
     "IndexedColor",
     "InputEvent",
@@ -188,30 +218,39 @@
     "Rect",
     "RegionView",
     "RenderHoldChanged",
+    "ResyncReason",
     "RgbColor",
     "RowRun",
     "RowView",
     "Screen",
     "ScreenAssertionError",
+    "ScreenDelta",
     "ScreenErased",
     "ScreenSet",
     "ScrollRegion",
     "SixelData",
+    "SixelErasePolicy",
     "SixelGraphic",
     "Snapshot",
     "StatusState",
     "StepResult",
     "StopOn",
     "Style",
+    "SyncToken",
+    "SyncView",
     "Terminal",
     "TerminalTimeoutError",
     "TitleChanged",
+    "TmuxCaptureResult",
+    "TmuxLineFlags",
+    "TmuxPaneMetadata",
     "UnderlineStyle",
     "UnhandledSequence",
     "UnsafePasteError",
     "WidthRole",
     "WindowRenamed",
     "WorkingDirectoryChanged",
+    "ZLayer",
     "__author__",
     "__copyright__",
     "__description__",
@@ -224,14 +263,17 @@
     "__title__",
     "__tracker__",
     "__version__",
+    "decode_tmux_capture",
     "display_width",
     "encode_input",
     "encode_paste",
     "explain",
     "format_explain",
     "is_safe_paste",
+    "parse_flagged_line",
     "parse_sgr",
     "render",
     "sanitize_terminal_text",
     "strip",
+    "unescape_tmux_control_output",
 ]
diff --git a/src/libvt/tmux.py b/src/libvt/tmux.py
new file mode 100644
index 0000000..c2ce13b
--- /dev/null
+++ b/src/libvt/tmux.py
@@ -0,0 +1,930 @@
+r"""Sans-I/O ``tmux`` ``capture-pane`` and control-mode (``-CC``) decoders."""
+
+from __future__ import annotations
+
+import collections.abc
+import contextlib
+import enum
+import re
+from dataclasses import dataclass
+
+from libvt._grid import WidthRole, _Row, bump_row_gen, raw_width_bits
+from libvt.config import (
+    DEFAULT_LIMITS,
+    TMUX_CAPTURE_POLICY,
+    TMUX_PROFILE,
+    Limits,
+    Policy,
+    Profile,
+)
+from libvt.events import PromptKind, PromptZone
+from libvt.modes import DEC_PRIVATE_MASK, Mode
+from libvt.parser import CsiParams, Parser
+from libvt.screen import Screen, ScrollRegion
+from libvt.style import DEFAULT_STYLE
+from libvt.terminal import Snapshot, Terminal
+
+type CaptureInput = str | bytes | collections.abc.Sequence[str]
+
+TMUX_METADATA_FORMAT: str = (
+    "#{pane_width}\t#{pane_height}\t#{cursor_x}\t#{cursor_y}\t"
+    "#{cursor_flag}\t#{alternate_on}\t#{alternate_saved_x}\t"
+    "#{alternate_saved_y}\t#{scroll_region_upper}\t#{scroll_region_lower}\t"
+    "#{insert_flag}\t#{origin_flag}\t#{wrap_flag}\t#{keypad_cursor_flag}\t"
+    "#{bracket_paste_flag}\t#{mouse_standard_flag}\t#{mouse_button_flag}\t"
+    "#{mouse_all_flag}\t#{mouse_sgr_flag}\t#{pane_private_modes}\t"
+    "#{pane_tabs}\t#{history_size}\t#{history_limit}\t"
+    "#{pane_synchronized}\t#{pane_output_generation}\t"
+    "#{pane_current_path}\t#{pane_title}"
+)
+
+_FLAG_TOKEN_RE = re.compile(r"^(?:-|D?H?O?P?W?X?)$")
+_OCTAL_ESCAPE_RE = re.compile(rb"\\([0-3][0-7]{2})")
+_TMUX_UINT_MAX = 0xFFFF_FFFF
+
+_BASE_UNEXPOSED_FIELDS: frozenset[str] = frozenset(
+    {
+        "active_pen_sgr",
+        "cursor_shape",
+        "decom_saved_cursor",
+        "decsc_saved_cursor",
+        "g0_g3_charsets",
+        "gl_shift",
+        "kitty_keyboard_flags",
+    },
+)
+
+
+class TmuxLineFlags(enum.IntFlag):
+    """Per-line flags emitted by ``tmux capture-pane -F`` (``tmux >= 3.8``)."""
+
+    NONE = 0
+    DEAD = 1
+    HYPERLINK = 2
+    START_OUTPUT = 4
+    START_PROMPT = 8
+    WRAPPED = 16
+    EXTENDED = 32
+
+
+_CHAR_TO_LINE_FLAG: dict[str, TmuxLineFlags] = {
+    "D": TmuxLineFlags.DEAD,
+    "H": TmuxLineFlags.HYPERLINK,
+    "O": TmuxLineFlags.START_OUTPUT,
+    "P": TmuxLineFlags.START_PROMPT,
+    "W": TmuxLineFlags.WRAPPED,
+    "X": TmuxLineFlags.EXTENDED,
+}
+
+
+def parse_flagged_line(line: str) -> tuple[TmuxLineFlags, str]:
+    r"""Split a ``tmux capture-pane -F`` line into ``(flags, body)``.
+
+    Parameters
+    ----------
+    line : str
+        Single line emitted by ``tmux capture-pane -F`` (without trailing
+        ``\n``).
+
+    Returns
+    -------
+    tuple[TmuxLineFlags, str]
+        Parsed :class:`TmuxLineFlags` and remaining SGR/text payload.
+
+    Raises
+    ------
+    ValueError
+        If *line* does not start with a valid ```` space-delimited prefix.
+    """
+    raw_flags, sep, body = line.partition(" ")
+    if not sep or not raw_flags or _FLAG_TOKEN_RE.match(raw_flags) is None:
+        msg = f"invalid tmux capture-pane -F line prefix: {line[:24]!r}"
+        raise ValueError(msg)
+    flags = TmuxLineFlags.NONE
+    if raw_flags != "-":
+        for ch in raw_flags:
+            flags |= _CHAR_TO_LINE_FLAG[ch]
+    return flags, body
+
+
+def unescape_tmux_control_output(data: collections.abc.Buffer | str) -> bytes:
+    r"""Decode ``tmux -CC`` ``%output`` octal escapes into raw PTY bytes.
+
+    ``tmux`` control mode escapes bytes ``< 0x20`` and backslash (``0x5c`` ->
+    ``\134``) as three-digit octal sequences ``\ooo`` while passing printable
+    ASCII and UTF-8 bytes verbatim (including split multi-byte UTF-8 sequences).
+
+    Parameters
+    ----------
+    data : collections.abc.Buffer | str
+        Escaped payload following ``%output %``.
+
+    Returns
+    -------
+    bytes
+        Unescaped raw VT byte stream ready for :meth:`~libvt.terminal.Terminal.feed`.
+    """
+    raw = (
+        data.encode("utf-8", errors="surrogateescape")
+        if isinstance(data, str)
+        else bytes(data)
+    )
+    if b"\\" not in raw:
+        return raw
+    return _OCTAL_ESCAPE_RE.sub(lambda m: bytes((int(m.group(1), 8),)), raw)
+
+
+def _opt_int(raw: str, default: int) -> int:
+    s = raw.strip()
+    if not s:
+        return default
+    try:
+        return int(s)
+    except ValueError:
+        return default
+
+
+def _opt_saved_coord(raw: str) -> int | None:
+    s = raw.strip()
+    if not s:
+        return None
+    try:
+        val = int(s)
+    except ValueError:
+        return None
+    if val < 0 or val >= _TMUX_UINT_MAX:
+        return None
+    return val
+
+
+def _opt_bool(raw: str, *, default: bool = False) -> bool:
+    s = raw.strip()
+    if not s:
+        return default
+    return s != "0"
+
+
+@dataclass(frozen=True, slots=True)
+class TmuxPaneMetadata:
+    """Out-of-band ``tmux`` pane state queried via :data:`TMUX_METADATA_FORMAT`.
+
+    Attributes
+    ----------
+    cols : int
+        Pane width in columns (``#{pane_width}``).
+    rows : int
+        Pane height in rows (``#{pane_height}``).
+    cursor_x : int
+        Raw zero-based ``#{cursor_x}`` (equals ``cols`` when ``pending_wrap``
+        is active in ``tmux``).
+    cursor_y : int
+        Zero-based ``#{cursor_y}``.
+    cursor_visible : bool
+        ``True`` when ``#{cursor_flag}`` is non-zero.
+    alternate_on : bool
+        ``True`` when ``#{alternate_on}`` indicates an active alternate screen.
+    alternate_saved_x : int | None
+        Saved primary-screen ``x`` (``#{alternate_saved_x}``; ``None`` when
+        ``tmux`` reports ``UINT_MAX`` under ``?47``/``?1047``).
+    alternate_saved_y : int | None
+        Saved primary-screen ``y`` (``#{alternate_saved_y}``; ``None`` when
+        unset).
+    scroll_region_upper : int
+        Zero-based top scroll margin (``#{scroll_region_upper}``).
+    scroll_region_lower : int | None
+        Zero-based bottom scroll margin (``None`` defaults to ``rows - 1``).
+    insert_flag : bool
+        ``IRM`` insert mode (``#{insert_flag}``).
+    origin_flag : bool
+        ``DECOM`` origin mode (``#{origin_flag}``).
+    wrap_flag : bool
+        ``DECAWM`` autowrap mode (``#{wrap_flag}``).
+    keypad_cursor_flag : bool
+        ``DECCKM`` application cursor keys (``#{keypad_cursor_flag}``).
+    bracketed_paste_flag : bool
+        ``?2004`` bracketed paste mode (``#{bracket_paste_flag}``).
+    mouse_standard_flag : bool
+        ``?1000`` VT200 mouse reporting (``#{mouse_standard_flag}``).
+    mouse_button_flag : bool
+        ``?1002`` button-event mouse reporting (``#{mouse_button_flag}``).
+    mouse_any_flag : bool
+        ``?1003`` all-motion mouse reporting (``#{mouse_all_flag}``).
+    mouse_sgr_flag : bool
+        ``?1006`` SGR mouse encoding (``#{mouse_sgr_flag}``).
+    focus_events_flag : bool
+        ``?1004`` focus-in/out reporting (from ``#{pane_private_modes}``).
+    private_modes : frozenset[int]
+        DEC private mode numbers parsed from ``#{pane_private_modes}``.
+    pane_tabs : tuple[int, ...] | None
+        Sorted zero-based tabstop columns from ``#{pane_tabs}``, or ``None`` to
+        use standard 8-column tabstops.
+    history_size : int
+        Current scrollback line count (``#{history_size}``).
+    history_limit : int
+        Pane ``history-limit`` (``#{history_limit}``).
+    synchronized : bool
+        ``?2026`` synchronized-output hold state (``#{pane_synchronized}``).
+    output_generation : int | None
+        ``#{pane_output_generation}`` counter on ``tmux >= 3.8``, else ``None``.
+    cwd : str
+        ``#{pane_current_path}``, if available.
+    title : str
+        ``#{pane_title}``, if available.
+    """
+
+    cols: int = 80
+    rows: int = 24
+    cursor_x: int = 0
+    cursor_y: int = 0
+    cursor_visible: bool = True
+    alternate_on: bool = False
+    alternate_saved_x: int | None = None
+    alternate_saved_y: int | None = None
+    scroll_region_upper: int = 0
+    scroll_region_lower: int | None = None
+    insert_flag: bool = False
+    origin_flag: bool = False
+    wrap_flag: bool = True
+    keypad_cursor_flag: bool = False
+    bracketed_paste_flag: bool = False
+    mouse_standard_flag: bool = False
+    mouse_button_flag: bool = False
+    mouse_any_flag: bool = False
+    mouse_sgr_flag: bool = False
+    focus_events_flag: bool = False
+    private_modes: frozenset[int] = frozenset()
+    pane_tabs: tuple[int, ...] | None = None
+    history_size: int = 0
+    history_limit: int = 2_000
+    synchronized: bool = False
+    output_generation: int | None = None
+    cwd: str = ""
+    title: str = ""
+
+    @property
+    def pending_wrap(self) -> bool:
+        """Return ``True`` when ``cursor_x >= cols`` encodes ``pending_wrap``."""
+        return self.cursor_x >= self.cols and self.wrap_flag
+
+    @property
+    def clamped_cursor_col(self) -> int:
+        """Return zero-based cursor column clamped into ``[0, cols - 1]``."""
+        return min(max(0, self.cursor_x), max(0, self.cols - 1))
+
+    @property
+    def clamped_cursor_row(self) -> int:
+        """Return zero-based cursor row clamped into ``[0, rows - 1]``."""
+        return min(max(0, self.cursor_y), max(0, self.rows - 1))
+
+    @classmethod
+    def from_format_line(cls, line: str) -> TmuxPaneMetadata:
+        """Parse one line emitted by ``display-message -p TMUX_METADATA_FORMAT``."""
+        cleaned = line.rstrip("\r\n")
+        parts = cleaned.split("\t", 26)
+        if len(parts) < 27:
+            parts.extend([""] * (27 - len(parts)))
+        cols = max(1, _opt_int(parts[0], 80))
+        rows = max(1, _opt_int(parts[1], 24))
+
+        priv_raw = parts[19].strip()
+        priv_modes: set[int] = set()
+        focus_on = False
+        if priv_raw in ("0", "1"):
+            focus_on = priv_raw == "1"
+        elif priv_raw:
+            for tok in priv_raw.split(","):
+                p_str = tok.strip().lstrip("?")
+                if p_str.isdigit():
+                    priv_modes.add(int(p_str))
+            focus_on = 1004 in priv_modes
+
+        tabs_raw = parts[20].strip()
+        tabs: tuple[int, ...] | None = None
+        if tabs_raw:
+            parsed_tabs: list[int] = []
+            for tok in tabs_raw.split(","):
+                t_str = tok.strip()
+                if t_str.isdigit():
+                    parsed_tabs.append(int(t_str))
+            tabs = tuple(sorted(set(parsed_tabs)))
+        gen_raw = parts[24].strip()
+        out_gen = int(gen_raw) if gen_raw.isdigit() else None
+        sr_low_raw = parts[9].strip()
+        sr_lower = int(sr_low_raw) if sr_low_raw.isdigit() else (rows - 1)
+        return cls(
+            cols=cols,
+            rows=rows,
+            cursor_x=_opt_int(parts[2], 0),
+            cursor_y=_opt_int(parts[3], 0),
+            cursor_visible=_opt_bool(parts[4], default=True),
+            alternate_on=_opt_bool(parts[5]),
+            alternate_saved_x=_opt_saved_coord(parts[6]),
+            alternate_saved_y=_opt_saved_coord(parts[7]),
+            scroll_region_upper=_opt_int(parts[8], 0),
+            scroll_region_lower=sr_lower,
+            insert_flag=_opt_bool(parts[10]),
+            origin_flag=_opt_bool(parts[11]),
+            wrap_flag=_opt_bool(parts[12], default=True),
+            keypad_cursor_flag=_opt_bool(parts[13]),
+            bracketed_paste_flag=_opt_bool(parts[14]) or (2004 in priv_modes),
+            mouse_standard_flag=_opt_bool(parts[15]) or (1000 in priv_modes),
+            mouse_button_flag=_opt_bool(parts[16]) or (1002 in priv_modes),
+            mouse_any_flag=_opt_bool(parts[17]) or (1003 in priv_modes),
+            mouse_sgr_flag=_opt_bool(parts[18]) or (1006 in priv_modes),
+            focus_events_flag=focus_on,
+            private_modes=frozenset(priv_modes),
+            pane_tabs=tabs,
+            history_size=_opt_int(parts[21], 0),
+            history_limit=max(0, _opt_int(parts[22], 2_000)),
+            synchronized=_opt_bool(parts[23]) or (2026 in priv_modes),
+            output_generation=out_gen,
+            cwd=parts[25],
+            title=parts[26],
+        )
+
+
+@dataclass(frozen=True, slots=True)
+class CaptureCompleteness:
+    """Explicit fidelity report for a decoded ``tmux capture-pane`` snapshot.
+
+    Attributes
+    ----------
+    exact_cells : bool
+        ``True`` when cell glyphs, styles, and tab expansions were decoded from
+        ``-e -p -N`` output.
+    exact_wraps : bool
+        ``True`` when soft-wrap flags came from ``-F`` or an exact ``-J``
+        companion capture.
+    exact_generation_bracket : bool
+        ``True`` when pre- and post-capture ``pane_output_generation`` counters
+        were supplied and matched.
+    unexposed_fields : frozenset[str]
+        Internal terminal state fields that ``tmux`` does not expose through
+        format variables or ``capture-pane``.
+    """
+
+    exact_cells: bool
+    exact_wraps: bool
+    exact_generation_bracket: bool
+    unexposed_fields: frozenset[str]
+
+
+@dataclass(frozen=True, slots=True)
+class TmuxCaptureResult:
+    """Decoded ``tmux`` capture bundle ready for inspection or live streaming.
+
+    Attributes
+    ----------
+    terminal : Terminal
+        Reconstructed :class:`~libvt.terminal.Terminal` configured with
+        ``profile`` and ready for subsequent :meth:`~libvt.terminal.Terminal.feed`
+        bytes.
+    snapshot : Snapshot
+        Immutable :class:`~libvt.terminal.Snapshot` of *terminal*.
+    completeness : CaptureCompleteness
+        Fidelity flags and terminal fields not exposed by ``tmux``.
+    line_flags : tuple[TmuxLineFlags, ...]
+        Per-line flags across ``history + viewport`` (all ``NONE`` when
+        ``flagged=False``).
+    """
+
+    terminal: Terminal
+    snapshot: Snapshot
+    completeness: CaptureCompleteness
+    line_flags: tuple[TmuxLineFlags, ...]
+
+
+class _CaptureRowSink:
+    r"""Internal parser sink expanding ``GRID_FLAG_TAB`` ``\t`` with active SGR."""
+
+    __slots__ = ("_cols", "_scratch", "_tabstops")
+
+    def __init__(
+        self,
+        scratch: Terminal,
+        cols: int,
+        tabstops: tuple[int, ...],
+    ) -> None:
+        self._scratch = scratch
+        self._cols = cols
+        self._tabstops = tabstops
+
+    def on_print(self, text: str) -> None:
+        self._scratch._handle_print(text)
+
+    def on_execute(self, byte: int) -> None:
+        if byte == 0x09:
+            cur_col = self._scratch.screen._cur_col
+            nxt = next(
+                (t_col for t_col in self._tabstops if cur_col < t_col < self._cols),
+                self._cols,
+            )
+            span = max(1, min(self._cols - cur_col, nxt - cur_col))
+            self._scratch._handle_print(" " * span)
+            return
+        if byte in (0x0E, 0x0F):
+            self._scratch._handle_execute(byte)
+
+    def on_esc(self, intermediates: bytes, final: int) -> None:
+        self._scratch._handle_esc(intermediates, final)
+
+    def on_csi(
+        self,
+        prefix: int,
+        params: CsiParams,
+        intermediates: bytes,
+        final: int,
+    ) -> None:
+        self._scratch._handle_csi(prefix, params, intermediates, final)
+
+    def on_osc(self, code: int, data: bytes, terminator: bytes) -> None:
+        self._scratch._handle_osc(code, data, terminator)
+
+    def on_dcs(
+        self,
+        prefix: int,
+        params: CsiParams,
+        intermediates: bytes,
+        final: int,
+        data: bytes,
+    ) -> None:
+        self._scratch._handle_dcs(prefix, params, intermediates, final, data)
+
+    def on_apc(self, data: bytes) -> None:
+        self._scratch._handle_apc(data)
+
+
+def _split_capture_lines(raw: CaptureInput) -> list[str]:
+    if isinstance(raw, collections.abc.Sequence) and not isinstance(
+        raw, (str, bytes, bytearray)
+    ):
+        return [ln.rstrip("\r\n") for ln in raw]
+    text = (
+        bytes(raw).decode("utf-8", errors="replace")
+        if isinstance(raw, (bytes, bytearray))
+        else raw
+    )
+    text = text.removesuffix("\n")
+    if not text:
+        return []
+    return text.split("\n")
+
+
+def _row_trimmed_text_and_cols(row: _Row) -> tuple[str, int]:
+    t_end = row.text_used
+    while t_end > 0 and row.chars[t_end - 1] == " ":
+        t_end -= 1
+    return "".join(row.chars[:t_end]), t_end
+
+
+def _infer_wraps_from_joined(
+    plain_rows: list[str],
+    row_used_cols: list[int],
+    joined_raw: CaptureInput,
+    cols: int,
+) -> list[bool] | None:
+    joined_lines = _split_capture_lines(joined_raw)
+    n = len(plain_rows)
+    if len(joined_lines) == n:
+        return [False] * n
+    if len(joined_lines) > n:
+        return None
+    wraps = [False] * n
+    r_idx = 0
+    for j_line in joined_lines:
+        if r_idx >= n or not j_line.startswith(plain_rows[r_idx]):
+            return None
+        pos = len(plain_rows[r_idx])
+        while r_idx + 1 < n and pos < len(j_line):
+            pad = max(0, cols - row_used_cols[r_idx])
+            nxt = plain_rows[r_idx + 1]
+            if (
+                pad > 0
+                and j_line.startswith(" " * pad, pos)
+                and j_line.startswith(nxt, pos + pad)
+            ):
+                wraps[r_idx] = True
+                pos += pad + len(nxt)
+                r_idx += 1
+            elif j_line.startswith(nxt, pos):
+                wraps[r_idx] = True
+                pos += len(nxt)
+                r_idx += 1
+            else:
+                break
+        if pos != len(j_line):
+            return None
+        r_idx += 1
+    return wraps if r_idx == n else None
+
+
+def _trim_unwrapped_row(row: _Row) -> None:
+    while row.text_used > 0 and row.chars[row.text_used - 1] == " ":
+        row.text_used -= 1
+    while (
+        row.used > row.text_used
+        and row.chars[row.used - 1] == " "
+        and row.attr_at(row.used - 1) == 0
+        and row.ext_at(row.used - 1) is None
+    ):
+        row.used -= 1
+
+
+def _populate_screen_from_lines(
+    target: Screen,
+    raw_lines: list[str],
+    *,
+    rows: int,
+    cols: int,
+    tabstops: tuple[int, ...],
+    flagged: bool,
+    joined_capture: CaptureInput | None,
+    profile: Profile,
+    policy: Policy,
+    limits: Limits,
+) -> tuple[tuple[TmuxLineFlags, ...], bool, list[PromptZone]]:
+    flags_list: list[TmuxLineFlags] = []
+    bodies: list[str] = []
+    if flagged:
+        for ln in raw_lines:
+            fl, body = parse_flagged_line(ln)
+            flags_list.append(fl)
+            bodies.append(body)
+    else:
+        flags_list = [TmuxLineFlags.NONE] * len(raw_lines)
+        bodies = list(raw_lines)
+
+    scratch = Terminal(
+        rows=1,
+        cols=cols,
+        scrollback=0,
+        profile=profile,
+        policy=policy,
+        limits=limits,
+    )
+    scratch.modes.set_mode(Mode.DECAWM, enabled=False)
+    # Pre-seed G0='B' and G1='0' on the capture scratch decoder so bare
+    # 0x0e / 0x0f (SO / SI) emitted by tmux grid_string_cells_code decode ACS.
+    scratch._g_sets = ["B", "0", "B", "B"]
+    scratch._gl = 0
+
+    line_parser = Parser(limits=limits)
+    sink = _CaptureRowSink(scratch, cols, tabstops)
+    decoded_rows: list[_Row] = []
+    for body in bodies:
+        scratch_row = scratch.screen._rows[0]
+        scratch_row.reset_blank(cols)
+        scratch._set_cursor(scratch.screen, 0, 0, pending_wrap=False)
+        line_parser.reset()
+        line_parser.feed_to(body.encode("utf-8", errors="surrogateescape"), sink)
+        decoded_rows.append(scratch_row.clone())
+
+    row_wraps: list[bool]
+    exact_wraps = flagged
+    if flagged:
+        row_wraps = [bool(fl & TmuxLineFlags.WRAPPED) for fl in flags_list]
+    elif joined_capture is not None and decoded_rows:
+        trimmed_pairs = [_row_trimmed_text_and_cols(r) for r in decoded_rows]
+        plain_texts = [pair[0] for pair in trimmed_pairs]
+        used_cols = [pair[1] for pair in trimmed_pairs]
+        inferred = _infer_wraps_from_joined(
+            plain_texts, used_cols, joined_capture, cols
+        )
+        if inferred is not None:
+            exact_wraps = True
+            row_wraps = inferred
+        else:
+            row_wraps = [False] * len(decoded_rows)
+    else:
+        row_wraps = [False] * len(decoded_rows)
+
+    for idx, row_obj in enumerate(decoded_rows):
+        row_obj.wrapped = row_wraps[idx]
+        if not row_wraps[idx]:
+            _trim_unwrapped_row(row_obj)
+
+    for i in range(len(decoded_rows) - 1):
+        cur_r = decoded_rows[i]
+        nxt_r = decoded_rows[i + 1]
+        if cur_r.wrapped and raw_width_bits(nxt_r.attr_at(0)) == int(WidthRole.WIDE):
+            _, trimmed_cols = _row_trimmed_text_and_cols(cur_r)
+            if trimmed_cols == cols - 1:
+                cur_r.write_spacer_head(cols - 1, 0, None)
+                cur_r.wrapped = True
+
+    total = len(decoded_rows)
+    hist_count = max(0, total - rows)
+    target._history.clear()
+    maxlen = target._history.maxlen
+    keep_hist = min(hist_count, maxlen) if (maxlen is not None and maxlen > 0) else 0
+    dropped_hist = hist_count - keep_hist
+    if keep_hist > 0:
+        for r_h in decoded_rows[dropped_hist:hist_count]:
+            target._history.append(r_h.freeze())
+    target._scrolled_total = hist_count
+    target._evicted_total = dropped_hist
+
+    view_rows = decoded_rows[hist_count : hist_count + rows]
+    while len(view_rows) < rows:
+        view_rows.append(_Row(cols))
+    for r_v in view_rows:
+        bump_row_gen(r_v)
+    target._rows = view_rows
+
+    zones: list[PromptZone] = []
+    for idx in range(dropped_hist, len(flags_list)):
+        fl = flags_list[idx]
+        abs_r = idx
+        rel_r = idx - hist_count
+        if fl & TmuxLineFlags.START_PROMPT:
+            zones.append(
+                PromptZone(
+                    kind=PromptKind.PROMPT_START,
+                    row=rel_r,
+                    col=0,
+                    abs_row=abs_r,
+                ),
+            )
+        if fl & TmuxLineFlags.START_OUTPUT:
+            zones.append(
+                PromptZone(
+                    kind=PromptKind.COMMAND_EXECUTED,
+                    row=rel_r,
+                    col=0,
+                    abs_row=abs_r,
+                ),
+            )
+
+    return tuple(flags_list), exact_wraps, zones
+
+
+def decode_tmux_capture(
+    captured: CaptureInput,
+    *,
+    metadata: TmuxPaneMetadata | str | None = None,
+    rows: int = 24,
+    cols: int = 80,
+    scrollback: int | None = None,
+    flagged: bool = False,
+    joined_capture: CaptureInput | None = None,
+    saved_primary_capture: CaptureInput | None = None,
+    saved_primary_flagged: bool | None = None,
+    post_metadata: TmuxPaneMetadata | str | None = None,
+    profile: Profile = TMUX_PROFILE,
+    policy: Policy = TMUX_CAPTURE_POLICY,
+    limits: Limits = DEFAULT_LIMITS,
+) -> TmuxCaptureResult:
+    r"""Reconstruct a :class:`~libvt.terminal.Terminal` from ``tmux capture-pane``.
+
+    Handles bare ``SO``/``SI`` (``0x0e``/``0x0f``) ACS box-drawing runs without
+    polluting the reconstructed terminal's live ``G1`` charset, expands
+    ``GRID_FLAG_TAB`` ``\t`` cells against ``#{pane_tabs}`` while preserving
+    active SGR background/attributes, carries SGR across rows just like
+    ``tmux``'s ``grid_string_cells(&gc)``, reconstructs ``pending_wrap`` from
+    ``cursor_x >= pane_width``, and optionally populates backgrounded primary
+    history when ``alternate_on`` is active.
+
+    Parameters
+    ----------
+    captured : CaptureInput
+        Output of ``tmux capture-pane -S - -E - -e -p -N [-F]`` as ``str``,
+        ``bytes``, or a line sequence (e.g. ``libtmux`` ``Pane.capture_pane``).
+    metadata : TmuxPaneMetadata | str | None
+        Parsed :class:`TmuxPaneMetadata` or raw format line emitted by
+        ``display-message -p TMUX_METADATA_FORMAT``; when ``None``, *rows*,
+        *cols*, and *scrollback* defaults are used.
+    rows : int
+        Fallback pane height when *metadata* is ``None``.
+    cols : int
+        Fallback pane width when *metadata* is ``None``.
+    scrollback : int | None
+        Explicit scrollback line cap; when ``None``, defaults to
+        ``metadata.history_limit`` if *metadata* is provided, else ``2000``.
+    flagged : bool
+        ``True`` when *captured* includes ``capture-pane -F`` line prefixes.
+    joined_capture : CaptureInput | None
+        Optional ``capture-pane -S - -E - -p -J`` output used to infer soft
+        wraps on ``tmux < 3.8`` when ``flagged=False``.
+    saved_primary_capture : CaptureInput | None
+        Optional ``capture-pane -a -q -S - -E - -e -p -N [-F]`` output restoring
+        the backgrounded primary screen and scrollback when ``alternate_on`` is
+        ``True``.
+    saved_primary_flagged : bool | None
+        Whether *saved_primary_capture* carries ``-F`` prefixes (defaults to
+        *flagged*).
+    post_metadata : TmuxPaneMetadata | str | None
+        Optional second metadata sample taken immediately after ``capture-pane``
+        to verify ``pane_output_generation`` stability.
+    profile : Profile
+        Compatibility profile for the reconstructed terminal.
+    policy : Policy
+        Security policy for the reconstructed terminal.
+    limits : Limits
+        Resource ceilings for the reconstructed terminal.
+
+    Returns
+    -------
+    TmuxCaptureResult
+        Reconstructed terminal, immutable snapshot, completeness report, and
+        parsed per-line flags.
+    """
+    fallback_sb = 2_000 if scrollback is None else scrollback
+    if isinstance(metadata, str):
+        meta = TmuxPaneMetadata.from_format_line(metadata)
+    elif metadata is not None:
+        meta = metadata
+    else:
+        meta = TmuxPaneMetadata(cols=cols, rows=rows, history_limit=fallback_sb)
+
+    post_meta = (
+        TmuxPaneMetadata.from_format_line(post_metadata)
+        if isinstance(post_metadata, str)
+        else post_metadata
+    )
+
+    eff_rows = max(1, meta.rows)
+    eff_cols = max(1, meta.cols)
+    eff_scrollback = (
+        scrollback
+        if scrollback is not None
+        else (meta.history_limit if metadata is not None else 2_000)
+    )
+    tabstops = (
+        tuple(sorted({t for t in meta.pane_tabs if 0 < t < eff_cols}))
+        if meta.pane_tabs is not None
+        else tuple(range(8, eff_cols, 8))
+    )
+
+    term = Terminal(
+        rows=eff_rows,
+        cols=eff_cols,
+        scrollback=eff_scrollback,
+        profile=profile,
+        policy=policy,
+        limits=limits,
+    )
+
+    term._tabstops_from_list(term.screens.primary, tabstops)
+    term._tabstops_from_list(term.screens.alternate, tabstops)
+
+    raw_lines = _split_capture_lines(captured)
+    if meta.alternate_on:
+        if saved_primary_capture is not None:
+            prim_lines = _split_capture_lines(saved_primary_capture)
+            prim_flagged = (
+                flagged if saved_primary_flagged is None else saved_primary_flagged
+            )
+            _, _, prim_zones = _populate_screen_from_lines(
+                term.screens.primary,
+                prim_lines,
+                rows=eff_rows,
+                cols=eff_cols,
+                tabstops=tabstops,
+                flagged=prim_flagged,
+                joined_capture=None,
+                profile=profile,
+                policy=policy,
+                limits=limits,
+            )
+            for z in prim_zones:
+                term._prompt_zones.append(z)
+        has_saved_xy = (
+            meta.alternate_saved_x is not None or meta.alternate_saved_y is not None
+        )
+        saved_x = 0 if meta.alternate_saved_x is None else meta.alternate_saved_x
+        saved_y = 0 if meta.alternate_saved_y is None else meta.alternate_saved_y
+        term.screens.primary._cur_row = min(eff_rows - 1, max(0, saved_y))
+        term.screens.primary._cur_col = min(eff_cols - 1, max(0, saved_x))
+        term.screens.primary._pending_wrap = saved_x >= eff_cols and meta.wrap_flag
+        term._saved_primary = term._saved_primary.__class__(
+            row=term.screens.primary._cur_row,
+            col=term.screens.primary._cur_col,
+            pending_wrap=term.screens.primary._pending_wrap,
+            style=DEFAULT_STYLE,
+            decom=False,
+            g_sets=("B", profile.default_g1_charset, "B", "B"),
+            gl=0,
+            protected=False,
+        )
+        term.screens.active_is_alt = True
+        entered_mode = Mode.ALT_SCREEN if has_saved_xy else Mode.ALT_SCREEN_1047
+        term.modes.sync_alt_screen(active_is_alt=True, entered_via=entered_mode)
+        line_flags, exact_wraps, _ = _populate_screen_from_lines(
+            term.screens.alternate,
+            raw_lines[-eff_rows:],
+            rows=eff_rows,
+            cols=eff_cols,
+            tabstops=tabstops,
+            flagged=flagged,
+            joined_capture=joined_capture,
+            profile=profile,
+            policy=policy,
+            limits=limits,
+        )
+    else:
+        line_flags, exact_wraps, zones = _populate_screen_from_lines(
+            term.screens.primary,
+            raw_lines,
+            rows=eff_rows,
+            cols=eff_cols,
+            tabstops=tabstops,
+            flagged=flagged,
+            joined_capture=joined_capture,
+            profile=profile,
+            policy=policy,
+            limits=limits,
+        )
+        for z in zones:
+            term._prompt_zones.append(z)
+
+    active = term.screens.active
+    sr_top = max(0, min(eff_rows - 1, meta.scroll_region_upper))
+    sr_bot_raw = (
+        (eff_rows - 1) if meta.scroll_region_lower is None else meta.scroll_region_lower
+    )
+    sr_bot = max(sr_top, min(eff_rows - 1, sr_bot_raw))
+    active.scroll_region = ScrollRegion(
+        top=sr_top,
+        bottom=sr_bot,
+        left=0,
+        right=eff_cols - 1,
+    )
+
+    term.modes.set_mode(Mode.DECAWM, enabled=meta.wrap_flag)
+    term.modes.set_mode(Mode.IRM, enabled=meta.insert_flag)
+    term.modes.set_mode(Mode.DECOM, enabled=meta.origin_flag)
+    term.modes.set_mode(Mode.DECTCEM, enabled=meta.cursor_visible)
+    term.modes.set_mode(Mode.DECCKM, enabled=meta.keypad_cursor_flag)
+    term.modes.set_mode(Mode.BRACKETED_PASTE, enabled=meta.bracketed_paste_flag)
+    term.modes.set_mode(Mode.MOUSE_VT200, enabled=meta.mouse_standard_flag)
+    term.modes.set_mode(Mode.MOUSE_BUTTON_EVENT, enabled=meta.mouse_button_flag)
+    term.modes.set_mode(Mode.MOUSE_ANY_EVENT, enabled=meta.mouse_any_flag)
+    term.modes.set_mode(Mode.MOUSE_SGR, enabled=meta.mouse_sgr_flag)
+    term.modes.set_mode(Mode.FOCUS_EVENT, enabled=meta.focus_events_flag)
+    for priv_code in meta.private_modes:
+        if priv_code not in (47, 1047, 1049, 2026):
+            raw_m = DEC_PRIVATE_MASK | priv_code
+            with contextlib.suppress(ValueError):
+                term.modes.set_mode(Mode(raw_m), enabled=True)
+
+    active._cur_visible = meta.cursor_visible
+    active._cur_row = meta.clamped_cursor_row
+    active._cur_col = meta.clamped_cursor_col
+    active._pending_wrap = meta.pending_wrap
+
+    term._g_sets = ["B", profile.default_g1_charset, "B", "B"]
+    term._gl = 0
+    term._single_shift = None
+    term._style = DEFAULT_STYLE
+    term._hyperlink = None
+    term._protected = False
+    term._sync_pen_cache()
+    if meta.title:
+        term._title = meta.title
+    if meta.cwd:
+        term._cwd = meta.cwd
+    if term._prompt_zones or meta.title or meta.cwd:
+        term._aux_revision += 1
+    term._generation += 1
+    term._cached_snapshot = None
+    if meta.synchronized:
+        term.modes.set_mode(Mode.SYNCHRONIZED_OUTPUT, enabled=True)
+        term._sync_generation = 1
+        term._sync_hold_pending = True
+
+    unexposed = set(_BASE_UNEXPOSED_FIELDS)
+    if not exact_wraps:
+        unexposed.add("soft_wraps")
+    if meta.alternate_on and saved_primary_capture is None:
+        unexposed.add("saved_primary_screen")
+
+    exact_gen = (
+        meta.output_generation is not None
+        and post_meta is not None
+        and post_meta.output_generation == meta.output_generation
+    )
+    completeness = CaptureCompleteness(
+        exact_cells=True,
+        exact_wraps=exact_wraps,
+        exact_generation_bracket=exact_gen,
+        unexposed_fields=frozenset(unexposed),
+    )
+    return TmuxCaptureResult(
+        terminal=term,
+        snapshot=term.snapshot(),
+        completeness=completeness,
+        line_flags=line_flags,
+    )
+
+
+__all__ = [
+    "TMUX_METADATA_FORMAT",
+    "CaptureCompleteness",
+    "CaptureInput",
+    "TmuxCaptureResult",
+    "TmuxLineFlags",
+    "TmuxPaneMetadata",
+    "decode_tmux_capture",
+    "parse_flagged_line",
+    "unescape_tmux_control_output",
+]
diff --git a/tests/test_incremental_tmux_and_graphics.py b/tests/test_incremental_tmux_and_graphics.py
new file mode 100644
index 0000000..b00019b
--- /dev/null
+++ b/tests/test_incremental_tmux_and_graphics.py
@@ -0,0 +1,705 @@
+"""Regression and feature tests for incremental deltas, tmux capture, and graphics."""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import copy
+import pickle
+import shutil
+import struct
+import subprocess
+import time
+import traceback
+import zlib
+
+import pytest
+
+import libvt
+from libvt import _ucd
+from libvt.aio import AsyncTerminalStream
+from libvt.config import DEFAULT_PROFILE, TMUX_PROFILE, Profile
+from libvt.events import KittyGraphic
+from libvt.exc import TerminalTimeoutError
+from libvt.graphics import GraphicsProtocol, ZLayer
+from libvt.modes import Mode
+from libvt.parser import ParserState
+from libvt.screen import RowView
+from libvt.style import AnsiColor
+from libvt.terminal import ResyncReason
+from libvt.tmux import (
+    TMUX_METADATA_FORMAT,
+    TmuxLineFlags,
+    TmuxPaneMetadata,
+    decode_tmux_capture,
+    unescape_tmux_control_output,
+)
+
+
+class _SlottedTimeoutError(TerminalTimeoutError):
+    """Downstream subclass with ``__slots__`` and custom keyword-only ``__init__``."""
+
+    __slots__ = ("attempt",)
+
+    def __init__(
+        self,
+        message: str,
+        *,
+        attempt: int,
+        parser_state: ParserState = ParserState.GROUND,
+        screen_text: str = "",
+        recent_bytes: bytes | bytearray | memoryview = b"",
+    ) -> None:
+        super().__init__(
+            message,
+            parser_state=parser_state,
+            screen_text=screen_text,
+            recent_bytes=recent_bytes,
+            eof=False,
+        )
+        self.attempt = attempt
+
+
+class _DynamicTimeoutError(TerminalTimeoutError):
+    """Downstream subclass allowing arbitrary instance attributes."""
+
+    extra_context: str = ""
+
+
+async def test_timeout_error_notes_slots_subclasses_and_concise_str() -> None:
+    """``TerminalTimeoutError`` preserves ``__notes__``, slots, and 1-line ``str``."""
+    empty = TerminalTimeoutError()
+    assert empty.args == ()
+    assert str(empty) == ""
+    assert empty.errno is None
+
+    quiet = TerminalTimeoutError(
+        "quiet timeout",
+        screen_text="secret-viewport",
+        attach_note=False,
+    )
+    assert not hasattr(quiet, "__notes__")
+    for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+        quiet_rt = pickle.loads(pickle.dumps(quiet, protocol=proto))
+        assert not hasattr(quiet_rt, "__notes__")
+        assert quiet_rt.screen_text == "secret-viewport"
+
+    slotted = _SlottedTimeoutError(
+        "slotted timeout",
+        attempt=4,
+        parser_state=ParserState.CSI_PARAM,
+        screen_text="row0",
+        recent_bytes=b"\x1b[1;",
+    )
+    slotted.add_note("slot-note")
+    for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+        slotted_rt = pickle.loads(pickle.dumps(slotted, protocol=proto))
+        assert type(slotted_rt) is _SlottedTimeoutError
+        assert slotted_rt.attempt == 4
+        assert slotted_rt.errno is None
+        assert slotted_rt.__notes__ == slotted.__notes__
+    for cloned_slot in (copy.copy(slotted), copy.deepcopy(slotted)):
+        assert type(cloned_slot) is _SlottedTimeoutError
+        assert cloned_slot.attempt == 4
+        assert cloned_slot.__notes__ == slotted.__notes__
+
+    sub = _DynamicTimeoutError(
+        "timed out waiting for prompt",
+        parser_state=ParserState.OSC_STRING,
+        screen_text="$ stuck",
+        recent_bytes=memoryview(b"\x1b]0;unterminated"),
+        eof=False,
+    )
+    sub.add_note("attempt=3")
+    sub.extra_context = "pane-%1"
+
+    assert str(sub) == "timed out waiting for prompt"
+    assert "\n" not in str(sub)
+    assert isinstance(sub.recent_bytes, bytes)
+    assert any("OSC_STRING" in n for n in sub.__notes__)
+    assert "attempt=3" in sub.__notes__
+
+    shallow = copy.copy(sub)
+    shallow.add_note("shallow-only")
+    assert "shallow-only" not in sub.__notes__
+
+    for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+        restored = pickle.loads(pickle.dumps(sub, protocol=proto))
+        assert type(restored) is _DynamicTimeoutError
+        assert restored.errno is None
+        assert str(restored) == "timed out waiting for prompt"
+        assert restored.parser_state == ParserState.OSC_STRING
+        assert restored.screen_text == "$ stuck"
+        assert restored.recent_bytes == b"\x1b]0;unterminated"
+        assert restored.eof is False
+        assert restored.__notes__ == sub.__notes__
+        assert restored.extra_context == "pane-%1"
+
+    caught: list[TerminalTimeoutError] = []
+    group_msg = "batch"
+    other_msg = "other"
+    try:
+        raise ExceptionGroup(group_msg, [sub, ValueError(other_msg)])
+    except* TimeoutError as eg:
+        caught.extend(e for e in eg.exceptions if isinstance(e, TerminalTimeoutError))
+    except* ValueError:
+        pass
+    assert len(caught) == 1
+    assert caught[0].__notes__ == sub.__notes__
+
+    reader = asyncio.StreamReader()
+    stream = AsyncTerminalStream(reader, rows=2, cols=12)
+    reader.feed_data(b"hello\x1b]0;stuck")
+    with pytest.raises(TerminalTimeoutError) as exc_info:
+        await stream.wait_for("missing", timeout=0.02)
+    err = exc_info.value
+    assert "\n" not in str(err)
+    assert "Flight Recorder:" not in str(err)
+    assert "Flight Recorder:" in err.format_diagnostics()
+    assert any("Flight Recorder:" in n for n in err.__notes__)
+    assert "Flight Recorder:" in "".join(traceback.format_exception(err))
+
+    with pytest.raises(TerminalTimeoutError) as no_note_exc:
+        await stream.wait_for("missing", timeout=0.01, attach_note=False)
+    assert not hasattr(no_note_exc.value, "__notes__")
+
+
+def test_right_margin_widening_zwsp_and_safe_narrow_bmp_slicing() -> None:
+    """Right-margin ``VS16`` keeps SGR/margins, ``ZWSP`` breaks, ``?7l`` is fast."""
+    for chunk_mode in ("whole", "per_char", "per_byte"):
+        term = libvt.Terminal(rows=3, cols=4)
+        payload = "\x1b[31mabc1\x1b[34m\ufe0f\u20e3Z"
+        if chunk_mode == "whole":
+            term.feed_str(payload)
+        elif chunk_mode == "per_char":
+            for ch in payload:
+                term.feed_str(ch)
+        else:
+            raw = payload.encode("utf-8")
+            for idx in range(len(raw)):
+                term.feed(raw[idx : idx + 1])
+
+        assert term[0].text == "abc"
+        assert term[0].wrapped is True
+        assert term[1, 0].text == "1\ufe0f\u20e3"
+        assert term[1, 0].width == 2
+        assert term[1, 0].style.fg == AnsiColor.RED
+        assert term[1, 2].text == "Z"
+        assert term[1, 2].style.fg == AnsiColor.BLUE
+
+    # DECSTBM bottom < rows - 1 keeps wrapped=True after right-margin widening scroll.
+    bounded = libvt.Terminal(rows=4, cols=4)
+    bounded.feed_str("\x1b[1;2rL0\r\nabc1\ufe0f\u20e3Z")
+    assert bounded[0].text == "abc"
+    assert bounded[0].wrapped is True
+    assert bounded[1, 0].text == "1\ufe0f\u20e3"
+    assert bounded[1, 2].text == "Z"
+
+    # Mode.IRM shifts existing text on the destination row when widening wraps.
+    irm = libvt.Terminal(rows=3, cols=4)
+    irm.feed_str("\x1b[2;1HXY\x1b[1;1H\x1b[4habc1\ufe0f\u20e3")
+    assert irm[1, 0].text == "1\ufe0f\u20e3"
+    assert irm[1, 2].text == "X"
+    assert irm[1, 3].text == "Y"
+
+    # U+200B ZERO WIDTH SPACE is GCB=Control (GB4/GB5) and must break the cluster.
+    zwsp_term = libvt.Terminal(rows=2, cols=6)
+    zwsp_term.feed_str("1\u200b\ufe0fA")
+    assert zwsp_term[0, 0].text == "1"
+    assert zwsp_term[0, 0].width == 1
+    assert zwsp_term[0, 1].text == "A"
+
+    matched_cps = [
+        cp
+        for cp in range(0x10000)
+        if _ucd.SAFE_NARROW_BMP_RE.match(chr(cp)) is not None
+    ]
+    assert len(matched_cps) >= 18_000
+    for sample in ("┌", "─", "│", "█", "Ω", "д", "→", "⠿"):
+        assert _ucd.SAFE_NARROW_BMP_RE.match(sample) is not None
+    for unsafe in (
+        "\u0301",
+        "\ufe0f",
+        "\u200d",
+        "中",
+        "\u202e",
+        "\x00",
+        "\x7f",
+        "\x85",
+    ):
+        assert _ucd.SAFE_NARROW_BMP_RE.match(unsafe) is None
+
+    mixed = "┌── Ωμέγα 🚀 Кириллица ──┐#1\ufe0f\u20e3*2\ufe0f"
+    bulk = libvt.Terminal(rows=4, cols=16)
+    bulk.feed_str(mixed)
+    scalar = libvt.Terminal(rows=4, cols=16)
+    for ch in mixed:
+        scalar.feed_str(ch)
+    assert bulk.lines == scalar.lines
+    assert bulk.cursor == scalar.cursor
+
+    # ?7l (DECAWM disabled) collapses right-margin slice overwrites in O(cols) time.
+    no_wrap = libvt.Terminal(rows=2, cols=8)
+    t0 = time.monotonic()
+    no_wrap.feed_str("\x1b[?7l" + ("ABCDEFGH" * 12_500) + "!")
+    elapsed = time.monotonic() - t0
+    assert elapsed < 0.2
+    assert no_wrap[0].text == "ABCDEFG!"
+
+
+def test_tmux_profile_decstr_ed2_history_versions_and_linux_console() -> None:
+    """``Profile.tmux`` handles ``next-3.9``/``rc``, ``DECSTR``, and ``ED 2``."""
+    p_next = Profile.tmux("next-3.9")
+    assert p_next.sixel_erase_policy == "cell_mask"
+    p_rc = Profile.tmux("tmux 3.8-rc3")
+    assert p_rc.sixel_erase_policy == "whole_image"
+    p_prefixed = Profile.tmux("tmux 3.8a")
+    assert p_prefixed.sixel_erase_policy == "whole_image"
+
+    lt = libvt.Terminal(rows=2, cols=8, profile=Profile.linux_console())
+    lt.feed(b"\x0elqqk\x0f")
+    assert lt[0].text == "┌──┐"
+
+    tm = libvt.Terminal(rows=4, cols=10, scrollback=20, profile=TMUX_PROFILE)
+    tm.feed(b"\x1b[31m\x1b[?7l\x1b[!pA")
+    assert tm.modes.is_set(Mode.DECAWM) is False
+    assert tm[0, 0].style.fg == AnsiColor.RED
+
+    vt = libvt.Terminal(rows=4, cols=10, profile=DEFAULT_PROFILE)
+    vt.feed(b"\x1b[31m\x1b[?7l\x1b[!pA")
+    assert vt.modes.is_set(Mode.DECAWM) is True
+    assert vt[0, 0].style.fg is None
+
+    tm2 = libvt.Terminal(rows=4, cols=10, scrollback=20, profile=TMUX_PROFILE)
+    tm2.feed(b"ROW_ONE\r\nROW_TWO\x1b[4;5H\x1b[44m\x1b[2J")
+    assert [r.text for r in tm2.history] == ["ROW_ONE", "ROW_TWO"]
+    assert tm2.lines == ("", "", "", "")
+    assert tm2[0, 0].style.bg == AnsiColor.BLUE
+    assert (tm2.cursor.row, tm2.cursor.col) == (3, 4)
+
+    # ED 0 at (0, 0) scrolls primary content (including BCE-colored rows) into history.
+    tm2.feed(b"\x1b[0m\x1b[HHOME_ROW\x1b[H\x1b[J")
+    assert [r.text for r in tm2.history] == [
+        "ROW_ONE",
+        "ROW_TWO",
+        "HOME_ROW",
+        "",
+        "",
+        "",
+    ]
+    assert tm2.history[3][0].style.bg == AnsiColor.BLUE
+
+    tm2.feed(b"\x1b[?1049hALT_LINE\x1b[2J")
+    assert len(tm2.history) == 6
+    assert tm2.lines == ("", "", "", "")
+
+
+def test_tmux_capture_decoder_synthetic_and_live() -> None:
+    """``decode_tmux_capture`` decodes ``list[str]``, ``-J``, and live ``tmux``."""
+    assert unescape_tmux_control_output(r"\033[31mhi\134there\015\012") == (
+        b"\x1b[31mhi\\there\r\n"
+    )
+    raw_utf8_line = b"caf\xc3\xa9\\012".decode("utf-8", errors="surrogateescape")
+    assert unescape_tmux_control_output(raw_utf8_line) == b"caf\xc3\xa9\n"
+
+    # Format string uses real tmux format names and parses UINT_MAX saved coords.
+    assert "#{bracket_paste_flag}" in TMUX_METADATA_FORMAT
+    assert "#{mouse_all_flag}" in TMUX_METADATA_FORMAT
+    assert "#{pane_private_modes}" in TMUX_METADATA_FORMAT
+    raw_fmt = (
+        "8\t3\t0\t2\t1\t0\t4294967295\t4294967295\t0\t2\t"
+        "0\t0\t1\t0\t1\t0\t0\t1\t1\t1004,2004\t"
+        "0,4\t0\t2000\t1\t7\t/tmp\ttitle"
+    )
+    parsed_meta = TmuxPaneMetadata.from_format_line(raw_fmt)
+    assert parsed_meta.alternate_saved_x is None
+    assert parsed_meta.alternate_saved_y is None
+    assert parsed_meta.bracketed_paste_flag is True
+    assert parsed_meta.mouse_any_flag is True
+    assert parsed_meta.focus_events_flag is True
+    assert parsed_meta.synchronized is True
+
+    # Sequence[str] input (libtmux capture_pane() shape) + ?2026 synchronized hold.
+    sync_term = libvt.Terminal.from_tmux_capture(
+        ["HOLD_LIN", "", ""],
+        metadata=raw_fmt,
+    )
+    assert sync_term.synchronized is True
+    sync_term.feed(b"\x1b[1;1HDIRTY")
+    assert sync_term.committed[0].text == "HOLD_LIN"
+    sync_term.feed(b"\x1b[?2026l")
+    assert sync_term.committed[0].text == "DIRTYLIN"
+
+    # Unflagged capture + joined_capture infers 3-row soft wrap + CJK SPACER_HEAD wrap,
+    # and flagged P/O lines keep PromptZone rows accurate when scrollback < hist_count.
+    unflagged_lines = ["H0", "H1", "ABCD", "EFGH", "IJ", "abc ", "中文"]
+    joined_lines = ["H0", "H1", "ABCDEFGHIJ", "abc中文"]
+    cjk_meta = TmuxPaneMetadata(cols=4, rows=5, history_size=2)
+    cjk_term = libvt.Terminal.from_tmux_capture(
+        unflagged_lines,
+        metadata=cjk_meta,
+        scrollback=1,
+        joined_capture=joined_lines,
+    )
+    assert [r.text for r in cjk_term.history] == ["H1"]
+    assert cjk_term[0].wrapped is True
+    assert cjk_term[1].wrapped is True
+    assert cjk_term[2].wrapped is False
+    assert cjk_term[3].wrapped is True
+    cjk_term.resize(rows=5, cols=10)
+    assert cjk_term.lines[:3] == ("H1", "ABCDEFGHIJ", "abc中文")
+
+    pz_snap = libvt.Snapshot.from_tmux_capture(
+        ["P H0", "P H1", "- V0", "O V1", "- V2", "- V3", "- V4"],
+        metadata=cjk_meta,
+        scrollback=1,
+        flagged=True,
+    )
+    assert [r.text for r in pz_snap.history] == ["H1"]
+    assert [(z.row, z.kind.value) for z in pz_snap.prompt_zones] == [
+        (-1, "A"),
+        (1, "C"),
+    ]
+
+    # Synthetic flagged (-F -e -p -N) capture with scrollback, bare SO/SI ACS,
+    # SGR carry across rows, custom tabstops, soft wrap, and pending_wrap.
+    meta = TmuxPaneMetadata(
+        cols=8,
+        rows=3,
+        cursor_x=8,
+        cursor_y=2,
+        wrap_flag=True,
+        pane_tabs=(4, 8),
+        output_generation=42,
+    )
+    captured = (
+        "- HIST_0  \n"
+        "X \x1b[31m\x0elqqk\x0f    \n"
+        "WX ABCDEFGH\n"
+        "X \x1b[44m\t\x1b[49m1234\n"
+    )
+    res = decode_tmux_capture(
+        captured,
+        metadata=meta,
+        post_metadata=meta,
+        flagged=True,
+    )
+    assert res.completeness.exact_wraps is True
+    assert res.completeness.exact_generation_bracket is True
+    assert TmuxLineFlags.WRAPPED in res.line_flags[2]
+    assert [r.text for r in res.snapshot.history] == ["HIST_0"]
+    assert res.terminal[0].text == "┌──┐"
+    assert res.terminal[0, 0].style.fg == AnsiColor.RED
+    assert res.terminal[1].text == "ABCDEFGH"
+    assert res.terminal[1].wrapped is True
+    assert res.terminal[1, 0].style.fg == AnsiColor.RED
+    assert res.terminal[2].text == "    1234"
+    assert res.terminal[2, 0].style.bg == AnsiColor.BLUE
+    assert res.terminal[2, 3].style.bg == AnsiColor.BLUE
+    assert res.terminal[2, 4].style.bg is None
+    assert res.terminal.cursor.row == 2
+    assert res.terminal.cursor.col == 7
+    assert res.terminal.cursor.pending_wrap is True
+    res.terminal.feed(b"\x1b[0m!\x0el\x0f")
+    assert res.terminal[2].text == "!l"
+
+    if shutil.which("tmux") is not None:
+        sock = f"libvt-test-{zlib.crc32(b'incremental-tmux')}"
+        try:
+            subprocess.run(
+                [
+                    "tmux",
+                    "-L",
+                    sock,
+                    "-f",
+                    "/dev/null",
+                    "new-session",
+                    "-d",
+                    "-x",
+                    "10",
+                    "-y",
+                    "3",
+                    "sh",
+                    "-c",
+                    (
+                        "printf '\\033[?2004h\\033(0lqqk\\033(B\\r\\n"
+                        "1234567890WRAP\\r\\n\\t\\033[42mX\\033[0m'; sleep 30"
+                    ),
+                ],
+                check=True,
+            )
+            for _ in range(100):
+                chk = subprocess.run(
+                    ["tmux", "-L", sock, "capture-pane", "-p"],
+                    check=True,
+                    capture_output=True,
+                    text=True,
+                )
+                if "X" in chk.stdout:
+                    break
+                time.sleep(0.02)
+            else:
+                pytest.fail("timed out waiting for tmux pane output")
+            meta_raw = subprocess.run(
+                [
+                    "tmux",
+                    "-L",
+                    sock,
+                    "display-message",
+                    "-p",
+                    TMUX_METADATA_FORMAT,
+                ],
+                check=True,
+                capture_output=True,
+                text=True,
+            ).stdout.rstrip("\n")
+            cap_raw = subprocess.run(
+                [
+                    "tmux",
+                    "-L",
+                    sock,
+                    "capture-pane",
+                    "-S",
+                    "-",
+                    "-E",
+                    "-",
+                    "-F",
+                    "-e",
+                    "-p",
+                    "-N",
+                ],
+                check=True,
+                capture_output=True,
+                text=True,
+            ).stdout
+            live_res = decode_tmux_capture(cap_raw, metadata=meta_raw, flagged=True)
+            assert live_res.terminal.modes.is_set(Mode.BRACKETED_PASTE) is True
+            assert [r.text for r in live_res.snapshot.history] == ["┌──┐"]
+            assert live_res.terminal[0].text == "1234567890"
+            assert live_res.terminal[0].wrapped is True
+            assert live_res.terminal[1].text == "WRAP"
+            assert live_res.terminal[2].text == "        X"
+            assert live_res.terminal[2, 0].style.bg is None
+            assert live_res.terminal[2, 8].style.bg == AnsiColor.GREEN
+        finally:
+            subprocess.run(
+                ["tmux", "-L", sock, "kill-server"],
+                check=False,
+                capture_output=True,
+            )
+
+
+def test_changes_since_watermarks_and_replica_equivalence() -> None:
+    """``changes_since`` and ``apply_lines``/``apply_rows`` stay exact."""
+    term = libvt.Terminal(
+        rows=4,
+        cols=6,
+        scrollback=6,
+        profile=TMUX_PROFILE,
+    )
+    rep_lines_hist: list[str] = []
+    rep_lines_view: list[str] = []
+    rep_rows_hist: list[RowView] = []
+    rep_rows_view: list[RowView] = []
+
+    def _step_and_assert(tok: libvt.SyncToken | None) -> libvt.ScreenDelta:
+        delta = term.changes_since(tok)
+        delta.apply_lines(rep_lines_hist, rep_lines_view)
+        delta.apply_rows(rep_rows_hist, rep_rows_view)
+        snap = delta.snapshot
+        assert rep_lines_hist == [r.text for r in snap.history]
+        assert rep_lines_view == list(snap.lines)
+        assert [r.text for r in rep_rows_hist] == [r.text for r in snap.history]
+        assert [(r.text, r.wrapped) for r in rep_rows_view] == [
+            (snap[i].text, snap[i].wrapped) for i in range(snap.rows)
+        ]
+        return delta
+
+    d = _step_and_assert(None)
+    assert d.resync_reason == ResyncReason.INITIAL
+
+    # Wide SPACER_HEAD wrap + cross-row heal + DCH at col 0 clearing preceding wrapped.
+    term.feed_str("abcde中\r\nLINE_2")
+    d = _step_and_assert(d.token)
+    assert rep_rows_view[0].wrapped is True
+    term.feed_str("\x1b[2;1H\x1b[P")
+    d = _step_and_assert(d.token)
+    assert rep_rows_view[0].wrapped is False
+
+    # Full-screen scroll + large multi-row scroll exceeding viewport height (> 4 rows).
+    term.feed_str("\x1b[4;1H\r\nS1\r\nS2\r\nS3\r\nS4\r\nS5")
+    d = _step_and_assert(d.token)
+    assert d.resync_reason == ResyncReason.NONE
+    assert d.viewport_scroll_up == 5
+
+    # Bounded DECSTBM top=0, bottom=2 (rows=4) pushes to history while pinning row 3.
+    term.feed_str("\x1b[1;3r\x1b[3;1H\nTOP_SC\x1b[r")
+    d = _step_and_assert(d.token)
+    assert d.resync_reason == ResyncReason.NONE
+
+    # ED 3 clears scrollback and subsequent scroll stays incremental.
+    term.feed(b"\x1b[3J\x1b[4;1H\r\nAFTER_CLEAR")
+    d = _step_and_assert(d.token)
+    assert d.history_cleared is True
+
+    # Auxiliary metadata mutations (OSC 7501, remote OSC 7 URI, ESC k) flag changes.
+    term.feed(b"\x1b]7501;state=working:id=build\x07")
+    d = _step_and_assert(d.token)
+    assert d.metadata_changed is True
+
+    term.feed(b"\x1b]7;file://remote-box.example/srv/app\x07")
+    d = _step_and_assert(d.token)
+    assert d.metadata_changed is True
+    assert d.snapshot.cwd == ""
+    assert d.snapshot.cwd_uri == "file://remote-box.example/srv/app"
+
+    term.feed(b"\x1bkmy-window\x1b\\")
+    d = _step_and_assert(d.token)
+    assert d.metadata_changed is True
+
+    # ?2026 synchronized output holds committed view while working view advances.
+    c_tok = term.sync_token(view="committed")
+    term.feed(b"\x1b[?2026h\x1b[1;1HTORN")
+    assert term.changes_since(c_tok, view="committed").has_changes is False
+    assert 0 in term.changes_since(c_tok, view="working").dirty_rows
+    term.feed(b"\x1b[?2026l")
+    d = _step_and_assert(c_tok)
+    assert d.has_changes is True
+
+    # ?1049h / ?1049l bumps epoch; scrolling > scrollback triggers HISTORY_EVICTED.
+    stale_pre_alt = d.token
+    term.feed(b"\x1b[?1049hALT\x1b[?1049l")
+    d = _step_and_assert(stale_pre_alt)
+    assert d.resync_reason == ResyncReason.EPOCH_CHANGED
+
+    stale_same_epoch = d.token
+    f_tok = d.token
+    for idx in range(10):
+        term.feed(f"\r\nEV{idx}".encode("ascii"))
+        f_tok = term.changes_since(f_tok).token
+    assert term.changes_since(stale_same_epoch).resync_reason == (
+        ResyncReason.HISTORY_EVICTED
+    )
+
+
+def test_sixel_and_kitty_graphics_and_snapshot_immutability() -> None:
+    """``SIXEL``/Kitty handle scroll-before-place, limits, and frozen ``Snapshot``."""
+    ihdr_body = struct.pack(">IIBBBBB", 16, 32, 8, 6, 0, 0, 0)
+    ihdr_crc = struct.pack(">I", zlib.crc32(b"IHDR" + ihdr_body) & 0xFFFFFFFF)
+    png_bytes = (
+        b"\x89PNG\r\n\x1a\n" + struct.pack(">I", 13) + b"IHDR" + ihdr_body + ihdr_crc
+    )
+    z_payload = base64.b64encode(zlib.compress(png_bytes))
+    part1, part2 = z_payload[:12], z_payload[12:]
+
+    term = libvt.Terminal(rows=6, cols=10, scrollback=10)
+    term.feed(b"\x1b[2;3H")
+    term.feed(b"\x1b_Ga=T,f=100,o=z,i=7,p=1,z=-5,m=1;" + part1 + b"\x1b\\")
+    assert len(term.placements) == 0
+    term.feed(b"\x1b_Gm=0;" + part2 + b"\x1b\\")
+    assert b"\x1b_Gi=7,p=1;OK\x1b\\" in term.drain_replies()
+
+    assert len(term.placements) == 1
+    kp = term.placements[0]
+    assert kp.protocol == GraphicsProtocol.KITTY
+    assert (kp.row, kp.col, kp.rows, kp.cols) == (1, 2, 2, 2)
+    assert kp.layer == ZLayer.BELOW_TEXT
+    assert (term.cursor.row, term.cursor.col) == (2, 4)
+
+    # Kitty U=0 overlay survives text overwrite; d=y with missing y=0 is a safe no-op.
+    term.feed(b"\x1b[2;3HOVER\x1b[K\x1b_Ga=d,d=y\x1b\\")
+    assert len(term.placements) == 1
+
+    # Retransmitting i=7 replaces stale placements of image 7.
+    raw_1cell = base64.b64encode(b"\xff" * (8 * 16 * 3))
+    term.feed(b"\x1b[1;1H\x1b_Ga=t,f=24,s=8,v=16,i=7;" + raw_1cell + b"\x1b\\")
+    assert len(term.placements) == 0
+    assert b"\x1b_Gi=7;OK\x1b\\" in term.drain_replies()
+
+    # Unnumbered Kitty a=T upload places image silently (zero PTY reply bytes).
+    term.feed(b"\x1b[1;1H\x1b_Ga=T,f=24,s=8,v=16;" + raw_1cell + b"\x1b\\")
+    assert term.drain_replies() == b""
+    assert len(term.placements) == 1
+
+    # Query a=q without i= stays silent; i + I together and truncated payloads fail.
+    term.feed(b"\x1b_Ga=q,f=24,s=1,v=1;" + base64.b64encode(b"abc") + b"\x1b\\")
+    assert term.drain_replies() == b""
+    term.feed(b"\x1b_Ga=t,i=2,I=3,f=24,s=1,v=1;" + base64.b64encode(b"abc") + b"\x1b\\")
+    assert b"EINVAL" in term.drain_replies()
+    term.feed(b"\x1b_Ga=t,i=8,f=24,s=8,v=16;" + base64.b64encode(b"short") + b"\x1b\\")
+    assert b"EINVAL" in term.drain_replies()
+    assert 8 not in term.images
+    comp_trunc = base64.b64encode(zlib.compress(png_bytes)[:-4])
+    term.feed(b"\x1b_Ga=t,i=9,f=100,o=z;" + comp_trunc + b"\x1b\\")
+    assert b"EINVAL" in term.drain_replies()
+    assert 9 not in term.images
+
+    # Reject local filesystem t=f safely in sans-I/O emulator.
+    term.feed(b"\x1b_Ga=T,t=f,i=99;" + base64.b64encode(b"/etc/passwd") + b"\x1b\\")
+    assert 99 not in term.images
+    assert b"EINVAL" in term.drain_replies()
+
+    # Virtual parent + relative child placement + cascade delete.
+    term.feed(b"\x1b_Ga=T,U=1,i=20,p=1,c=2,r=2,f=24,s=8,v=16;" + raw_1cell + b"\x1b\\")
+    # Virtual parent cannot anchor non-virtual relative child; real parent can:
+    term.feed(b"\x1b_Ga=p,i=20,p=2,P=20,Q=1\x1b\\")
+    assert b"ENOPARENT" in term.drain_replies()
+    term.drain_replies()
+    term.feed(b"\x1b[2;2H\x1b_Ga=p,i=20,p=3,c=2,r=2\x1b\\")
+    term.feed(b"\x1b_Ga=p,i=20,p=4,P=20,Q=3,H=2,V=1\x1b\\")
+    term.drain_replies()
+    child_pls = [p for p in term.placements if p.image_id == 20 and p.placement_id == 4]
+    assert len(child_pls) == 1
+    assert (child_pls[0].row, child_pls[0].col) == (2, 3)
+    term.feed(b"\x1b_Ga=d,d=i,i=20,p=3\x1b\\")
+    assert not any(
+        p.image_id == 20 and p.placement_id in (3, 4) for p in term.placements
+    )
+
+    # Bottom-of-alt-screen Kitty & SIXEL scroll-before-place keep full 2-row graphic.
+    alt_t = libvt.Terminal(rows=4, cols=8)
+    raw_2row = base64.b64encode(b"\xaa" * (16 * 32 * 3))
+    alt_t.feed(b"\x1b[?1049h\x1b[4;2H\x1b_Ga=T,f=24,s=16,v=32;" + raw_2row + b"\x1b\\")
+    assert len(alt_t.placements) == 1
+    assert (alt_t.placements[0].row, alt_t.placements[0].rows) == (2, 2)
+
+    sixel_seq = b'\x1bP0;1;0q"1;1;16;32#0!16~-#0!16~-#0!16~-#0!16~-#0!16~\x1b\\'
+    vt_sixel = libvt.Terminal(rows=6, cols=10, profile=Profile.tmux("next-3.9"))
+    vt_sixel.feed(sixel_seq)
+    assert len(vt_sixel.placements) == 1
+    sp = vt_sixel.placements[0]
+    assert sp.protocol == GraphicsProtocol.SIXEL
+    assert (sp.row, sp.col, sp.rows, sp.cols) == (0, 0, 2, 2)
+    assert (vt_sixel.cursor.row, vt_sixel.cursor.col) == (2, 0)
+    vt_sixel.feed(b"\x1b[1;1HX")
+    assert vt_sixel.placements[0].occupies_cell(0, 0) is False
+    assert vt_sixel.placements[0].occupies_cell(0, 1) is True
+
+    tm38_sixel = libvt.Terminal(rows=6, cols=10, profile=Profile.tmux("3.8a"))
+    tm38_sixel.feed(sixel_seq)
+    tm38_sixel.feed(b"\x1b[1;1HX")
+    assert len(tm38_sixel.placements) == 0
+
+    # 10,000px SIXEL stream under DECLRMM finishes in O(rows) without per-row DoS loop.
+    dos_t = libvt.Terminal(rows=24, cols=80, record_events=True)
+    t0 = time.monotonic()
+    for _ in range(20):
+        dos_t.feed(b'\x1b[?69h\x1b[10;20s\x1b[1;1H\x1bPq"1;1;10;10000#0~\x1b\\')
+    assert time.monotonic() - t0 < 0.2
+
+    # Snapshot and KittyCommand.control enforce immutability at runtime.
+    ev_t = libvt.Terminal(rows=4, cols=8, record_events=True)
+    ev_t.feed(b"\x1b_Ga=T,f=24,s=8,v=16,i=5;" + raw_1cell + b"\x1b\\")
+    evs = [e for e in ev_t.drain_events() if isinstance(e, KittyGraphic)]
+    assert len(evs) == 1
+    with pytest.raises(TypeError):
+        evs[0].command.control["a"] = "d"  # type: ignore[index]
+
+    snap = ev_t.snapshot()
+    assert len(snap.to_dict()["placements"]) == 1
+    with pytest.raises(AttributeError):
+        snap.title = "mutated"  # type: ignore[misc]
+    with pytest.raises(TypeError):
+        snap.program_statuses["x"] = None  # type: ignore[index]
+    with pytest.raises(TypeError):
+        snap.images[999] = None  # type: ignore[index]

From 19979970e837a60f961631f65e49cb4938bcbd45 Mon Sep 17 00:00:00 2001
From: Tony Narlock 
Date: Sun, 22 Nov 2026 14:32:00 -0600
Subject: [PATCH 23/29] tests(refactor[suite]): Split tests by module

why: Review-round grab-bag files obscured module ownership, and full
1.1M-codepoint loops, per-step grid scans, and extra subprocess spawns
slowed local test runs.

what:
- Replace review-round and multi-module grab-bag test files with 1:1
  per-module test files (test_aio, test_codec, test_exc, test_graphics,
  test_input, test_parser, test_screen, test_status, test_terminal,
  test_testing, test_tmux, test_ucd)
- Migrate multi-case loops to typed NamedTuple @pytest.mark.parametrize
  tables with explicit test_id identifiers and strict ty annotations
- Verify Unicode 17 parity across distinct stage-2 blocks and stage-1
  boundaries, scan SAFE_NARROW_BMP_RE in C, test CLI stdin in-process,
  and consolidate POSIX PTY assertions into one child session
---
 AGENTS.md                                     |   3 +-
 tests/test_aio.py                             | 136 ++++
 tests/test_aio_and_pytest.py                  | 216 ------
 tests/test_benchmark.py                       |  12 +-
 .../{test_codec_and_cli.py => test_codec.py}  |  37 +-
 tests/test_exc.py                             | 123 +++
 tests/test_graphics.py                        | 128 ++++
 tests/test_incremental_tmux_and_graphics.py   | 705 ------------------
 tests/test_input.py                           |  67 ++
 tests/test_parser.py                          | 135 ++--
 tests/test_pr2_review_fixes.py                | 404 ----------
 tests/test_protocols_and_input.py             | 252 -------
 tests/test_screen.py                          | 294 ++++++++
 tests/test_status.py                          | 155 ++++
 tests/test_terminal.py                        | 459 +++++++++---
 tests/test_testing.py                         |  78 ++
 tests/test_tmux.py                            | 222 ++++++
 tests/test_ucd.py                             | 180 +++++
 tests/test_ucd_and_grid.py                    | 354 ---------
 19 files changed, 1811 insertions(+), 2149 deletions(-)
 create mode 100644 tests/test_aio.py
 delete mode 100644 tests/test_aio_and_pytest.py
 rename tests/{test_codec_and_cli.py => test_codec.py} (55%)
 create mode 100644 tests/test_exc.py
 create mode 100644 tests/test_graphics.py
 delete mode 100644 tests/test_incremental_tmux_and_graphics.py
 create mode 100644 tests/test_input.py
 delete mode 100644 tests/test_pr2_review_fixes.py
 delete mode 100644 tests/test_protocols_and_input.py
 create mode 100644 tests/test_screen.py
 create mode 100644 tests/test_status.py
 create mode 100644 tests/test_testing.py
 create mode 100644 tests/test_tmux.py
 create mode 100644 tests/test_ucd.py
 delete mode 100644 tests/test_ucd_and_grid.py

diff --git a/AGENTS.md b/AGENTS.md
index f7f60bf..d006f94 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -19,9 +19,10 @@ what was asked for.
 | `src/libvt/parser.py`, `modes.py`, `style.py`, `config.py` | VT500 byte parser, CSI subparameters, modes, SGR styles, and `Profile` / `Policy` / `Limits` |
 | `src/libvt/_ucd.py`, `_grid.py`, `screen.py`, `terminal.py` | Unicode 17 width/clustering tables, packed viewport & RLE scrollback rows, `Screen` / `ScreenSet`, `Terminal`, `Snapshot`, and `Formatter` |
 | `src/libvt/status.py`, `events.py`, `input.py`, `codec.py` | Rex `OSC 7501` program status store, closed `Event` union, mode-aware input encoders, and cold-path VT sequence explainer |
+| `src/libvt/graphics.py`, `tmux.py` | Zero-dependency `SIXEL` / Kitty `APC G` placement tracker and `tmux capture-pane` / `-CC` decoders |
 | `src/libvt/aio.py`, `__main__.py` | `AsyncTerminalStream`, POSIX `open_pty()`, and `python -m libvt` CLI (`explain`, `render`, `strip`) |
 | `src/libvt/testing.py`, `pytest_plugin.py`, `exc.py` | Boxed `assert_screen`, `FlightRecorder` diagnostics, `vt_*` pytest fixtures, and exceptions |
-| `tests/` | Unit, property fuzz, PTY, CLI, and fixture tests |
+| `tests/` | Functional, property-fuzz, PTY, CLI, and fixture tests organized by module under test |
 | `docs/` | Sphinx/MyST site: `topics/` (concepts), `api/` (autodoc), `project/` (contributing, releasing, ADRs `0001`–`0010`) |
 | `scripts/` | Unicode table generator (`generate_ucd.py`) and VT throughput benchmarks (`bench_vt.py`, `benchmark.py`) |
 | `README.md` | Doctested quickstart — every `>>> ` block is a real test |
diff --git a/tests/test_aio.py b/tests/test_aio.py
new file mode 100644
index 0000000..61e136c
--- /dev/null
+++ b/tests/test_aio.py
@@ -0,0 +1,136 @@
+"""Tests for ``libvt.aio`` async terminal streams and POSIX PTY sessions."""
+
+from __future__ import annotations
+
+import asyncio
+import socket
+import sys
+
+import pytest
+
+import libvt
+from libvt.aio import AsyncTerminalStream, open_pty
+from libvt.exc import TerminalTimeoutError
+from libvt.parser import ParserState
+
+
+class _MemoryWriter:
+    """In-memory writer stub capturing outbound DSR/DA reply bytes."""
+
+    def __init__(self) -> None:
+        self.buffer = bytearray()
+        self.closed = False
+
+    def write(self, data: bytes, /) -> None:
+        self.buffer.extend(data)
+
+    async def drain(self) -> None:
+        await asyncio.sleep(0)
+
+    def close(self) -> None:
+        self.closed = True
+
+    async def wait_closed(self) -> None:
+        await asyncio.sleep(0)
+
+
+async def test_async_terminal_stream_sync_coalescing_replies_and_timeout() -> None:
+    """``AsyncTerminalStream`` coalesces ``?2026``, flushes DSR, and formats errors."""
+    reader = asyncio.StreamReader()
+    writer = _MemoryWriter()
+    stream = AsyncTerminalStream(
+        reader,
+        writer,
+        rows=4,
+        cols=20,
+        sync_timeout=0.01,
+    )
+
+    reader.feed_data(b"base\x1b[?2026h\x1b[Hwedged\x1b[6n")
+    snap = await stream.wait_for("wedged", timeout=0.2)
+    assert snap[0].text == "wedged"
+    assert bytes(writer.buffer) == b"\x1b[1;7R"
+
+    async with AsyncTerminalStream(
+        asyncio.StreamReader(),
+        rows=2,
+        cols=14,
+        sync_timeout=0.01,
+    ) as bg_stream:
+        bg_stream.reader.feed_data(b"\x1b[?2026h\x1b[Hatomic-ok\x1b[?2026l")
+        snap2 = await bg_stream.wait_for("atomic-ok", timeout=0.2)
+        assert snap2[0].text == "atomic-ok"
+
+        bg_stream.reader.feed_data(b"\x1b]0;stuck")
+        with pytest.raises(TerminalTimeoutError) as exc_info:
+            await bg_stream.wait_for("missing", timeout=0.005)
+        err = exc_info.value
+        assert err.parser_state == ParserState.OSC_STRING
+        assert b"\x1b]0;stuck" in err.recent_bytes
+        assert "\n" not in str(err)
+        assert any("Flight Recorder:" in n for n in err.__notes__)
+
+        with pytest.raises(TerminalTimeoutError) as quiet_exc:
+            await bg_stream.wait_for("missing", timeout=0.005, attach_note=False)
+        assert not hasattr(quiet_exc.value, "__notes__")
+
+
+@pytest.mark.skipif(sys.platform == "win32", reason="POSIX pty required")
+async def test_open_pty_controlling_tty_signals_sigpipe_and_reap() -> None:
+    """``open_pty`` configures ``TIOCSCTTY``, signals, and process-group cleanup."""
+    with pytest.raises(FileNotFoundError):
+        async with open_pty(("definitely-missing-libvt-command-xyz",)):
+            pass
+
+    host = socket.gethostname()
+    child_code = (
+        "import os, signal, sys, time\n"
+        "tty_fd = os.open('/dev/tty', os.O_RDWR)\n"
+        "os.close(tty_fd)\n"
+        "fg_ok = (os.tcgetpgrp(0) == os.getpid())\n"
+        # Verify preexec restored default SIGPIPE disposition before Python overrides it
+        # in child exec targets by inspecting inherited mask/bg process group behavior.
+        "bg_pid = os.fork()\n"
+        "if bg_pid == 0:\n"
+        "    time.sleep(30)\n"
+        "    os._exit(0)\n"
+        "winch = False\n"
+        "def _on_winch(s, f):\n"
+        "    global winch\n"
+        "    winch = True\n"
+        "signal.signal(signal.SIGWINCH, _on_winch)\n"
+        f"sys.stdout.write('\\x1b]7;file://{host}/var/tmp\\x07')\n"
+        "sys.stdout.write('\\x1b]7501;state=working:id=job\\x1b\\\\')\n"
+        "sys.stdout.write(f'CTTY={fg_ok} BG={bg_pid} \\x1b[6n')\n"
+        "sys.stdout.flush()\n"
+        "reply = b''\n"
+        "while not reply.endswith(b'R'):\n"
+        "    ch = sys.stdin.buffer.read(1)\n"
+        "    if not ch: break\n"
+        "    reply += ch\n"
+        "print('DSR=' + repr(reply.decode('ascii', 'replace')), flush=True)\n"
+        "while not winch:\n"
+        "    signal.pause()\n"
+        "try:\n"
+        "    print('WINCH=1', flush=True)\n"
+        "    while True:\n"
+        "        signal.pause()\n"
+        "except KeyboardInterrupt:\n"
+        "    print('SIGINT=1', flush=True)\n"
+    )
+    async with open_pty(
+        (sys.executable, "-u", "-c", child_code),
+        rows=8,
+        cols=60,
+        tty_mode="cbreak",
+        policy=libvt.Policy(allow_passthrough=True),
+    ) as pty_sess:
+        await pty_sess.wait_for("DSR='\\x1b[1;", timeout=3.0)
+        assert "CTTY=True" in pty_sess.terminal.text
+        assert pty_sess.terminal.cwd == "/var/tmp"
+        assert "job" in pty_sess.terminal.program_statuses
+        pty_sess.resize(rows=10, cols=70)
+        await pty_sess.wait_for("WINCH=1", timeout=3.0)
+        pty_sess.send(b"\x03")
+        await pty_sess.wait_for("SIGINT=1", timeout=3.0)
+    assert pty_sess.terminal.program_statuses == {}
diff --git a/tests/test_aio_and_pytest.py b/tests/test_aio_and_pytest.py
deleted file mode 100644
index 583b9b3..0000000
--- a/tests/test_aio_and_pytest.py
+++ /dev/null
@@ -1,216 +0,0 @@
-"""Async stream, POSIX PTY subprocess, pytest fixture, and boxed assertion tests."""
-
-from __future__ import annotations
-
-import asyncio
-import pathlib
-import shutil
-import socket
-import sys
-
-import pytest
-
-import libvt
-from libvt.aio import AsyncTerminalStream, open_pty
-from libvt.pytest_plugin import PtyFactory, TerminalFactory
-from libvt.terminal import FlightRecorder, Terminal
-from libvt.testing import assert_screen, assert_screen_box
-
-
-class _MemoryWriter:
-    """Minimal writer stub capturing reply bytes flushed by ``AsyncTerminalStream``."""
-
-    def __init__(self) -> None:
-        self.buffer = bytearray()
-        self.closed = False
-
-    def write(self, data: bytes, /) -> None:
-        self.buffer.extend(data)
-
-    async def drain(self) -> None:
-        await asyncio.sleep(0)
-
-    def close(self) -> None:
-        self.closed = True
-
-    async def wait_closed(self) -> None:
-        await asyncio.sleep(0)
-
-
-async def test_async_terminal_stream_sync_coalescing_timeout_and_replies() -> None:
-    """``AsyncTerminalStream`` coalesces ``?2026``, expires wedges, and writes DSR."""
-    reader = asyncio.StreamReader()
-    writer = _MemoryWriter()
-    stream = AsyncTerminalStream(
-        reader,
-        writer,
-        rows=4,
-        cols=20,
-        sync_timeout=0.05,
-    )
-
-    reader.feed_data(b"base\x1b[?2026h\x1b[Hwedged\x1b[6n")
-    snap = await stream.wait_for("wedged", timeout=0.5)
-    assert snap[0].text == "wedged"
-    assert bytes(writer.buffer) == b"\x1b[1;7R"
-
-    async with AsyncTerminalStream(
-        asyncio.StreamReader(),
-        rows=4,
-        cols=20,
-        sync_timeout=0.05,
-    ) as bg_stream:
-        bg_stream.reader.feed_data(b"\x1b[?2026h\x1b[Hatomic-ok\x1b[?2026l")
-        snap2 = await bg_stream.wait_for("atomic-ok", timeout=0.5)
-        assert snap2[0].text == "atomic-ok"
-
-
-@pytest.mark.skipif(sys.platform == "win32", reason="POSIX pty required")
-async def test_open_pty_controlling_tty_signals_tty_mode_and_errors(
-    vt_pty: PtyFactory,
-) -> None:
-    """``open_pty`` sets ``TIOCSCTTY``, ``SIGWINCH``/``SIGINT``, and ``SIGPIPE``."""
-    host = socket.gethostname()
-    child_code = (
-        "import os, signal, sys\n"
-        "tty_fd = os.open('/dev/tty', os.O_RDWR)\n"
-        "os.close(tty_fd)\n"
-        "fg_ok = (os.tcgetpgrp(0) == os.getpid())\n"
-        "winch = False\n"
-        "def _on_winch(s, f):\n"
-        "    global winch\n"
-        "    winch = True\n"
-        "signal.signal(signal.SIGWINCH, _on_winch)\n"
-        f"sys.stdout.write('\\x1b]7;file://{host}/var/tmp\\x07')\n"
-        "sys.stdout.write('\\x1b]7501;state=working:id=job\\x1b\\\\')\n"
-        "sys.stdout.write(f'CTTY={fg_ok} \\x1b[6n')\n"
-        "sys.stdout.flush()\n"
-        "reply = b''\n"
-        "while not reply.endswith(b'R'):\n"
-        "    ch = sys.stdin.buffer.read(1)\n"
-        "    if not ch: break\n"
-        "    reply += ch\n"
-        "print('DSR=' + repr(reply.decode('ascii', 'replace')), flush=True)\n"
-        "while not winch:\n"
-        "    signal.pause()\n"
-        "try:\n"
-        "    print('WINCH=1', flush=True)\n"
-        "    while True:\n"
-        "        signal.pause()\n"
-        "except KeyboardInterrupt:\n"
-        "    print('SIGINT=1', flush=True)\n"
-    )
-    async with open_pty(
-        (sys.executable, "-u", "-c", child_code),
-        rows=8,
-        cols=60,
-        tty_mode="cbreak",
-    ) as pty_sess:
-        await pty_sess.wait_for("DSR='\\x1b[1;11R'", timeout=3.0)
-        assert "CTTY=True" in pty_sess.terminal.text
-        assert pty_sess.terminal.cwd == "/var/tmp"
-        assert "job" in pty_sess.terminal.program_statuses
-        pty_sess.resize(rows=10, cols=70)
-        await pty_sess.wait_for("WINCH=1", timeout=3.0)
-        pty_sess.send(b"\x03")
-        await pty_sess.wait_for("SIGINT=1", timeout=3.0)
-    assert pty_sess.terminal.program_statuses == {}
-
-    # Non-Python execvp targets inherit default SIGPIPE (not Python's SIG_IGN).
-    cat_bin = shutil.which("cat")
-    if cat_bin is not None and pathlib.Path("/proc/self/status").exists():
-        async with vt_pty((cat_bin, "/proc/self/status"), rows=40, cols=80) as cat_sess:
-            snap = await cat_sess.wait_for("SigIgn:", timeout=3.0)
-        sig_ign_hex = next(
-            ln.split(":")[1].strip() for ln in snap.lines if ln.startswith("SigIgn:")
-        )
-        sigpipe_bit = 1 << 12  # signal 13 (SIGPIPE) -> bit 12
-        assert (int(sig_ign_hex, 16) & sigpipe_bit) == 0
-
-    # Missing executable raises FileNotFoundError in parent with zero PTY noise.
-    with pytest.raises(FileNotFoundError):
-        async with open_pty(("definitely-missing-libvt-command-xyz",)):
-            pass
-
-    # Interactive bash + background sleep pipeline reaps cleanly via killpg(SIGHUP),
-    # and custom Policy still receives local hostname in osc7_hosts!
-    bash_bin = shutil.which("bash")
-    if bash_bin is not None:
-        async with open_pty(
-            (bash_bin, "--norc", "--noprofile", "-i"),
-            rows=6,
-            cols=60,
-            policy=libvt.Policy(allow_passthrough=True),
-        ) as bash_sess:
-            bash_sess.send(
-                f"printf '\\033]7;file://{host}/tmp\\007'\n"
-                "sleep 30 &\n"
-                "printf 'BG_%s\\n' OK\n"
-            )
-            await bash_sess.wait_for("BG_OK", timeout=3.0)
-            assert bash_sess.terminal.cwd == "/tmp"
-
-
-def test_assert_screen_literal_borders_and_assert_screen_box(
-    vt_terminal: Terminal,
-    vt_factory: TerminalFactory,
-    vt_parser: libvt.Parser,
-    vt_recorder: FlightRecorder,
-) -> None:
-    """``assert_screen`` keeps borders literal; ``assert_screen_box`` checks frames."""
-    assert vt_terminal.rows == 24
-    assert vt_terminal.cols == 80
-    assert vt_terminal.recorder is vt_recorder
-    assert isinstance(vt_parser, libvt.Parser)
-
-    # Regression test: real DEC Special Graphics border passes assert_screen verbatim!
-    bordered = vt_factory(rows=3, cols=5)
-    bordered.feed(b"\x1b(0lqqqk\r\nx X x\r\nmqqqj\x1b(B")
-    assert bordered.text == "┌───┐\n│ X │\n└───┘"
-    assert_screen(bordered, bordered.text)
-    assert_screen(
-        bordered,
-        """
-        ┌───┐
-        │ X │
-        └───┘
-        """,
-    )
-
-    # Boxed assertions verify column width, soft-wrap 'W', and literal 'W' inside cells.
-    small = vt_factory(rows=2, cols=8)
-    small.feed("日本ok\r\nline2  W".encode())
-    assert_screen_box(
-        small,
-        """
-        ┌────────┐
-        │日本ok  │
-        │line2  W│
-        └────────┘
-        """,
-    )
-
-    wrapped = vt_factory(rows=2, cols=4)
-    wrapped.feed(b"abcdef")
-    assert_screen_box(
-        wrapped,
-        """
-        ┌────┐
-        │abcd│W
-        │ef  │
-        └────┘
-        """,
-        cursor=(1, 2),
-    )
-
-    with pytest.raises(ValueError, match="display width"):
-        assert_screen_box(small, "┌────┐\n│short│\n└────┘")
-
-    spoof_term = vt_factory(rows=1, cols=10, recorder=vt_recorder)
-    spoof_term.feed(b"\x1b[31mhi")
-    spoof_term.screen._rows[0].write_narrow(2, "\u202e", 0, None)
-    with pytest.raises(AssertionError) as exc_info:
-        assert_screen_box(spoof_term, "┌──────────┐\n│mismatch  │\n└──────────┘")
-    msg = str(exc_info.value)
-    assert "\\u202e" in msg
-    assert "Flight Recorder:" in msg
diff --git a/tests/test_benchmark.py b/tests/test_benchmark.py
index 8904740..5c06743 100644
--- a/tests/test_benchmark.py
+++ b/tests/test_benchmark.py
@@ -1,4 +1,4 @@
-"""Tests for the in-process and cross-commit benchmark helpers."""
+"""Tests for in-process and cross-commit benchmark runners."""
 
 from __future__ import annotations
 
@@ -7,23 +7,23 @@
 from scripts import bench_vt, benchmark
 
 
-def test_bench_vt_summarize_and_run() -> None:
-    """In-process benchmark statistics and default suite produce valid metrics."""
+def test_bench_vt_summarize_and_single_pass() -> None:
+    """In-process benchmark statistics and single-pass runner emit valid metrics."""
     stats = bench_vt.summarize([0.010, 0.020, 0.030, 0.040])
     assert stats["n"] == 4.0
     assert stats["min"] == 0.010
     assert stats["max"] == 0.040
     assert stats["p90"] == 0.040
 
-    results = bench_vt.run_benchmarks(warmup=1, runs=2)
+    results = bench_vt.run_benchmarks(warmup=0, runs=1)
     assert len(results) >= 2
-    assert results[0].stats_seconds["n"] == 2.0
+    assert results[0].stats_seconds["n"] == 1.0
 
 
 def test_benchmark_config_layering_and_sanitization(
     tmp_path: pathlib.Path,
 ) -> None:
-    """TOML layers merge cleanly and local paths are sanitized from commands."""
+    """TOML layers merge in precedence order and sanitize local paths."""
     primary = tmp_path / "benchmark.toml"
     primary.write_text(
         '[settings]\nruns = 3\n\n[bench.smoke]\ncommand = "{venv}/bin/python -V"\n',
diff --git a/tests/test_codec_and_cli.py b/tests/test_codec.py
similarity index 55%
rename from tests/test_codec_and_cli.py
rename to tests/test_codec.py
index 2b62996..5a5f7d2 100644
--- a/tests/test_codec_and_cli.py
+++ b/tests/test_codec.py
@@ -1,9 +1,9 @@
-"""Declarative VT sequence explainer and ``python -m libvt`` CLI tests."""
+"""Tests for ``libvt.codec`` sequence disassembly and ``python -m libvt`` CLI."""
 
 from __future__ import annotations
 
+import io
 import pathlib
-import subprocess
 import sys
 
 import pytest
@@ -12,29 +12,32 @@
 from libvt.codec import explain, format_explain
 
 
-def test_codec_explain_and_format_explain() -> None:
-    """``explain`` and ``format_explain`` annotate SGR, CSI, OSC, DCS, and UTF-8."""
+def test_explain_disassembles_csi_subparams_osc_dcs_and_hpr_vpr() -> None:
+    """``explain`` and ``format_explain`` classify SGR, CSI, OSC, and DCS spans."""
     sample = (
-        b"\x1b[?2026h\x1b[1;38:2::10:20:30mHi\r\n"
+        b"\x1b[?2026h\x1b[1;38:2::10:20:30mHi\x1b[3a\x1b[2e\r\n"
         b"\x1b]7501;state=working\x1b\\\x1bP>|libvt\x1b\\\x1b[?2026l"
     )
     items = explain(sample)
     kinds = {it.kind for it in items}
-    mnemonics = {it.mnemonic for it in items}
+    mnemonics = [it.mnemonic for it in items]
     assert {"CSI", "PRINT", "C0", "OSC", "DCS"} <= kinds
     assert "SGR" in mnemonics
     assert "DECSET" in mnemonics
+    assert "HPR" in mnemonics
+    assert "VPR" in mnemonics
 
     rendered = format_explain(sample)
     assert "SGR" in rendered
     assert "7501" in rendered
 
 
-def test_cli_explain_render_and_strip(
+def test_cli_subcommands_file_and_stdin(
     tmp_path: pathlib.Path,
     capsys: pytest.CaptureFixture[str],
+    monkeypatch: pytest.MonkeyPatch,
 ) -> None:
-    """``python -m libvt`` subcommands process files and stdin byte streams."""
+    """``python -m libvt`` subcommands process file paths and ``stdin`` streams."""
     sample_file = tmp_path / "sample.vt"
     sample_file.write_bytes(b"\x1b[1;32mhello\x1b[0m\r\nworld")
 
@@ -45,14 +48,12 @@ def test_cli_explain_render_and_strip(
     assert capsys.readouterr().out == "hello\nworld\n"
 
     assert main(["explain", str(sample_file)]) == 0
-    explained = capsys.readouterr().out
-    assert "SGR" in explained
-
-    proc = subprocess.run(
-        (sys.executable, "-m", "libvt", "strip"),
-        input=b"\x1b[1;34mpiped\x1b[0m\n",
-        capture_output=True,
-        check=False,
+    assert "SGR" in capsys.readouterr().out
+
+    monkeypatch.setattr(
+        sys,
+        "stdin",
+        io.TextIOWrapper(io.BytesIO(b"\x1b[1;34mpiped\x1b[0m\n")),
     )
-    assert proc.returncode == 0
-    assert proc.stdout == b"piped\n"
+    assert main(["strip"]) == 0
+    assert capsys.readouterr().out == "piped\n"
diff --git a/tests/test_exc.py b/tests/test_exc.py
new file mode 100644
index 0000000..ef99ab4
--- /dev/null
+++ b/tests/test_exc.py
@@ -0,0 +1,123 @@
+"""Tests for ``libvt.exc`` exception hierarchy, notes, and pickling."""
+
+from __future__ import annotations
+
+import copy
+import pickle
+import traceback
+
+from libvt.exc import TerminalTimeoutError
+from libvt.parser import ParserState
+
+
+class _SlottedTimeoutError(TerminalTimeoutError):
+    """Subclass with ``__slots__`` and custom keyword-only ``__init__``."""
+
+    __slots__ = ("attempt",)
+
+    def __init__(
+        self,
+        message: str,
+        *,
+        attempt: int,
+        parser_state: ParserState = ParserState.GROUND,
+        screen_text: str = "",
+        recent_bytes: bytes | bytearray | memoryview = b"",
+    ) -> None:
+        super().__init__(
+            message,
+            parser_state=parser_state,
+            screen_text=screen_text,
+            recent_bytes=recent_bytes,
+            eof=False,
+        )
+        self.attempt = attempt
+
+
+class _DynamicTimeoutError(TerminalTimeoutError):
+    """Subclass allowing dynamic ``__dict__`` attributes."""
+
+    extra_context: str = ""
+
+
+def test_timeout_error_zero_arg_and_attach_note_suppression() -> None:
+    """Zero-arg construction keeps ``args == ()``; ``attach_note=False`` omits notes."""
+    empty = TerminalTimeoutError()
+    assert isinstance(empty, TimeoutError)
+    assert empty.args == ()
+    assert str(empty) == ""
+    assert empty.errno is None
+
+    quiet = TerminalTimeoutError(
+        "quiet timeout",
+        screen_text="secret-viewport",
+        attach_note=False,
+    )
+    assert not hasattr(quiet, "__notes__")
+    assert "secret-viewport" in quiet.format_diagnostics()
+    for proto in (0, pickle.HIGHEST_PROTOCOL):
+        quiet_rt = pickle.loads(pickle.dumps(quiet, protocol=proto))
+        assert not hasattr(quiet_rt, "__notes__")
+        assert quiet_rt.screen_text == "secret-viewport"
+
+
+def test_timeout_error_slots_subclasses_copy_pickle_and_exception_group() -> None:
+    """``TerminalTimeoutError`` preserves slots, dynamic attrs, and unaliased notes."""
+    slotted = _SlottedTimeoutError(
+        "slotted timeout",
+        attempt=4,
+        parser_state=ParserState.CSI_PARAM,
+        screen_text="row0",
+        recent_bytes=b"\x1b[1;",
+    )
+    slotted.add_note("slot-note")
+    for proto in (0, pickle.HIGHEST_PROTOCOL):
+        slotted_rt = pickle.loads(pickle.dumps(slotted, protocol=proto))
+        assert type(slotted_rt) is _SlottedTimeoutError
+        assert slotted_rt.attempt == 4
+        assert slotted_rt.errno is None
+        assert slotted_rt.__notes__ == slotted.__notes__
+    for cloned_slot in (copy.copy(slotted), copy.deepcopy(slotted)):
+        assert type(cloned_slot) is _SlottedTimeoutError
+        assert cloned_slot.attempt == 4
+        assert cloned_slot.__notes__ == slotted.__notes__
+
+    sub = _DynamicTimeoutError(
+        "timed out waiting for prompt",
+        parser_state=ParserState.OSC_STRING,
+        screen_text="$ stuck",
+        recent_bytes=memoryview(b"\x1b]0;unterminated"),
+        eof=False,
+    )
+    sub.add_note("attempt=3")
+    sub.extra_context = "pane-%1"
+
+    assert str(sub) == "timed out waiting for prompt"
+    assert "\n" not in str(sub)
+    assert isinstance(sub.recent_bytes, bytes)
+    assert any("OSC_STRING" in n for n in sub.__notes__)
+    assert "parser_state=OSC_STRING" in "".join(traceback.format_exception(sub))
+
+    shallow = copy.copy(sub)
+    shallow.add_note("shallow-only")
+    assert "shallow-only" not in sub.__notes__
+
+    restored = pickle.loads(pickle.dumps(sub, protocol=pickle.HIGHEST_PROTOCOL))
+    assert type(restored) is _DynamicTimeoutError
+    assert restored.errno is None
+    assert restored.parser_state == ParserState.OSC_STRING
+    assert restored.recent_bytes == b"\x1b]0;unterminated"
+    assert restored.__notes__ == sub.__notes__
+    assert restored.extra_context == "pane-%1"
+
+    caught: list[TerminalTimeoutError] = []
+    group_msg = "batch"
+    other_msg = "other"
+    try:
+        raise ExceptionGroup(group_msg, [sub, ValueError(other_msg)])
+    except* TimeoutError as eg:
+        caught.extend(e for e in eg.exceptions if isinstance(e, TerminalTimeoutError))
+    except* ValueError:
+        pass
+    assert len(caught) == 1
+    assert caught[0].__notes__ == sub.__notes__
diff --git a/tests/test_graphics.py b/tests/test_graphics.py
new file mode 100644
index 0000000..730d4a3
--- /dev/null
+++ b/tests/test_graphics.py
@@ -0,0 +1,128 @@
+"""Tests for ``libvt.graphics`` zero-dependency ``SIXEL`` and Kitty ``APC G``."""
+
+from __future__ import annotations
+
+import base64
+import struct
+import time
+import typing as t
+import zlib
+
+import pytest
+
+import libvt
+from libvt.config import Profile
+from libvt.events import KittyGraphic
+from libvt.graphics import GraphicsProtocol, ZLayer
+
+
+def _minimal_png(width: int, height: int) -> bytes:
+    """Construct a minimal PNG header with ``IHDR`` dimensions ``(width, height)``."""
+    ihdr_body = struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0)
+    ihdr_crc = struct.pack(">I", zlib.crc32(b"IHDR" + ihdr_body) & 0xFFFFFFFF)
+    return b"\x89PNG\r\n\x1a\n" + struct.pack(">I", 13) + b"IHDR" + ihdr_body + ihdr_crc
+
+
+def test_kitty_chunked_upload_validation_and_relative_placements() -> None:
+    """Kitty ``APC G`` validates uploads, silences unnumbered IDs, and links parents."""
+    png_bytes = _minimal_png(16, 32)
+    z_payload = base64.b64encode(zlib.compress(png_bytes))
+    part1, part2 = z_payload[:12], z_payload[12:]
+
+    term = libvt.Terminal(rows=6, cols=10, scrollback=10)
+    term.feed(b"\x1b[2;3H\x1b_Ga=T,f=100,o=z,i=7,p=1,z=-5,m=1;" + part1 + b"\x1b\\")
+    assert len(term.placements) == 0
+    term.feed(b"\x1b_Gm=0;" + part2 + b"\x1b\\")
+    assert b"\x1b_Gi=7,p=1;OK\x1b\\" in term.drain_replies()
+    assert len(term.placements) == 1
+    kp = term.placements[0]
+    assert (kp.protocol, kp.row, kp.col, kp.rows, kp.cols, kp.layer) == (
+        GraphicsProtocol.KITTY,
+        1,
+        2,
+        2,
+        2,
+        ZLayer.BELOW_TEXT,
+    )
+    assert (term.cursor.row, term.cursor.col) == (2, 4)
+
+    # U=0 overlay survives text overwrite; d=y with missing y=0 is a safe no-op.
+    term.feed(b"\x1b[2;3HOVER\x1b[K\x1b_Ga=d,d=y\x1b\\")
+    assert len(term.placements) == 1
+
+    # Retransmitting i=7 clears stale placements; unnumbered upload stays silent.
+    raw_1cell = base64.b64encode(b"\xff" * (8 * 16 * 3))
+    term.feed(b"\x1b[1;1H\x1b_Ga=t,f=24,s=8,v=16,i=7;" + raw_1cell + b"\x1b\\")
+    assert (len(term.placements), b"\x1b_Gi=7;OK\x1b\\" in term.drain_replies()) == (
+        0,
+        True,
+    )
+    term.feed(b"\x1b[1;1H\x1b_Ga=T,f=24,s=8,v=16;" + raw_1cell + b"\x1b\\")
+    assert (term.drain_replies(), len(term.placements)) == (b"", 1)
+
+    # Reject missing-i query, mutually exclusive i+I, truncated raw/zlib, and t=f.
+    term.feed(b"\x1b_Ga=q,f=24,s=1,v=1;" + base64.b64encode(b"abc") + b"\x1b\\")
+    assert term.drain_replies() == b""
+    for bad_pkt in (
+        b"\x1b_Ga=t,i=2,I=3,f=24,s=1,v=1;" + base64.b64encode(b"abc") + b"\x1b\\",
+        b"\x1b_Ga=t,i=8,f=24,s=8,v=16;" + base64.b64encode(b"short") + b"\x1b\\",
+        b"\x1b_Ga=t,i=9,f=100,o=z;"
+        + base64.b64encode(zlib.compress(png_bytes)[:-4])
+        + b"\x1b\\",
+        b"\x1b_Ga=T,t=f,i=99;" + base64.b64encode(b"/etc/passwd") + b"\x1b\\",
+    ):
+        term.feed(bad_pkt)
+        assert b"EINVAL" in term.drain_replies()
+
+    # Virtual U=1 parent rejected as non-virtual parent; real parent cascades delete.
+    term.feed(b"\x1b_Ga=T,U=1,i=20,p=1,c=2,r=2,f=24,s=8,v=16;" + raw_1cell + b"\x1b\\")
+    term.feed(b"\x1b_Ga=p,i=20,p=2,P=20,Q=1\x1b\\")
+    assert b"ENOPARENT" in term.drain_replies()
+    term.feed(b"\x1b[2;2H\x1b_Ga=p,i=20,p=3,c=2,r=2\x1b\\")
+    term.feed(b"\x1b_Ga=p,i=20,p=4,P=20,Q=3,H=2,V=1\x1b\\")
+    term.drain_replies()
+    child = [p for p in term.placements if p.image_id == 20 and p.placement_id == 4]
+    assert len(child) == 1
+    assert (child[0].row, child[0].col) == (2, 3)
+    term.feed(b"\x1b_Ga=d,d=i,i=20,p=3\x1b\\")
+    assert not any(
+        p.image_id == 20 and p.placement_id in (3, 4) for p in term.placements
+    )
+
+
+def test_scroll_before_place_sixel_erase_policies_and_event_immutability() -> None:
+    """Alt-screen scroll-before-place, ``SIXEL`` erase policies, and ``O(rows)``."""
+    alt_t = libvt.Terminal(rows=4, cols=8)
+    raw_2row = base64.b64encode(b"\xaa" * (16 * 32 * 3))
+    alt_t.feed(b"\x1b[?1049h\x1b[4;2H\x1b_Ga=T,f=24,s=16,v=32;" + raw_2row + b"\x1b\\")
+    assert (alt_t.placements[0].row, alt_t.placements[0].rows) == (2, 2)
+
+    sixel_seq = b'\x1bP0;1;0q"1;1;16;32#0!16~-#0!16~-#0!16~-#0!16~-#0!16~\x1b\\'
+    vt_sixel = libvt.Terminal(rows=6, cols=10, profile=Profile.tmux("next-3.9"))
+    vt_sixel.feed(sixel_seq)
+    assert (vt_sixel.placements[0].rows, vt_sixel.cursor.row) == (2, 2)
+    vt_sixel.feed(b"\x1b[1;1HX")
+    assert (
+        vt_sixel.placements[0].occupies_cell(0, 0),
+        vt_sixel.placements[0].occupies_cell(0, 1),
+    ) == (False, True)
+
+    tm38_sixel = libvt.Terminal(rows=6, cols=10, profile=Profile.tmux("3.8a"))
+    tm38_sixel.feed(sixel_seq + b"\x1b[1;1HX")
+    assert len(tm38_sixel.placements) == 0
+
+    # 10,000px SIXEL under DECLRMM stays O(rows) without per-row linefeed loops.
+    dos_t = libvt.Terminal(rows=24, cols=80, record_events=True)
+    t0 = time.monotonic()
+    for _ in range(10):
+        dos_t.feed(b'\x1b[?69h\x1b[10;20s\x1b[1;1H\x1bPq"1;1;10;10000#0~\x1b\\')
+    assert time.monotonic() - t0 < 0.1
+
+    ev_t = libvt.Terminal(rows=4, cols=8, record_events=True)
+    raw_1cell = base64.b64encode(b"\xff" * (8 * 16 * 3))
+    ev_t.feed(b"\x1b_Ga=T,f=24,s=8,v=16,i=5;" + raw_1cell + b"\x1b\\")
+    evs = [e for e in ev_t.drain_events() if isinstance(e, KittyGraphic)]
+    with pytest.raises(TypeError):
+        t.cast("dict[str, str]", evs[0].command.control)["a"] = "d"
+    with pytest.raises(TypeError):
+        t.cast("dict[int, object]", ev_t.snapshot().images)[999] = None
diff --git a/tests/test_incremental_tmux_and_graphics.py b/tests/test_incremental_tmux_and_graphics.py
deleted file mode 100644
index b00019b..0000000
--- a/tests/test_incremental_tmux_and_graphics.py
+++ /dev/null
@@ -1,705 +0,0 @@
-"""Regression and feature tests for incremental deltas, tmux capture, and graphics."""
-
-from __future__ import annotations
-
-import asyncio
-import base64
-import copy
-import pickle
-import shutil
-import struct
-import subprocess
-import time
-import traceback
-import zlib
-
-import pytest
-
-import libvt
-from libvt import _ucd
-from libvt.aio import AsyncTerminalStream
-from libvt.config import DEFAULT_PROFILE, TMUX_PROFILE, Profile
-from libvt.events import KittyGraphic
-from libvt.exc import TerminalTimeoutError
-from libvt.graphics import GraphicsProtocol, ZLayer
-from libvt.modes import Mode
-from libvt.parser import ParserState
-from libvt.screen import RowView
-from libvt.style import AnsiColor
-from libvt.terminal import ResyncReason
-from libvt.tmux import (
-    TMUX_METADATA_FORMAT,
-    TmuxLineFlags,
-    TmuxPaneMetadata,
-    decode_tmux_capture,
-    unescape_tmux_control_output,
-)
-
-
-class _SlottedTimeoutError(TerminalTimeoutError):
-    """Downstream subclass with ``__slots__`` and custom keyword-only ``__init__``."""
-
-    __slots__ = ("attempt",)
-
-    def __init__(
-        self,
-        message: str,
-        *,
-        attempt: int,
-        parser_state: ParserState = ParserState.GROUND,
-        screen_text: str = "",
-        recent_bytes: bytes | bytearray | memoryview = b"",
-    ) -> None:
-        super().__init__(
-            message,
-            parser_state=parser_state,
-            screen_text=screen_text,
-            recent_bytes=recent_bytes,
-            eof=False,
-        )
-        self.attempt = attempt
-
-
-class _DynamicTimeoutError(TerminalTimeoutError):
-    """Downstream subclass allowing arbitrary instance attributes."""
-
-    extra_context: str = ""
-
-
-async def test_timeout_error_notes_slots_subclasses_and_concise_str() -> None:
-    """``TerminalTimeoutError`` preserves ``__notes__``, slots, and 1-line ``str``."""
-    empty = TerminalTimeoutError()
-    assert empty.args == ()
-    assert str(empty) == ""
-    assert empty.errno is None
-
-    quiet = TerminalTimeoutError(
-        "quiet timeout",
-        screen_text="secret-viewport",
-        attach_note=False,
-    )
-    assert not hasattr(quiet, "__notes__")
-    for proto in range(pickle.HIGHEST_PROTOCOL + 1):
-        quiet_rt = pickle.loads(pickle.dumps(quiet, protocol=proto))
-        assert not hasattr(quiet_rt, "__notes__")
-        assert quiet_rt.screen_text == "secret-viewport"
-
-    slotted = _SlottedTimeoutError(
-        "slotted timeout",
-        attempt=4,
-        parser_state=ParserState.CSI_PARAM,
-        screen_text="row0",
-        recent_bytes=b"\x1b[1;",
-    )
-    slotted.add_note("slot-note")
-    for proto in range(pickle.HIGHEST_PROTOCOL + 1):
-        slotted_rt = pickle.loads(pickle.dumps(slotted, protocol=proto))
-        assert type(slotted_rt) is _SlottedTimeoutError
-        assert slotted_rt.attempt == 4
-        assert slotted_rt.errno is None
-        assert slotted_rt.__notes__ == slotted.__notes__
-    for cloned_slot in (copy.copy(slotted), copy.deepcopy(slotted)):
-        assert type(cloned_slot) is _SlottedTimeoutError
-        assert cloned_slot.attempt == 4
-        assert cloned_slot.__notes__ == slotted.__notes__
-
-    sub = _DynamicTimeoutError(
-        "timed out waiting for prompt",
-        parser_state=ParserState.OSC_STRING,
-        screen_text="$ stuck",
-        recent_bytes=memoryview(b"\x1b]0;unterminated"),
-        eof=False,
-    )
-    sub.add_note("attempt=3")
-    sub.extra_context = "pane-%1"
-
-    assert str(sub) == "timed out waiting for prompt"
-    assert "\n" not in str(sub)
-    assert isinstance(sub.recent_bytes, bytes)
-    assert any("OSC_STRING" in n for n in sub.__notes__)
-    assert "attempt=3" in sub.__notes__
-
-    shallow = copy.copy(sub)
-    shallow.add_note("shallow-only")
-    assert "shallow-only" not in sub.__notes__
-
-    for proto in range(pickle.HIGHEST_PROTOCOL + 1):
-        restored = pickle.loads(pickle.dumps(sub, protocol=proto))
-        assert type(restored) is _DynamicTimeoutError
-        assert restored.errno is None
-        assert str(restored) == "timed out waiting for prompt"
-        assert restored.parser_state == ParserState.OSC_STRING
-        assert restored.screen_text == "$ stuck"
-        assert restored.recent_bytes == b"\x1b]0;unterminated"
-        assert restored.eof is False
-        assert restored.__notes__ == sub.__notes__
-        assert restored.extra_context == "pane-%1"
-
-    caught: list[TerminalTimeoutError] = []
-    group_msg = "batch"
-    other_msg = "other"
-    try:
-        raise ExceptionGroup(group_msg, [sub, ValueError(other_msg)])
-    except* TimeoutError as eg:
-        caught.extend(e for e in eg.exceptions if isinstance(e, TerminalTimeoutError))
-    except* ValueError:
-        pass
-    assert len(caught) == 1
-    assert caught[0].__notes__ == sub.__notes__
-
-    reader = asyncio.StreamReader()
-    stream = AsyncTerminalStream(reader, rows=2, cols=12)
-    reader.feed_data(b"hello\x1b]0;stuck")
-    with pytest.raises(TerminalTimeoutError) as exc_info:
-        await stream.wait_for("missing", timeout=0.02)
-    err = exc_info.value
-    assert "\n" not in str(err)
-    assert "Flight Recorder:" not in str(err)
-    assert "Flight Recorder:" in err.format_diagnostics()
-    assert any("Flight Recorder:" in n for n in err.__notes__)
-    assert "Flight Recorder:" in "".join(traceback.format_exception(err))
-
-    with pytest.raises(TerminalTimeoutError) as no_note_exc:
-        await stream.wait_for("missing", timeout=0.01, attach_note=False)
-    assert not hasattr(no_note_exc.value, "__notes__")
-
-
-def test_right_margin_widening_zwsp_and_safe_narrow_bmp_slicing() -> None:
-    """Right-margin ``VS16`` keeps SGR/margins, ``ZWSP`` breaks, ``?7l`` is fast."""
-    for chunk_mode in ("whole", "per_char", "per_byte"):
-        term = libvt.Terminal(rows=3, cols=4)
-        payload = "\x1b[31mabc1\x1b[34m\ufe0f\u20e3Z"
-        if chunk_mode == "whole":
-            term.feed_str(payload)
-        elif chunk_mode == "per_char":
-            for ch in payload:
-                term.feed_str(ch)
-        else:
-            raw = payload.encode("utf-8")
-            for idx in range(len(raw)):
-                term.feed(raw[idx : idx + 1])
-
-        assert term[0].text == "abc"
-        assert term[0].wrapped is True
-        assert term[1, 0].text == "1\ufe0f\u20e3"
-        assert term[1, 0].width == 2
-        assert term[1, 0].style.fg == AnsiColor.RED
-        assert term[1, 2].text == "Z"
-        assert term[1, 2].style.fg == AnsiColor.BLUE
-
-    # DECSTBM bottom < rows - 1 keeps wrapped=True after right-margin widening scroll.
-    bounded = libvt.Terminal(rows=4, cols=4)
-    bounded.feed_str("\x1b[1;2rL0\r\nabc1\ufe0f\u20e3Z")
-    assert bounded[0].text == "abc"
-    assert bounded[0].wrapped is True
-    assert bounded[1, 0].text == "1\ufe0f\u20e3"
-    assert bounded[1, 2].text == "Z"
-
-    # Mode.IRM shifts existing text on the destination row when widening wraps.
-    irm = libvt.Terminal(rows=3, cols=4)
-    irm.feed_str("\x1b[2;1HXY\x1b[1;1H\x1b[4habc1\ufe0f\u20e3")
-    assert irm[1, 0].text == "1\ufe0f\u20e3"
-    assert irm[1, 2].text == "X"
-    assert irm[1, 3].text == "Y"
-
-    # U+200B ZERO WIDTH SPACE is GCB=Control (GB4/GB5) and must break the cluster.
-    zwsp_term = libvt.Terminal(rows=2, cols=6)
-    zwsp_term.feed_str("1\u200b\ufe0fA")
-    assert zwsp_term[0, 0].text == "1"
-    assert zwsp_term[0, 0].width == 1
-    assert zwsp_term[0, 1].text == "A"
-
-    matched_cps = [
-        cp
-        for cp in range(0x10000)
-        if _ucd.SAFE_NARROW_BMP_RE.match(chr(cp)) is not None
-    ]
-    assert len(matched_cps) >= 18_000
-    for sample in ("┌", "─", "│", "█", "Ω", "д", "→", "⠿"):
-        assert _ucd.SAFE_NARROW_BMP_RE.match(sample) is not None
-    for unsafe in (
-        "\u0301",
-        "\ufe0f",
-        "\u200d",
-        "中",
-        "\u202e",
-        "\x00",
-        "\x7f",
-        "\x85",
-    ):
-        assert _ucd.SAFE_NARROW_BMP_RE.match(unsafe) is None
-
-    mixed = "┌── Ωμέγα 🚀 Кириллица ──┐#1\ufe0f\u20e3*2\ufe0f"
-    bulk = libvt.Terminal(rows=4, cols=16)
-    bulk.feed_str(mixed)
-    scalar = libvt.Terminal(rows=4, cols=16)
-    for ch in mixed:
-        scalar.feed_str(ch)
-    assert bulk.lines == scalar.lines
-    assert bulk.cursor == scalar.cursor
-
-    # ?7l (DECAWM disabled) collapses right-margin slice overwrites in O(cols) time.
-    no_wrap = libvt.Terminal(rows=2, cols=8)
-    t0 = time.monotonic()
-    no_wrap.feed_str("\x1b[?7l" + ("ABCDEFGH" * 12_500) + "!")
-    elapsed = time.monotonic() - t0
-    assert elapsed < 0.2
-    assert no_wrap[0].text == "ABCDEFG!"
-
-
-def test_tmux_profile_decstr_ed2_history_versions_and_linux_console() -> None:
-    """``Profile.tmux`` handles ``next-3.9``/``rc``, ``DECSTR``, and ``ED 2``."""
-    p_next = Profile.tmux("next-3.9")
-    assert p_next.sixel_erase_policy == "cell_mask"
-    p_rc = Profile.tmux("tmux 3.8-rc3")
-    assert p_rc.sixel_erase_policy == "whole_image"
-    p_prefixed = Profile.tmux("tmux 3.8a")
-    assert p_prefixed.sixel_erase_policy == "whole_image"
-
-    lt = libvt.Terminal(rows=2, cols=8, profile=Profile.linux_console())
-    lt.feed(b"\x0elqqk\x0f")
-    assert lt[0].text == "┌──┐"
-
-    tm = libvt.Terminal(rows=4, cols=10, scrollback=20, profile=TMUX_PROFILE)
-    tm.feed(b"\x1b[31m\x1b[?7l\x1b[!pA")
-    assert tm.modes.is_set(Mode.DECAWM) is False
-    assert tm[0, 0].style.fg == AnsiColor.RED
-
-    vt = libvt.Terminal(rows=4, cols=10, profile=DEFAULT_PROFILE)
-    vt.feed(b"\x1b[31m\x1b[?7l\x1b[!pA")
-    assert vt.modes.is_set(Mode.DECAWM) is True
-    assert vt[0, 0].style.fg is None
-
-    tm2 = libvt.Terminal(rows=4, cols=10, scrollback=20, profile=TMUX_PROFILE)
-    tm2.feed(b"ROW_ONE\r\nROW_TWO\x1b[4;5H\x1b[44m\x1b[2J")
-    assert [r.text for r in tm2.history] == ["ROW_ONE", "ROW_TWO"]
-    assert tm2.lines == ("", "", "", "")
-    assert tm2[0, 0].style.bg == AnsiColor.BLUE
-    assert (tm2.cursor.row, tm2.cursor.col) == (3, 4)
-
-    # ED 0 at (0, 0) scrolls primary content (including BCE-colored rows) into history.
-    tm2.feed(b"\x1b[0m\x1b[HHOME_ROW\x1b[H\x1b[J")
-    assert [r.text for r in tm2.history] == [
-        "ROW_ONE",
-        "ROW_TWO",
-        "HOME_ROW",
-        "",
-        "",
-        "",
-    ]
-    assert tm2.history[3][0].style.bg == AnsiColor.BLUE
-
-    tm2.feed(b"\x1b[?1049hALT_LINE\x1b[2J")
-    assert len(tm2.history) == 6
-    assert tm2.lines == ("", "", "", "")
-
-
-def test_tmux_capture_decoder_synthetic_and_live() -> None:
-    """``decode_tmux_capture`` decodes ``list[str]``, ``-J``, and live ``tmux``."""
-    assert unescape_tmux_control_output(r"\033[31mhi\134there\015\012") == (
-        b"\x1b[31mhi\\there\r\n"
-    )
-    raw_utf8_line = b"caf\xc3\xa9\\012".decode("utf-8", errors="surrogateescape")
-    assert unescape_tmux_control_output(raw_utf8_line) == b"caf\xc3\xa9\n"
-
-    # Format string uses real tmux format names and parses UINT_MAX saved coords.
-    assert "#{bracket_paste_flag}" in TMUX_METADATA_FORMAT
-    assert "#{mouse_all_flag}" in TMUX_METADATA_FORMAT
-    assert "#{pane_private_modes}" in TMUX_METADATA_FORMAT
-    raw_fmt = (
-        "8\t3\t0\t2\t1\t0\t4294967295\t4294967295\t0\t2\t"
-        "0\t0\t1\t0\t1\t0\t0\t1\t1\t1004,2004\t"
-        "0,4\t0\t2000\t1\t7\t/tmp\ttitle"
-    )
-    parsed_meta = TmuxPaneMetadata.from_format_line(raw_fmt)
-    assert parsed_meta.alternate_saved_x is None
-    assert parsed_meta.alternate_saved_y is None
-    assert parsed_meta.bracketed_paste_flag is True
-    assert parsed_meta.mouse_any_flag is True
-    assert parsed_meta.focus_events_flag is True
-    assert parsed_meta.synchronized is True
-
-    # Sequence[str] input (libtmux capture_pane() shape) + ?2026 synchronized hold.
-    sync_term = libvt.Terminal.from_tmux_capture(
-        ["HOLD_LIN", "", ""],
-        metadata=raw_fmt,
-    )
-    assert sync_term.synchronized is True
-    sync_term.feed(b"\x1b[1;1HDIRTY")
-    assert sync_term.committed[0].text == "HOLD_LIN"
-    sync_term.feed(b"\x1b[?2026l")
-    assert sync_term.committed[0].text == "DIRTYLIN"
-
-    # Unflagged capture + joined_capture infers 3-row soft wrap + CJK SPACER_HEAD wrap,
-    # and flagged P/O lines keep PromptZone rows accurate when scrollback < hist_count.
-    unflagged_lines = ["H0", "H1", "ABCD", "EFGH", "IJ", "abc ", "中文"]
-    joined_lines = ["H0", "H1", "ABCDEFGHIJ", "abc中文"]
-    cjk_meta = TmuxPaneMetadata(cols=4, rows=5, history_size=2)
-    cjk_term = libvt.Terminal.from_tmux_capture(
-        unflagged_lines,
-        metadata=cjk_meta,
-        scrollback=1,
-        joined_capture=joined_lines,
-    )
-    assert [r.text for r in cjk_term.history] == ["H1"]
-    assert cjk_term[0].wrapped is True
-    assert cjk_term[1].wrapped is True
-    assert cjk_term[2].wrapped is False
-    assert cjk_term[3].wrapped is True
-    cjk_term.resize(rows=5, cols=10)
-    assert cjk_term.lines[:3] == ("H1", "ABCDEFGHIJ", "abc中文")
-
-    pz_snap = libvt.Snapshot.from_tmux_capture(
-        ["P H0", "P H1", "- V0", "O V1", "- V2", "- V3", "- V4"],
-        metadata=cjk_meta,
-        scrollback=1,
-        flagged=True,
-    )
-    assert [r.text for r in pz_snap.history] == ["H1"]
-    assert [(z.row, z.kind.value) for z in pz_snap.prompt_zones] == [
-        (-1, "A"),
-        (1, "C"),
-    ]
-
-    # Synthetic flagged (-F -e -p -N) capture with scrollback, bare SO/SI ACS,
-    # SGR carry across rows, custom tabstops, soft wrap, and pending_wrap.
-    meta = TmuxPaneMetadata(
-        cols=8,
-        rows=3,
-        cursor_x=8,
-        cursor_y=2,
-        wrap_flag=True,
-        pane_tabs=(4, 8),
-        output_generation=42,
-    )
-    captured = (
-        "- HIST_0  \n"
-        "X \x1b[31m\x0elqqk\x0f    \n"
-        "WX ABCDEFGH\n"
-        "X \x1b[44m\t\x1b[49m1234\n"
-    )
-    res = decode_tmux_capture(
-        captured,
-        metadata=meta,
-        post_metadata=meta,
-        flagged=True,
-    )
-    assert res.completeness.exact_wraps is True
-    assert res.completeness.exact_generation_bracket is True
-    assert TmuxLineFlags.WRAPPED in res.line_flags[2]
-    assert [r.text for r in res.snapshot.history] == ["HIST_0"]
-    assert res.terminal[0].text == "┌──┐"
-    assert res.terminal[0, 0].style.fg == AnsiColor.RED
-    assert res.terminal[1].text == "ABCDEFGH"
-    assert res.terminal[1].wrapped is True
-    assert res.terminal[1, 0].style.fg == AnsiColor.RED
-    assert res.terminal[2].text == "    1234"
-    assert res.terminal[2, 0].style.bg == AnsiColor.BLUE
-    assert res.terminal[2, 3].style.bg == AnsiColor.BLUE
-    assert res.terminal[2, 4].style.bg is None
-    assert res.terminal.cursor.row == 2
-    assert res.terminal.cursor.col == 7
-    assert res.terminal.cursor.pending_wrap is True
-    res.terminal.feed(b"\x1b[0m!\x0el\x0f")
-    assert res.terminal[2].text == "!l"
-
-    if shutil.which("tmux") is not None:
-        sock = f"libvt-test-{zlib.crc32(b'incremental-tmux')}"
-        try:
-            subprocess.run(
-                [
-                    "tmux",
-                    "-L",
-                    sock,
-                    "-f",
-                    "/dev/null",
-                    "new-session",
-                    "-d",
-                    "-x",
-                    "10",
-                    "-y",
-                    "3",
-                    "sh",
-                    "-c",
-                    (
-                        "printf '\\033[?2004h\\033(0lqqk\\033(B\\r\\n"
-                        "1234567890WRAP\\r\\n\\t\\033[42mX\\033[0m'; sleep 30"
-                    ),
-                ],
-                check=True,
-            )
-            for _ in range(100):
-                chk = subprocess.run(
-                    ["tmux", "-L", sock, "capture-pane", "-p"],
-                    check=True,
-                    capture_output=True,
-                    text=True,
-                )
-                if "X" in chk.stdout:
-                    break
-                time.sleep(0.02)
-            else:
-                pytest.fail("timed out waiting for tmux pane output")
-            meta_raw = subprocess.run(
-                [
-                    "tmux",
-                    "-L",
-                    sock,
-                    "display-message",
-                    "-p",
-                    TMUX_METADATA_FORMAT,
-                ],
-                check=True,
-                capture_output=True,
-                text=True,
-            ).stdout.rstrip("\n")
-            cap_raw = subprocess.run(
-                [
-                    "tmux",
-                    "-L",
-                    sock,
-                    "capture-pane",
-                    "-S",
-                    "-",
-                    "-E",
-                    "-",
-                    "-F",
-                    "-e",
-                    "-p",
-                    "-N",
-                ],
-                check=True,
-                capture_output=True,
-                text=True,
-            ).stdout
-            live_res = decode_tmux_capture(cap_raw, metadata=meta_raw, flagged=True)
-            assert live_res.terminal.modes.is_set(Mode.BRACKETED_PASTE) is True
-            assert [r.text for r in live_res.snapshot.history] == ["┌──┐"]
-            assert live_res.terminal[0].text == "1234567890"
-            assert live_res.terminal[0].wrapped is True
-            assert live_res.terminal[1].text == "WRAP"
-            assert live_res.terminal[2].text == "        X"
-            assert live_res.terminal[2, 0].style.bg is None
-            assert live_res.terminal[2, 8].style.bg == AnsiColor.GREEN
-        finally:
-            subprocess.run(
-                ["tmux", "-L", sock, "kill-server"],
-                check=False,
-                capture_output=True,
-            )
-
-
-def test_changes_since_watermarks_and_replica_equivalence() -> None:
-    """``changes_since`` and ``apply_lines``/``apply_rows`` stay exact."""
-    term = libvt.Terminal(
-        rows=4,
-        cols=6,
-        scrollback=6,
-        profile=TMUX_PROFILE,
-    )
-    rep_lines_hist: list[str] = []
-    rep_lines_view: list[str] = []
-    rep_rows_hist: list[RowView] = []
-    rep_rows_view: list[RowView] = []
-
-    def _step_and_assert(tok: libvt.SyncToken | None) -> libvt.ScreenDelta:
-        delta = term.changes_since(tok)
-        delta.apply_lines(rep_lines_hist, rep_lines_view)
-        delta.apply_rows(rep_rows_hist, rep_rows_view)
-        snap = delta.snapshot
-        assert rep_lines_hist == [r.text for r in snap.history]
-        assert rep_lines_view == list(snap.lines)
-        assert [r.text for r in rep_rows_hist] == [r.text for r in snap.history]
-        assert [(r.text, r.wrapped) for r in rep_rows_view] == [
-            (snap[i].text, snap[i].wrapped) for i in range(snap.rows)
-        ]
-        return delta
-
-    d = _step_and_assert(None)
-    assert d.resync_reason == ResyncReason.INITIAL
-
-    # Wide SPACER_HEAD wrap + cross-row heal + DCH at col 0 clearing preceding wrapped.
-    term.feed_str("abcde中\r\nLINE_2")
-    d = _step_and_assert(d.token)
-    assert rep_rows_view[0].wrapped is True
-    term.feed_str("\x1b[2;1H\x1b[P")
-    d = _step_and_assert(d.token)
-    assert rep_rows_view[0].wrapped is False
-
-    # Full-screen scroll + large multi-row scroll exceeding viewport height (> 4 rows).
-    term.feed_str("\x1b[4;1H\r\nS1\r\nS2\r\nS3\r\nS4\r\nS5")
-    d = _step_and_assert(d.token)
-    assert d.resync_reason == ResyncReason.NONE
-    assert d.viewport_scroll_up == 5
-
-    # Bounded DECSTBM top=0, bottom=2 (rows=4) pushes to history while pinning row 3.
-    term.feed_str("\x1b[1;3r\x1b[3;1H\nTOP_SC\x1b[r")
-    d = _step_and_assert(d.token)
-    assert d.resync_reason == ResyncReason.NONE
-
-    # ED 3 clears scrollback and subsequent scroll stays incremental.
-    term.feed(b"\x1b[3J\x1b[4;1H\r\nAFTER_CLEAR")
-    d = _step_and_assert(d.token)
-    assert d.history_cleared is True
-
-    # Auxiliary metadata mutations (OSC 7501, remote OSC 7 URI, ESC k) flag changes.
-    term.feed(b"\x1b]7501;state=working:id=build\x07")
-    d = _step_and_assert(d.token)
-    assert d.metadata_changed is True
-
-    term.feed(b"\x1b]7;file://remote-box.example/srv/app\x07")
-    d = _step_and_assert(d.token)
-    assert d.metadata_changed is True
-    assert d.snapshot.cwd == ""
-    assert d.snapshot.cwd_uri == "file://remote-box.example/srv/app"
-
-    term.feed(b"\x1bkmy-window\x1b\\")
-    d = _step_and_assert(d.token)
-    assert d.metadata_changed is True
-
-    # ?2026 synchronized output holds committed view while working view advances.
-    c_tok = term.sync_token(view="committed")
-    term.feed(b"\x1b[?2026h\x1b[1;1HTORN")
-    assert term.changes_since(c_tok, view="committed").has_changes is False
-    assert 0 in term.changes_since(c_tok, view="working").dirty_rows
-    term.feed(b"\x1b[?2026l")
-    d = _step_and_assert(c_tok)
-    assert d.has_changes is True
-
-    # ?1049h / ?1049l bumps epoch; scrolling > scrollback triggers HISTORY_EVICTED.
-    stale_pre_alt = d.token
-    term.feed(b"\x1b[?1049hALT\x1b[?1049l")
-    d = _step_and_assert(stale_pre_alt)
-    assert d.resync_reason == ResyncReason.EPOCH_CHANGED
-
-    stale_same_epoch = d.token
-    f_tok = d.token
-    for idx in range(10):
-        term.feed(f"\r\nEV{idx}".encode("ascii"))
-        f_tok = term.changes_since(f_tok).token
-    assert term.changes_since(stale_same_epoch).resync_reason == (
-        ResyncReason.HISTORY_EVICTED
-    )
-
-
-def test_sixel_and_kitty_graphics_and_snapshot_immutability() -> None:
-    """``SIXEL``/Kitty handle scroll-before-place, limits, and frozen ``Snapshot``."""
-    ihdr_body = struct.pack(">IIBBBBB", 16, 32, 8, 6, 0, 0, 0)
-    ihdr_crc = struct.pack(">I", zlib.crc32(b"IHDR" + ihdr_body) & 0xFFFFFFFF)
-    png_bytes = (
-        b"\x89PNG\r\n\x1a\n" + struct.pack(">I", 13) + b"IHDR" + ihdr_body + ihdr_crc
-    )
-    z_payload = base64.b64encode(zlib.compress(png_bytes))
-    part1, part2 = z_payload[:12], z_payload[12:]
-
-    term = libvt.Terminal(rows=6, cols=10, scrollback=10)
-    term.feed(b"\x1b[2;3H")
-    term.feed(b"\x1b_Ga=T,f=100,o=z,i=7,p=1,z=-5,m=1;" + part1 + b"\x1b\\")
-    assert len(term.placements) == 0
-    term.feed(b"\x1b_Gm=0;" + part2 + b"\x1b\\")
-    assert b"\x1b_Gi=7,p=1;OK\x1b\\" in term.drain_replies()
-
-    assert len(term.placements) == 1
-    kp = term.placements[0]
-    assert kp.protocol == GraphicsProtocol.KITTY
-    assert (kp.row, kp.col, kp.rows, kp.cols) == (1, 2, 2, 2)
-    assert kp.layer == ZLayer.BELOW_TEXT
-    assert (term.cursor.row, term.cursor.col) == (2, 4)
-
-    # Kitty U=0 overlay survives text overwrite; d=y with missing y=0 is a safe no-op.
-    term.feed(b"\x1b[2;3HOVER\x1b[K\x1b_Ga=d,d=y\x1b\\")
-    assert len(term.placements) == 1
-
-    # Retransmitting i=7 replaces stale placements of image 7.
-    raw_1cell = base64.b64encode(b"\xff" * (8 * 16 * 3))
-    term.feed(b"\x1b[1;1H\x1b_Ga=t,f=24,s=8,v=16,i=7;" + raw_1cell + b"\x1b\\")
-    assert len(term.placements) == 0
-    assert b"\x1b_Gi=7;OK\x1b\\" in term.drain_replies()
-
-    # Unnumbered Kitty a=T upload places image silently (zero PTY reply bytes).
-    term.feed(b"\x1b[1;1H\x1b_Ga=T,f=24,s=8,v=16;" + raw_1cell + b"\x1b\\")
-    assert term.drain_replies() == b""
-    assert len(term.placements) == 1
-
-    # Query a=q without i= stays silent; i + I together and truncated payloads fail.
-    term.feed(b"\x1b_Ga=q,f=24,s=1,v=1;" + base64.b64encode(b"abc") + b"\x1b\\")
-    assert term.drain_replies() == b""
-    term.feed(b"\x1b_Ga=t,i=2,I=3,f=24,s=1,v=1;" + base64.b64encode(b"abc") + b"\x1b\\")
-    assert b"EINVAL" in term.drain_replies()
-    term.feed(b"\x1b_Ga=t,i=8,f=24,s=8,v=16;" + base64.b64encode(b"short") + b"\x1b\\")
-    assert b"EINVAL" in term.drain_replies()
-    assert 8 not in term.images
-    comp_trunc = base64.b64encode(zlib.compress(png_bytes)[:-4])
-    term.feed(b"\x1b_Ga=t,i=9,f=100,o=z;" + comp_trunc + b"\x1b\\")
-    assert b"EINVAL" in term.drain_replies()
-    assert 9 not in term.images
-
-    # Reject local filesystem t=f safely in sans-I/O emulator.
-    term.feed(b"\x1b_Ga=T,t=f,i=99;" + base64.b64encode(b"/etc/passwd") + b"\x1b\\")
-    assert 99 not in term.images
-    assert b"EINVAL" in term.drain_replies()
-
-    # Virtual parent + relative child placement + cascade delete.
-    term.feed(b"\x1b_Ga=T,U=1,i=20,p=1,c=2,r=2,f=24,s=8,v=16;" + raw_1cell + b"\x1b\\")
-    # Virtual parent cannot anchor non-virtual relative child; real parent can:
-    term.feed(b"\x1b_Ga=p,i=20,p=2,P=20,Q=1\x1b\\")
-    assert b"ENOPARENT" in term.drain_replies()
-    term.drain_replies()
-    term.feed(b"\x1b[2;2H\x1b_Ga=p,i=20,p=3,c=2,r=2\x1b\\")
-    term.feed(b"\x1b_Ga=p,i=20,p=4,P=20,Q=3,H=2,V=1\x1b\\")
-    term.drain_replies()
-    child_pls = [p for p in term.placements if p.image_id == 20 and p.placement_id == 4]
-    assert len(child_pls) == 1
-    assert (child_pls[0].row, child_pls[0].col) == (2, 3)
-    term.feed(b"\x1b_Ga=d,d=i,i=20,p=3\x1b\\")
-    assert not any(
-        p.image_id == 20 and p.placement_id in (3, 4) for p in term.placements
-    )
-
-    # Bottom-of-alt-screen Kitty & SIXEL scroll-before-place keep full 2-row graphic.
-    alt_t = libvt.Terminal(rows=4, cols=8)
-    raw_2row = base64.b64encode(b"\xaa" * (16 * 32 * 3))
-    alt_t.feed(b"\x1b[?1049h\x1b[4;2H\x1b_Ga=T,f=24,s=16,v=32;" + raw_2row + b"\x1b\\")
-    assert len(alt_t.placements) == 1
-    assert (alt_t.placements[0].row, alt_t.placements[0].rows) == (2, 2)
-
-    sixel_seq = b'\x1bP0;1;0q"1;1;16;32#0!16~-#0!16~-#0!16~-#0!16~-#0!16~\x1b\\'
-    vt_sixel = libvt.Terminal(rows=6, cols=10, profile=Profile.tmux("next-3.9"))
-    vt_sixel.feed(sixel_seq)
-    assert len(vt_sixel.placements) == 1
-    sp = vt_sixel.placements[0]
-    assert sp.protocol == GraphicsProtocol.SIXEL
-    assert (sp.row, sp.col, sp.rows, sp.cols) == (0, 0, 2, 2)
-    assert (vt_sixel.cursor.row, vt_sixel.cursor.col) == (2, 0)
-    vt_sixel.feed(b"\x1b[1;1HX")
-    assert vt_sixel.placements[0].occupies_cell(0, 0) is False
-    assert vt_sixel.placements[0].occupies_cell(0, 1) is True
-
-    tm38_sixel = libvt.Terminal(rows=6, cols=10, profile=Profile.tmux("3.8a"))
-    tm38_sixel.feed(sixel_seq)
-    tm38_sixel.feed(b"\x1b[1;1HX")
-    assert len(tm38_sixel.placements) == 0
-
-    # 10,000px SIXEL stream under DECLRMM finishes in O(rows) without per-row DoS loop.
-    dos_t = libvt.Terminal(rows=24, cols=80, record_events=True)
-    t0 = time.monotonic()
-    for _ in range(20):
-        dos_t.feed(b'\x1b[?69h\x1b[10;20s\x1b[1;1H\x1bPq"1;1;10;10000#0~\x1b\\')
-    assert time.monotonic() - t0 < 0.2
-
-    # Snapshot and KittyCommand.control enforce immutability at runtime.
-    ev_t = libvt.Terminal(rows=4, cols=8, record_events=True)
-    ev_t.feed(b"\x1b_Ga=T,f=24,s=8,v=16,i=5;" + raw_1cell + b"\x1b\\")
-    evs = [e for e in ev_t.drain_events() if isinstance(e, KittyGraphic)]
-    assert len(evs) == 1
-    with pytest.raises(TypeError):
-        evs[0].command.control["a"] = "d"  # type: ignore[index]
-
-    snap = ev_t.snapshot()
-    assert len(snap.to_dict()["placements"]) == 1
-    with pytest.raises(AttributeError):
-        snap.title = "mutated"  # type: ignore[misc]
-    with pytest.raises(TypeError):
-        snap.program_statuses["x"] = None  # type: ignore[index]
-    with pytest.raises(TypeError):
-        snap.images[999] = None  # type: ignore[index]
diff --git a/tests/test_input.py b/tests/test_input.py
new file mode 100644
index 0000000..5914609
--- /dev/null
+++ b/tests/test_input.py
@@ -0,0 +1,67 @@
+"""Tests for ``libvt.input`` mode-aware key, mouse, focus, and paste encoding."""
+
+from __future__ import annotations
+
+import pytest
+
+import libvt
+from libvt.config import Policy
+from libvt.exc import UnsafePasteError
+from libvt.input import (
+    FocusEvent,
+    KeyEvent,
+    KeyMod,
+    KittyKeyboardFlags,
+    MouseAction,
+    MouseButton,
+    MouseEvent,
+    PasteEvent,
+)
+
+
+def test_kitty_keyboard_stack_mouse_sgr_and_focus_encoding() -> None:
+    """``KittyKeyboardStack`` isolates ``CSI u`` from ``SCORC`` and encodes input."""
+    term = libvt.Terminal(rows=4, cols=20)
+    term.feed(b"\x1b[2;4H\x1b[s\x1b[>1u\x1b[1;1H\x1b[u\x1b[?u")
+    assert (term.cursor.row, term.cursor.col) == (1, 3)
+    assert term.kitty_keyboard_flags == KittyKeyboardFlags.DISAMBIGUATE
+    assert term.drain_replies() == b"\x1b[?1u"
+
+    assert term.encode(KeyEvent.parse("escape")) == b"\x1b[27u"
+    assert term.encode(KeyEvent.parse("ctrl+a")) == b"\x1b[97;5u"
+
+    term.feed(b"\x1b[<1u\x1b[?1h")
+    assert term.encode(KeyEvent.parse("up")) == b"\x1bOA"
+
+    term.feed(b"\x1b[?1000;1006;1004h")
+    click = MouseEvent(
+        row=2,
+        col=4,
+        button=MouseButton.LEFT,
+        action=MouseAction.PRESS,
+        modifiers=KeyMod.SHIFT,
+    )
+    assert term.encode(click) == b"\x1b[<4;5;3M"
+    assert term.encode(FocusEvent(focused=True)) == b"\x1b[I"
+
+
+def test_paste_event_fail_closed_and_sanitizer() -> None:
+    r"""``PasteEvent`` blocks nested ``\x1b[201~`` bypasses and unbracketed newlines."""
+    term = libvt.Terminal(rows=4, cols=20)
+    with pytest.raises(UnsafePasteError):
+        term.encode(PasteEvent("ls\nrm -rf /"))
+    assert (
+        term.encode(PasteEvent("line1\nline2", allow_unbracketed_newlines=True))
+        == b"line1\nline2"
+    )
+
+    term.feed(b"\x1b[?2004h")
+    assert term.encode(PasteEvent("hello\nworld")) == b"\x1b[200~hello\nworld\x1b[201~"
+
+    with pytest.raises(UnsafePasteError):
+        term.encode(PasteEvent("safe\x1b[20\x1b[201~1~;evil\n"))
+
+    sanitized = term.encode(PasteEvent("hi\x1b[20\x1b[201~1~", sanitize=True))
+    assert sanitized == b"\x1b[200~hi[20[201~1~\x1b[201~"
+    assert Policy().allow_clipboard_read is False
+    assert Policy().allow_passthrough is False
diff --git a/tests/test_parser.py b/tests/test_parser.py
index e818a1a..2cbf15a 100644
--- a/tests/test_parser.py
+++ b/tests/test_parser.py
@@ -1,4 +1,4 @@
-"""Streaming VT500 parser, SGR subparameter, STRING_ESC, and encoding tests."""
+"""Tests for ``libvt.parser`` VT500 state transitions, SGR, and wire encodings."""
 
 from __future__ import annotations
 
@@ -7,7 +7,7 @@
 import pytest
 
 import libvt
-from libvt.config import Limits
+from libvt.config import Limits, Policy
 from libvt.parser import (
     Action,
     ApcDispatch,
@@ -20,10 +20,11 @@
     Print,
 )
 from libvt.style import AnsiColor, IndexedColor, RgbColor, UnderlineStyle
+from libvt.terminal import StopOn
 
 
 def _coalesce_prints(actions: list[Action]) -> list[Action]:
-    """Merge adjacent ``Print`` actions so arbitrary chunk cuts compare equal."""
+    """Merge adjacent ``Print`` actions so chunk cuts compare equal."""
     merged: list[Action] = []
     for act in actions:
         if isinstance(act, Print) and merged and isinstance(merged[-1], Print):
@@ -33,8 +34,9 @@ def _coalesce_prints(actions: list[Action]) -> list[Action]:
     return merged
 
 
-def test_chunk_cut_invariance_across_byte_steps() -> None:
-    """Arbitrary chunk boundaries yield identical parsed actions and terminal state."""
+@pytest.mark.parametrize("step", [1, 3, 13], ids=["step-1", "step-3", "step-13"])
+def test_chunk_cut_invariance(step: int) -> None:
+    """Arbitrary byte-chunk cuts yield identical actions and terminal state."""
     payload = (
         b"\x1b[?2026h\x1b[1;4:3;38:2::40:180:160;58:5:196m"
         + "Hello 日本 🧑‍🌾 🇯🇵!".encode()
@@ -42,34 +44,30 @@ def test_chunk_cut_invariance_across_byte_steps() -> None:
         + b"\x1b]7501;state=working:progress=42\x1b\\"
         + b"\x1bP1;2+q544e\x1b\\\x1b_Gi=1;AAAA\x1b\\\x1b[?2026l"
     )
-
     ref_actions = _coalesce_prints(Parser().feed(payload))
     ref_term = libvt.Terminal(rows=6, cols=40)
     ref_term.feed(payload)
-    ref_snap = ref_term.snapshot()
-
-    for step in (1, 2, 3, 5, 7, 13, 31):
-        parser = Parser()
-        term = libvt.Terminal(rows=6, cols=40)
-        chunked_actions: list[Action] = []
-        for idx in range(0, len(payload), step):
-            chunk = payload[idx : idx + step]
-            chunked_actions.extend(parser.feed(chunk))
-            term.feed(chunk)
-        assert _coalesce_prints(chunked_actions) == ref_actions
-        assert term.snapshot().text == ref_snap.text
-        assert term.cursor == ref_snap.cursor
-
-
-def test_sgr_colon_subparameters_and_indexed_vs_ansi() -> None:
-    """Colon SGR subparameters, 24-bit RGB, and palette color variants stay distinct."""
+
+    parser = Parser()
+    term = libvt.Terminal(rows=6, cols=40)
+    chunked_actions: list[Action] = []
+    for idx in range(0, len(payload), step):
+        chunk = payload[idx : idx + step]
+        chunked_actions.extend(parser.feed(chunk))
+        term.feed(chunk)
+    assert _coalesce_prints(chunked_actions) == ref_actions
+    assert term.text == ref_term.text
+    assert term.cursor == ref_term.cursor
+
+
+def test_sgr_colon_subparameters_and_palette_variants() -> None:
+    """Colon SGR subparameters, 24-bit RGB, and indexed vs ANSI colors stay distinct."""
     term = libvt.Terminal(rows=4, cols=20)
     term.feed(
         b"\x1b[1;2;4:3;38:2::40:180:160;48;5;1;58:5:196mA\x1b[22;31;24;59mB\x1b[0mC",
     )
     cell_a = term[0, 0]
-    assert cell_a.style.bold is True
-    assert cell_a.style.dim is True
+    assert (cell_a.style.bold, cell_a.style.dim) == (True, True)
     assert cell_a.style.underline == UnderlineStyle.CURLY
     assert cell_a.style.fg == RgbColor(40, 180, 160)
     assert cell_a.style.bg == IndexedColor(1)
@@ -77,45 +75,37 @@ def test_sgr_colon_subparameters_and_indexed_vs_ansi() -> None:
     assert cell_a.style.underline_color == IndexedColor(196)
 
     cell_b = term[0, 1]
-    assert cell_b.style.bold is False
-    assert cell_b.style.dim is False
+    assert (cell_b.style.bold, cell_b.style.dim) == (False, False)
     assert cell_b.style.fg == AnsiColor.RED
     assert cell_b.style.underline == UnderlineStyle.NONE
     assert cell_b.style.underline_color is None
-
-    cell_c = term[0, 2]
-    assert cell_c.style == libvt.Style()
+    assert term[0, 2].style == libvt.Style()
 
 
-def test_utf8_c1_isolation_and_latin1_wire_mode() -> None:
-    """UTF-8 isolates ``0x80..0x9F`` and ``U+009B``; ``latin-1`` parses 8-bit ``C1``."""
+def test_utf8_c1_isolation_latin1_wire_mode_and_incomplete_utf8() -> None:
+    """UTF-8 isolates ``0x80..0x9F``; ``latin-1`` parses ``C1``; C0 flushes UTF-8."""
     title = "Build “日本” Ü 😜"
     assert 0x9C in title.encode("utf-8")
 
     term = libvt.Terminal(rows=4, cols=30)
     term.feed(f"\x1b]2;{title}\x07ok".encode())
-    assert term.title == title
-    assert term.text == "ok"
+    assert (term.title, term.text) == (title, "ok")
 
-    # UTF-8 encoded U+009B (0xC2 0x9B) never smuggles CSI into UTF-8 streams!
     smuggled = Parser(encoding="utf-8").feed(b"\xc2\x9b31mSAFE")
     assert _coalesce_prints(smuggled) == [Print("31mSAFE")]
     assert libvt.strip(b"\xc2\x9b31mSAFE") == "31mSAFE"
 
-    parser = Parser()
-    actions = parser.feed(
+    actions = Parser().feed(
         b"\x1bPq" + title.encode("utf-8") + b"\x1b\\"
         b"\x1b_" + title.encode("utf-8") + b"\x1b\\",
     )
     assert len(actions) == 2
     assert isinstance(actions[0], DcsDispatch)
-    assert actions[0].data == title.encode("utf-8")
     assert isinstance(actions[1], ApcDispatch)
-    assert actions[1].data == title.encode("utf-8")
 
-    # Legacy 8-bit Latin-1 mode handles C1 anywhere transitions and 0xA0..0xFF glyphs.
-    lat_parser = Parser(encoding="latin-1")
-    lat_actions = lat_parser.feed(b"\x1b[12\x9b3;4H\x9d2;caf\xe9\x9c\x8d\xe9")
+    lat_actions = Parser(encoding="latin-1").feed(
+        b"\x1b[12\x9b3;4H\x9d2;caf\xe9\x9c\x8d\xe9",
+    )
     assert lat_actions == [
         CsiDispatch(0, libvt.CsiParams((3, 4), 0, 0), b"", ord("H")),
         OscDispatch(2, b"caf\xe9", b"\x9c"),
@@ -123,30 +113,35 @@ def test_utf8_c1_isolation_and_latin1_wire_mode() -> None:
         Print("é"),
     ]
 
+    lat_term = libvt.Terminal(rows=2, cols=10, encoding="latin-1")
+    step = lat_term.feed_until(
+        b"\x9d2;unterminated\x9b?2026hHI\x9b?2026ltrailing",
+        stop=StopOn.SYNC_END,
+    )
+    assert (step.stopped_on, lat_term[0].text) == (StopOn.SYNC_END, "HI")
+
     with pytest.raises(ValueError, match="unsupported parser encoding"):
         Parser(encoding=t.cast("t.Any", "ebcdic"))
 
-
-def test_incomplete_utf8_flushed_before_c0_control() -> None:
-    """Incomplete UTF-8 bytes emit ``U+FFFD`` before an intervening C0 control runs."""
-    term = libvt.Terminal(rows=4, cols=10)
-    term.feed(b"\xe2\x82\nX")
-    # U+FFFD prints at (0, 0) advancing cursor to col 1; LF moves to (1, 1).
-    assert term[0].text == "\ufffd"
-    assert term[1].text == " X"
+    # Incomplete UTF-8 flushes U+FFFD before an intervening C0 LF executes.
+    c0_term = libvt.Terminal(rows=4, cols=10)
+    c0_term.feed(b"\xe2\x82\nX")
+    assert (c0_term[0].text, c0_term[1].text) == ("\ufffd", " X")
 
 
-def test_string_esc_abort_and_oversized_payload_recovery() -> None:
-    r"""``STRING_ESC`` aborts non-``\`` escapes cleanly and preserves DCS headers."""
+def test_string_esc_abort_dcs_del_bel_and_payload_limits() -> None:
+    r"""``STRING_ESC`` aborts non-``\`` escapes, ``DCS`` ignores ``DEL``, limits cap."""
     p = Parser()
     p.feed(b"\x1b]2;pending\x1b")
     assert p.state == ParserState.STRING_ESC
-    # Non-'\' byte ('c' -> RIS) discards unclosed OSC and dispatches ESC c!
-    acts = p.feed(b"c")
-    assert acts == [EscDispatch(b"", ord("c"))]
+    assert p.feed(b"c") == [EscDispatch(b"", ord("c"))]
     assert p.state == ParserState.GROUND
 
-    # Ubiquitty OSC-G4 on Terminal: unclosed OSC 2 followed by ESC [ 31 m drops title.
+    # DCS ignores 0x7F (DEL) in header while keeping 0x07 (BEL) inside DCS tmux;.
+    pt_term = libvt.Terminal(rows=2, cols=16, policy=Policy(allow_passthrough=True))
+    pt_term.feed(b"\x1bPt\x7fmux;\x1b\x1b]2;ok-title\x07\x1b\\")
+    assert pt_term.title == "ok-title"
+
     term = libvt.Terminal(
         rows=4,
         cols=20,
@@ -154,27 +149,17 @@ def test_string_esc_abort_and_oversized_payload_recovery() -> None:
         record_events=True,
     )
     term.feed(b"\x1b]2;cut\x1b[32mok")
-    assert term.title == ""
-    assert term.text == "ok"
+    assert (term.title, term.text) == ("", "ok")
     assert term[0, 0].style.fg == AnsiColor.GREEN
 
-    # Opt-in abort_dispatch_osc=True commits interrupted OSC payloads on ESC (not CAN).
-    opt_term = libvt.Terminal(
-        rows=4,
-        cols=20,
-        policy=libvt.Policy(abort_dispatch_osc=True),
-    )
+    opt_term = libvt.Terminal(rows=4, cols=20, policy=Policy(abort_dispatch_osc=True))
     opt_term.feed(b"\x1b]2;committed\x1b[31mR\x1b]2;cancelled\x18X")
-    assert opt_term.title == "committed"
-    assert opt_term.text == "RX"
+    assert (opt_term.title, opt_term.text) == ("committed", "RX")
 
-    # Double ESC inside OSC cancels OSC and treats second ESC \ as standalone ST no-op.
     term.reset()
     term.feed(b"\x1b]2;short\x1b\x1b\\after")
-    assert term.title == ""
-    assert term.text == "after"
+    assert (term.title, term.text) == ("", "after")
 
-    # Disabling tmux_passthrough on Parser aborts DCS tmux; on ESC ESC.
     strict_dcs = Parser(tmux_passthrough=False).feed(b"\x1bPtmux;\x1b\x1b\\hi")
     assert _coalesce_prints([a for a in strict_dcs if isinstance(a, Print)]) == [
         Print("hi"),
@@ -184,13 +169,5 @@ def test_string_esc_abort_and_oversized_payload_recovery() -> None:
     term.reset()
     term.drain_events()
     term.feed(b"\x1b]2;" + (b"x" * 64) + b"\x07clean")
-    assert term.title == ""
-    assert term.text == "clean"
-    assert term.parser_state == ParserState.GROUND
+    assert (term.title, term.text) == ("", "clean")
     assert any(isinstance(ev, libvt.UnhandledSequence) for ev in term.drain_events())
-
-    # Exercise SGR memo FIFO eviction past 256 unique entries.
-    for idx in range(300):
-        r = idx & 0xFF
-        term.feed(f"\x1b[38;2;{r};10;20m.".encode("ascii"))
-    assert term[0, 0].text != ""
diff --git a/tests/test_pr2_review_fixes.py b/tests/test_pr2_review_fixes.py
deleted file mode 100644
index 6399c8d..0000000
--- a/tests/test_pr2_review_fixes.py
+++ /dev/null
@@ -1,404 +0,0 @@
-"""Regression tests for PR #2 architectural and terminal-profile review fixes."""
-
-from __future__ import annotations
-
-import asyncio
-import pickle
-
-import pytest
-
-import libvt
-from libvt.aio import AsyncTerminalStream
-from libvt.config import DEFAULT_PROFILE, TMUX_PROFILE, XTERM_PROFILE, Policy, Profile
-from libvt.events import ScreenErased
-from libvt.exc import TerminalTimeoutError
-from libvt.modes import Mode
-from libvt.parser import ParserState
-from libvt.style import AnsiColor
-from libvt.terminal import OutputFormat, StopOn
-
-
-def test_resize_preserves_pending_wrap_and_wide_glyphs() -> None:
-    """``resize()`` preserves ``pending_wrap``, wide cells, and profile reflow rules."""
-    # Case 1a: same-size 4x2 -> 4x2 preserves pending_wrap and scroll_region.
-    same = libvt.Terminal(rows=2, cols=4)
-    same.feed(b"\x1b[1;2rABCD")
-    assert same.cursor.pending_wrap is True
-    same.resize(rows=2, cols=4)
-    assert same.cursor.pending_wrap is True
-    same.feed(b"E")
-    assert same.lines == ("ABCD", "E")
-    assert (same.cursor.row, same.cursor.col) == (1, 1)
-    assert same.cursor.pending_wrap is False
-    assert same[0].wrapped is True
-
-    # Case 1b (DEFAULT_PROFILE reflow=True): widen 4x2 -> 8x2 unwraps pending_wrap.
-    widened = libvt.Terminal(rows=2, cols=4)
-    widened.feed(b"ABCD")
-    widened.resize(rows=2, cols=8)
-    assert widened.cursor.col == 4
-    assert widened.cursor.pending_wrap is False
-    widened.feed(b"E")
-    assert widened.lines == ("ABCDE", "")
-    assert (widened.cursor.row, widened.cursor.col) == (0, 5)
-    assert widened[0].wrapped is False
-
-    # Case 1b (XTERM_PROFILE reflow_on_resize=False): widen keeps col 3 + pending_wrap.
-    xt = libvt.Terminal(rows=2, cols=4, profile=XTERM_PROFILE)
-    xt.feed(b"ABCD")
-    xt.resize(rows=2, cols=8)
-    assert xt.cursor.col == 3
-    assert xt.cursor.pending_wrap is True
-    xt.feed(b"E")
-    assert xt.lines == ("ABCD", "E")
-    assert (xt.cursor.row, xt.cursor.col) == (1, 1)
-    assert xt[0].wrapped is False
-
-    # Wide glyph ending at right margin ('AB界' on 4 cols) reflows cleanly on widen.
-    wide = libvt.Terminal(rows=2, cols=4)
-    wide.feed("AB界".encode())
-    assert wide.cursor.pending_wrap is True
-    wide.resize(rows=2, cols=8)
-    wide.feed(b"E")
-    assert wide.lines == ("AB界E", "")
-    assert (wide.cursor.row, wide.cursor.col) == (0, 5)
-
-    # Exact-fit shrink 8x2 -> 4x2 after 'ABCD' produces no phantom blank row.
-    shrink = libvt.Terminal(rows=2, cols=8, scrollback=10)
-    shrink.feed(b"ABCD")
-    assert (shrink.cursor.row, shrink.cursor.col) == (0, 4)
-    shrink.resize(rows=2, cols=4)
-    assert shrink.history == ()
-    shrink.feed(b"E")
-    assert shrink.lines == ("ABCD", "E")
-    assert (shrink.cursor.row, shrink.cursor.col) == (1, 1)
-
-    # Resizing while inside ?1049h keeps primary saved cursor synchronized on ?1049l.
-    alt_resize = libvt.Terminal(rows=2, cols=4)
-    alt_resize.feed(b"ABCDabc\x1b[?1049h")
-    alt_resize.resize(rows=2, cols=8)
-    alt_resize.feed(b"\x1b[?1049lX")
-    assert alt_resize[0].text == "ABCDabcX"
-
-
-def test_sync_2026_chunk_and_observer_invariance_and_cursor_hold() -> None:
-    """``?2026`` ``committed`` freezes pre-``BSU`` screen/cursor independent of cuts."""
-    payload = b"B\x1b[?2026hC"
-    splits: list[list[bytes]] = [
-        [payload],
-        [bytes([b]) for b in payload],
-        *[[payload[:i], payload[i:]] for i in range(1, len(payload))],
-    ]
-    for observe_before in (False, True):
-        for chunks in splits:
-            term = libvt.Terminal(rows=2, cols=8)
-            term.feed(b"A")
-            if observe_before:
-                assert term.committed[0].text == "A"
-            for chunk in chunks:
-                term.feed(chunk)
-            assert term.synchronized is True
-            held = term.committed
-            assert held[0].text == "AB"
-            assert (held.cursor.row, held.cursor.col) == (0, 2)
-            assert Mode.SYNCHRONIZED_OUTPUT not in held.modes
-
-            live = term.snapshot()
-            assert live[0].text == "ABC"
-            assert (live.cursor.row, live.cursor.col) == (0, 3)
-            assert Mode.SYNCHRONIZED_OUTPUT in live.modes
-
-            term.feed(b"\x1b[?2026l")
-            after = term.committed
-            assert after[0].text == "ABC"
-            assert (after.cursor.row, after.cursor.col) == (0, 3)
-
-    # Scalar cursor/visibility/title hold at BSU while CPR & DECRQM report live state.
-    term2 = libvt.Terminal(rows=3, cols=10)
-    term2.feed(b"A")
-    term2.feed(b"\x1b[?2026h\x1b[2;3H\x1b[?25l\x1b]2;Next\x07\x1b[6n\x1b[?2026$p")
-    held2 = term2.committed
-    assert (held2.cursor.row, held2.cursor.col) == (0, 1)
-    assert held2.cursor.visible is True
-    assert held2.title == ""
-    assert term2.drain_replies() == b"\x1b[2;3R\x1b[?2026;1$y"
-
-    term2.feed(b"\x1b[?2026l")
-    done2 = term2.committed
-    assert (done2.cursor.row, done2.cursor.col) == (1, 2)
-    assert done2.cursor.visible is False
-    assert done2.title == "Next"
-
-
-def test_ed3_preserves_viewport_and_pending_wrap_and_profile_alt() -> None:
-    """``CSI 3 J`` clears history without wiping viewport cells or ``pending_wrap``."""
-    term = libvt.Terminal(rows=2, cols=4, scrollback=10, record_events=True)
-    term.feed(b"old\r\nnew\r\nABCD")
-    assert [r.text for r in term.history] == ["old"]
-    assert term.lines == ("new", "ABCD")
-    assert term.cursor.pending_wrap is True
-    term.drain_events()
-
-    term.feed(b"\x1b[3J")
-    assert term.history == ()
-    assert term.lines == ("new", "ABCD")
-    assert term.cursor.pending_wrap is True
-    assert [e for e in term.drain_events() if isinstance(e, ScreenErased)] == []
-
-    # DECSED 3 and out-of-range ED 99 are complete no-ops.
-    term.feed(b"\x1b[?3J\x1b[99J")
-    assert term.lines == ("new", "ABCD")
-    assert term.cursor.pending_wrap is True
-
-    term.feed(b"E")
-    assert term.lines == ("ABCD", "E")
-    assert [r.text for r in term.history] == ["new"]
-
-    # Alternate-screen ED 3 respects profile.ed3_clears_scrollback_on_alt.
-    def_term = libvt.Terminal(rows=2, cols=6, scrollback=10, profile=DEFAULT_PROFILE)
-    def_term.feed(b"hist1\r\nhist2\r\nvis\x1b[?1049hALT\x1b[3J")
-    assert def_term[0].text == "ALT"
-    assert [r.text for r in def_term.history] == ["hist1"]
-
-    for prof in (XTERM_PROFILE, TMUX_PROFILE):
-        p_term = libvt.Terminal(rows=2, cols=6, scrollback=10, profile=prof)
-        p_term.feed(b"hist1\r\nhist2\r\nvis\x1b[?1049hALT\x1b[3J")
-        assert p_term[0].text == "ALT"
-        assert p_term.history == ()
-
-
-def test_hpr_vpr_margins_decom_and_tmux_ignore() -> None:
-    """``HPR`` and ``VPR`` honor ``DECOM`` margins and ``TMUX_PROFILE`` ignore."""
-    term = libvt.Terminal(rows=4, cols=8)
-    term.feed(b"A\x1b[2aB\x1b[1eC")
-    assert term[0].text == "A  B"
-    assert term[1].text == "    C"
-
-    # HPR clears pending_wrap.
-    wrap_t = libvt.Terminal(rows=2, cols=4)
-    wrap_t.feed(b"ABCD\x1b[1aE")
-    assert wrap_t.lines == ("ABCE", "")
-
-    # DECOM off (?6l): HPR/VPR cross DECLRMM and DECSTBM margins to screen edges.
-    margin_t = libvt.Terminal(rows=4, cols=8)
-    margin_t.feed(b"\x1b[?69h\x1b[2;3r\x1b[3;6s\x1b[2;3H\x1b[10a\x1b[10e")
-    assert (margin_t.cursor.row, margin_t.cursor.col) == (3, 7)
-
-    # DECOM on (?6h): HPR/VPR clamp to active margins without double-adding origin.
-    margin_t.feed(b"\x1b[?6h\x1b[1a\x1b[1e")
-    assert (margin_t.cursor.row, margin_t.cursor.col) == (2, 3)
-    margin_t.feed(b"\x1b[99a\x1b[99e")
-    assert (margin_t.cursor.row, margin_t.cursor.col) == (2, 5)
-
-    # TMUX_PROFILE ignores HPR/VPR quietly even under Policy(strict=True).
-    tm = libvt.Terminal(
-        rows=2, cols=8, profile=TMUX_PROFILE, policy=Policy(strict=True)
-    )
-    tm.feed(b"A\x1b[3aB\x1b[2eC")
-    assert tm[0].text == "ABC"
-
-    spans = libvt.explain(b"\x1b[3a\x1b[2e")
-    assert [s.mnemonic for s in spans] == ["HPR", "VPR"]
-
-
-def test_decslrm_scroll_clear_range_rep_decaln_and_vs16_clamp() -> None:
-    """``DECSLRM`` scroll, ``ECH``, ``REP``, ``DECALN``, and ``?7l`` ``VS16`` hold."""
-    # DECSLRM scroll_up updates text_used bidirectionally.
-    scr_t = libvt.Terminal(rows=2, cols=6)
-    scr_t.feed(b"AB\x1b[?69h\x1b[1;2s\x1b[1;1H\x1b[S")
-    assert scr_t[0].text == ""
-
-    scr_t2 = libvt.Terminal(rows=2, cols=6)
-    scr_t2.feed(b"\r\nCD\x1b[?69h\x1b[1;2s\x1b[1;1H\x1b[S")
-    assert scr_t2[0].text == "CD"
-
-    scr_t3 = libvt.Terminal(rows=2, cols=6)
-    scr_t3.feed(b"AB\x1b[?69h\x1b[1;2s\x1b[1;1H\x1b[T")
-    assert scr_t3[1].text == "AB"
-
-    # Partial ECH trims text_used when erasing to the end of written text.
-    ech_t = libvt.Terminal(rows=2, cols=10)
-    ech_t.feed(b"ABCD\x1b[3G\x1b[2X")
-    assert ech_t[0].text == "AB"
-
-    # _Row.freeze() does not inflate FrozenRow.used to full screen width.
-    fr_t = libvt.Terminal(rows=2, cols=80, scrollback=5)
-    fr_t.feed(b"\x1b[31mA\x1b[0m\r\nB\r\nC")
-    assert fr_t._screens.primary._history[0].used == 1
-
-    # Non-print sequences clear REP _last_printed state.
-    rep_t = libvt.Terminal(rows=2, cols=10)
-    rep_t.feed(b"A\x1b[C\x1b[3b")
-    assert rep_t[0].text == "A"
-    rep_t.reset()
-    rep_t.feed(b"A\r\x1b[3b")
-    assert rep_t[0].text == "A"
-
-    # DECALN resets margins and wrapped flags before filling 'E'.
-    aln_t = libvt.Terminal(rows=2, cols=4)
-    aln_t.feed(b"ABCDEF\x1b[?69h\x1b[2;3s\x1b#8")
-    assert aln_t.lines == ("EEEE", "EEEE")
-    assert aln_t[0].wrapped is False
-    assert aln_t.screen.scroll_region == libvt.ScrollRegion(0, 1, 0, 3)
-
-    # ?7l right-margin VS16 keeps display_width <= cols without 2-col overflow.
-    vs_t = libvt.Terminal(rows=2, cols=4)
-    vs_t.feed("\x1b[?7lABC\u26a0\ufe0f".encode())
-    assert libvt.display_width(vs_t[0].text) <= 4
-    assert vs_t[0, 3].width == 1
-
-
-async def test_formatter_vt_bce_roundtrip_html_palette_and_timeout_diagnostics() -> (
-    None
-):
-    """``Formatter`` preserves BCE/HTML styles and timeout diagnostics."""
-    # VT formatter preserves both right-trimmed text AND trailing BCE background!
-    bce_t = libvt.Terminal(rows=2, cols=10)
-    bce_t.feed(b"\x1b[42mHI\x1b[K")
-    snap = bce_t.snapshot()
-    assert snap[0].text == "HI"
-    assert snap[0, 9].style.bg == AnsiColor.GREEN
-
-    vt_str = snap.format(OutputFormat.VT)
-    rt = libvt.Terminal(rows=2, cols=10)
-    rt.feed_str(vt_str)
-    assert rt[0].text == "HI"
-    assert rt[0, 9].style.bg == AnsiColor.GREEN
-
-    # HTML formatter renders ANSI/indexed colors, reverse video, and wavy lines.
-    html_t = libvt.Terminal(rows=2, cols=16)
-    html_t.feed(b"\x1b[31;48;5;208;4:3;9;53mWARN\x1b[0;7mREV\x1b[0m")
-    rendered_html = html_t.snapshot().format(OutputFormat.HTML)
-    assert "color:rgb(" in rendered_html
-    assert "background-color:rgb(255,135,0)" in rendered_html
-    assert "text-decoration-style:wavy" in rendered_html
-    assert "underline" in rendered_html and "overline" in rendered_html
-
-    # TerminalTimeoutError preserves single-arg OSError str/errno and pickles cleanly.
-    manual = TerminalTimeoutError(
-        "timed out",
-        parser_state=ParserState.OSC_STRING,
-        screen_text="hello",
-        recent_bytes=b"\x1b]0;stuck",
-        eof=False,
-    )
-    assert isinstance(manual, TimeoutError)
-    assert manual.errno is None
-    assert str(manual) == "timed out"
-    unpickled = pickle.loads(pickle.dumps(manual))
-    assert str(unpickled) == "timed out"
-    assert unpickled.parser_state == ParserState.OSC_STRING
-    assert unpickled.recent_bytes == b"\x1b]0;stuck"
-
-    # AsyncTerminalStream attaches FlightRecorder and populates timeout fields.
-    reader = asyncio.StreamReader()
-    stream = AsyncTerminalStream(reader, rows=2, cols=10)
-    reader.feed_data(b"hello\x1b]0;stuck")
-    with pytest.raises(TerminalTimeoutError) as exc_info:
-        await stream.wait_for("missing", timeout=0.05)
-    err = exc_info.value
-    assert err.parser_state == ParserState.OSC_STRING
-    assert b"\x1b]0;stuck" in err.recent_bytes
-    assert "\n" not in str(err)
-    assert "Flight Recorder:" in err.format_diagnostics()
-    assert any("Flight Recorder:" in note for note in err.__notes__)
-
-
-def test_tmux_phantom_column_il_dl_and_version_factory() -> None:
-    """``TMUX_PROFILE`` models phantom col ``cols``, ``IL``/``DL``, and versions."""
-    # Reverse-video header + EL 0 at phantom column preserves col 4 glyph and style!
-    tm = libvt.Terminal(rows=3, cols=5, profile=TMUX_PROFILE)
-    tm.feed(b"\x1b[7mHEAD!\x1b[K\x1b[0m")
-    assert tm[0].text == "HEAD!"
-    assert tm[0, 4].style.reverse is True
-    assert tm.cursor.pending_wrap is True
-
-    # ED 0 at phantom column keeps current row, clears below, and keeps pending_wrap.
-    tm.reset()
-    tm.feed(b"12345\r\nrow-2\x1b[1;1H12345\x1b[J")
-    assert tm.lines == ("12345", "", "")
-    assert tm.cursor.pending_wrap is True
-
-    # ECH, ICH, DCH at phantom column are no-ops keeping pending_wrap.
-    for seq in (b"\x1b[X", b"\x1b[@", b"\x1b[P"):
-        tm.reset()
-        tm.feed(b"12345" + seq)
-        assert tm[0].text == "12345"
-        assert tm.cursor.pending_wrap is True
-
-    # LF (LNM off), IND, RI, and VPA preserve pending_wrap under TMUX_PROFILE.
-    tm.reset()
-    tm.feed(b"12345\nX")
-    assert tm.lines == ("12345", "", "X")
-
-    tm.reset()
-    tm.feed(b"\x1b[2;1H12345\x1bMX")
-    assert tm.lines == ("", "X2345", "")
-
-    tm.reset()
-    tm.feed(b"12345\x1b[2dX")
-    assert tm.lines == ("12345", "", "X")
-
-    # DECRC drops pending_wrap under TMUX_PROFILE, clamping to cols - 1.
-    tm.reset()
-    tm.feed(b"12345\x1b7\x1b8X")
-    assert tm[0].text == "1234X"
-
-    # CPR (CSI 6 n) reports cols + 1 at phantom column under TMUX_PROFILE.
-    tm.reset()
-    tm.feed(b"12345\x1b[6n")
-    assert tm.drain_replies() == b"\x1b[1;6R"
-
-    # IL and DL preserve cursor column under TMUX_PROFILE (unlike DEFAULT_PROFILE).
-    tm.reset()
-    tm.feed(b"abcde\r\n12345\x1b[2;4H\x1b[L")
-    assert tm.cursor.col == 3
-    tm.feed(b"\x1b[M")
-    assert tm.cursor.col == 3
-
-    # Profile.tmux("3.8a") vs Profile.tmux("3.9") versioned quirks.
-    tm38 = libvt.Terminal(rows=2, cols=5, profile=Profile.tmux("3.8a"))
-    tm38.feed(b"1234X\x1b[2b")
-    assert tm38.lines == ("1234X", "")
-
-    tm39 = libvt.Terminal(rows=2, cols=5, profile=Profile.tmux("3.9"))
-    tm39.feed(b"1234X\x1b[2b")
-    assert tm39.lines == ("1234X", "XX")
-
-
-def test_parser_c_regex_dcs_del_bel_latin1_feed_until_and_narrow_bmp() -> None:
-    """Parser C-regex scans, ``latin-1`` ``feed_until``, and narrow BMP match."""
-    # DCS ignores 0x7F (DEL) while preserving 0x07 (BEL) inside DCS tmux; passthrough.
-    term = libvt.Terminal(
-        rows=2,
-        cols=16,
-        policy=Policy(allow_passthrough=True),
-    )
-    term.feed(b"\x1bPt\x7fmux;\x1b\x1b]2;ok-title\x07\x1b\\")
-    assert term.title == "ok-title"
-
-    # encoding='latin-1' feed_until handles 8-bit C1 0x9B aborting OSC_STRING!
-    lat_t = libvt.Terminal(rows=2, cols=10, encoding="latin-1")
-    step = lat_t.feed_until(
-        b"\x9d2;unterminated\x9b?2026hHI\x9b?2026ltrailing",
-        stop=StopOn.SYNC_END,
-    )
-    assert step.stopped_on == StopOn.SYNC_END
-    assert lat_t[0].text == "HI"
-
-    # Spacing GCB_PREPEND (U+0600) split across feed() before ASCII '1' matches atomic.
-    whole = libvt.Terminal(rows=2, cols=8)
-    whole.feed("\u06001".encode())
-    split = libvt.Terminal(rows=2, cols=8)
-    split.feed("\u0600".encode())
-    split.feed(b"1")
-    assert split[0, 0].text == whole[0, 0].text
-    assert split.cursor == whole.cursor
-
-    # Curated narrow-BMP slice fast path preserves widths, wraps, styles, and REP.
-    bmp = libvt.Terminal(rows=3, cols=8)
-    bmp.feed("\x1b[32mcafé\x1b[2b ─│┌┐".encode())
-    assert bmp[0].text == "cafééé ─"
-    assert bmp[0].wrapped is True
-    assert bmp[1].text == "│┌┐"
-    assert bmp[0, 3].style.fg == AnsiColor.GREEN
diff --git a/tests/test_protocols_and_input.py b/tests/test_protocols_and_input.py
deleted file mode 100644
index 78c49fc..0000000
--- a/tests/test_protocols_and_input.py
+++ /dev/null
@@ -1,252 +0,0 @@
-"""Rex OSC 7501, OSC 133/7/52, queries, tmux passthrough, and input encoding tests."""
-
-from __future__ import annotations
-
-import base64
-
-import pytest
-
-import libvt
-from libvt.config import Policy, Profile
-from libvt.events import (
-    ClipboardWrite,
-    ColorSchemeQueried,
-    Passthrough,
-    ProgramStatusChanged,
-    WorkingDirectoryChanged,
-)
-from libvt.exc import UnsafePasteError
-from libvt.input import (
-    FocusEvent,
-    KeyEvent,
-    KeyMod,
-    KittyKeyboardFlags,
-    MouseAction,
-    MouseButton,
-    MouseEvent,
-    PasteEvent,
-)
-from libvt.status import BlockKind, StatusState
-
-
-def test_osc_7501_rex_grammar_hierarchy_urgency_and_queries() -> None:
-    """Rex ``OSC 7501`` enforces grammar, hierarchy, urgency, and pruning."""
-    pull_term = libvt.Terminal(rows=4, cols=30, record_events=False)
-    pull_term.feed(b"\x1b]7501;?\x07")
-    pull_reply = pull_term.drain_replies()
-    assert pull_reply.startswith(b"\x1b]7501;?:")
-    assert pull_reply.endswith(b"\x07")
-
-    suppressed = libvt.Terminal(
-        rows=4,
-        cols=30,
-        policy=Policy(allow_program_status_query=False),
-        record_events=True,
-    )
-    suppressed.feed(b"\x1b]7501;?\x07")
-    assert suppressed.drain_replies() == b""
-
-    term = libvt.Terminal(rows=6, cols=40, record_events=True)
-    term.feed(b"\x1b]7501;?\x07")
-    assert term.drain_replies() == pull_reply
-    term.feed(b"\x1b]7501;?\x1b\\")
-    reply_st = term.drain_replies()
-    assert reply_st.startswith(b"\x1b]7501;?:")
-    assert reply_st.endswith(b"\x1b\\")
-
-    term.feed(b"\x1b]9;4;1;35\x07")
-    assert term.program_status is not None
-    assert term.program_status.state == StatusState.WORKING
-    assert term.program_status.progress == 35
-
-    b64_title = base64.b64encode("Compiling 日本".encode()).decode("ascii")
-    term.feed(
-        f"\x1b]7501;state=working:id=build:app=cargo:progress=50:title={b64_title}\x1b\\".encode(),
-    )
-    term.feed(b"\x1b]7501;state=blocked:id=build/sign:kind=auth\x1b\\")
-    term.feed(b"\x1b]9;4;0\x07")
-
-    child = term.program_statuses["build/sign"]
-    assert child.effective_app == "cargo"
-    assert child.kind == BlockKind.AUTH
-    assert term.program_statuses["build"].title == "Compiling 日本"
-    assert term.program_status == child
-
-    spoof_b64 = base64.b64encode("ok\u202eevil".encode()).decode("ascii")
-    term.feed(f"\x1b]7501;state=error:id=spoof:title={spoof_b64}\x1b\\".encode())
-    assert "spoof" not in term.program_statuses
-
-    term.feed(b"\x1b]7501;state=working\x1b\\")
-    assert "" in term.program_statuses
-    term.feed(b"\x1b]133;A;k=s\x07")
-    assert "" in term.program_statuses
-    term.feed(b"\x1b]133;A\x07")
-    assert "" not in term.program_statuses
-
-    term.feed(b"\x1b]7501;state=done:id=lint\x1b\\")
-    term.notify_process_exit()
-    assert "lint" in term.program_statuses
-    assert "build" not in term.program_statuses
-    assert "build/sign" not in term.program_statuses
-
-    term.feed(b"\x1b]7501;state=working:id=tree\x1b\\")
-    term.feed(b"\x1b]7501;state=working:id=tree/leaf\x1b\\")
-    term.feed(b"\x1b]7501;state=clear:id=tree\x1b\\")
-    assert "tree" not in term.program_statuses
-    assert "tree/leaf" not in term.program_statuses
-    assert any(isinstance(e, ProgramStatusChanged) for e in term.drain_events())
-
-
-def test_osc_133_abs_row_osc_7_osc_52_and_tmux_passthrough() -> None:
-    """``OSC 133`` ``abs_row``, ``OSC 7`` ``cwd_uri``, and ``Passthrough`` policy."""
-    term = libvt.Terminal(
-        rows=3,
-        cols=20,
-        scrollback=20,
-        profile=Profile(color_scheme=libvt.ColorScheme.LIGHT),
-        record_events=True,
-    )
-    for idx in range(5):
-        seq = (
-            f"\x1b]133;A\x07$ \x1b]133;B\x07cmd{idx}\r\n"
-            f"\x1b]133;C\x07out\r\n\x1b]133;D;0\x07"
-        )
-        term.feed(seq.encode())
-    zones = term.prompt_zones
-    assert len(zones) >= 4
-    assert [z.abs_row for z in zones] == sorted(z.abs_row for z in zones)
-    assert zones[-1].exit_code == 0
-
-    # OSC 7: localhost updates cwd & cwd_uri; remote / non-file / NUL clears cwd!
-    term.feed(b"\x1b]7;file://localhost/tmp/my%20dir\x07")
-    assert term.cwd == "/tmp/my dir"
-    assert term.cwd_uri == "file://localhost/tmp/my%20dir"
-    term.feed(b"\x1b]7;file://remote-box.example/srv\x07")
-    assert term.cwd == ""
-    assert term.cwd_uri == "file://remote-box.example/srv"
-    assert term.snapshot().cwd_uri == "file://remote-box.example/srv"
-    term.feed(b"\x1b]7;kitty-shell-cwd://localhost/srv\x07")
-    assert term.cwd == ""
-    assert term.cwd_uri == "kitty-shell-cwd://localhost/srv"
-    term.feed(b"\x1b]7;file://localhost/bad%00path\x07")
-    assert term.cwd == ""
-
-    # Empty OSC 7 clears both cwd and cwd_uri.
-    term.feed(b"\x1b]7;\x07")
-    assert term.cwd == ""
-    assert term.cwd_uri == ""
-
-    clip_b64 = base64.b64encode(b"copied").decode("ascii")
-    term.feed(f"\x1b]52;c;{clip_b64}\x07\x1b]52;c;?\x07".encode("ascii"))
-    assert term.drain_replies() == b""
-    events = term.drain_events()
-    assert (
-        WorkingDirectoryChanged(uri="file://remote-box.example/srv", path="/srv")
-        in events
-    )
-    assert ClipboardWrite(selection="c", text="copied") in events
-
-    term.feed(
-        b"\x1b[>q\x1bP$qm\x1b\\\x1bP+q544e\x1b\\\x1b]10;?\x07\x1b[?2031h\x1b[?996n",
-    )
-    replies = term.drain_replies()
-    assert b"\x1bP>|libvt" in replies
-    assert b"\x1bP1$r" in replies
-    assert b"\x1bP1+r544e=" in replies
-    assert b"\x1b]10;rgb:" in replies
-    assert b"\x1b[?997;2n" in replies
-    assert ColorSchemeQueried(scheme=libvt.ColorScheme.LIGHT) in term.drain_events()
-
-    # Default Policy(allow_passthrough=False) emits Passthrough without re-feeding.
-    term.feed(b"\x1bPtmux;\x1b\x1b]2;spoofed-title\x07\x1b\\")
-    assert term.title == ""
-    assert term.drain_events() == (Passthrough(data=b"\x1b]2;spoofed-title\x07"),)
-
-    # Policy(allow_passthrough=True) emits Passthrough and evaluates nested payloads.
-    allow_term = libvt.Terminal(
-        rows=3,
-        cols=20,
-        policy=Policy(allow_passthrough=True),
-        record_events=True,
-    )
-    allow_term.feed(b"\x1bPtmux;\x1b\x1b]2;bel-title\x07\x1b\\")
-    assert allow_term.title == "bel-title"
-    allow_term.feed(b"\x1bPtmux;\x1b\x1b]7501;state=done:id=inner\x1b\x1b\\\x1b\\")
-    assert "inner" in allow_term.program_statuses
-    allow_term.feed(
-        b"\x1bPtmux;\x1b\x1bPtmux;"
-        b"\x1b\x1b\x1b\x1b]7501;state=done:id=nested2\x1b\x1b\x1b\x1b\\"
-        b"\x1b\x1b\\\x1b\\",
-    )
-    assert "nested2" in allow_term.program_statuses
-    # Split DCS tmux; envelopes preserve inner parser state across packets!
-    allow_term.feed(b"\x1bPtmux;\x1b\x1b]2;hel\x1b\\" + b"\x1bPtmux;lo\x07\x1b\\")
-    assert allow_term.title == "hello"
-    assert allow_term.text == ""
-
-    # TMUX_PROFILE consumes ESC k  ESC \ without printing to cells, and
-    # OSC 10/11 + OSC 110/111 dynamic color overrides/resets work cleanly.
-    tmux_term = libvt.Terminal(
-        rows=3,
-        cols=20,
-        profile=libvt.TMUX_PROFILE,
-        policy=Policy(strict=True),
-    )
-    tmux_term.feed(b"\x1bkbuild-win\x1b\\OK\x1b]10;rgb:11/22/33\x1b\\\x1b]110\x1b\\")
-    assert tmux_term.text == "OK"
-    assert tmux_term.window_name == "build-win"
-    assert libvt.render(b"line1\nline2", rows=2, cols=10, newline_mode=True) == (
-        "line1\nline2"
-    )
-    assert libvt.DEFAULT_LIMITS.max_dcs_bytes > libvt.DEFAULT_LIMITS.max_apc_bytes
-    assert libvt.DEFAULT_LIMITS.max_status_records == 256
-
-
-def test_kitty_keyboard_stack_and_input_encoding() -> None:
-    """``KittyKeyboardStack`` isolates ``CSI u`` from ``SCORC`` and encodes input."""
-    term = libvt.Terminal(rows=4, cols=20)
-    term.feed(b"\x1b[2;4H\x1b[s\x1b[>1u\x1b[1;1H\x1b[u\x1b[?u")
-    assert term.cursor.row == 1
-    assert term.cursor.col == 3
-    assert term.kitty_keyboard_flags == KittyKeyboardFlags.DISAMBIGUATE
-    assert term.drain_replies() == b"\x1b[?1u"
-
-    assert term.encode(KeyEvent.parse("escape")) == b"\x1b[27u"
-    assert term.encode(KeyEvent.parse("ctrl+a")) == b"\x1b[97;5u"
-
-    term.feed(b"\x1b[<1u\x1b[?1h")
-    assert term.encode(KeyEvent.parse("up")) == b"\x1bOA"
-
-    term.feed(b"\x1b[?1000;1006;1004h")
-    click = MouseEvent(
-        row=2,
-        col=4,
-        button=MouseButton.LEFT,
-        action=MouseAction.PRESS,
-        modifiers=KeyMod.SHIFT,
-    )
-    assert term.encode(click) == b"\x1b[<4;5;3M"
-    assert term.encode(FocusEvent(focused=True)) == b"\x1b[I"
-
-
-def test_paste_event_fail_closed_and_character_sanitize() -> None:
-    r"""``PasteEvent`` blocks nested ``\x1b[201~`` bypasses and unbracketed newlines."""
-    term = libvt.Terminal(rows=4, cols=20)
-    with pytest.raises(UnsafePasteError):
-        term.encode(PasteEvent("ls\nrm -rf /"))
-    assert (
-        term.encode(PasteEvent("line1\nline2", allow_unbracketed_newlines=True))
-        == b"line1\nline2"
-    )
-
-    term.feed(b"\x1b[?2004h")
-    assert term.encode(PasteEvent("hello\nworld")) == b"\x1b[200~hello\nworld\x1b[201~"
-
-    with pytest.raises(UnsafePasteError):
-        term.encode(PasteEvent("safe\x1b[20\x1b[201~1~;evil\n"))
-
-    sanitized = term.encode(PasteEvent("hi\x1b[20\x1b[201~1~", sanitize=True))
-    assert sanitized == b"\x1b[200~hi[20[201~1~\x1b[201~"
-
-    assert Policy().allow_clipboard_read is False
-    assert Policy().allow_passthrough is False
diff --git a/tests/test_screen.py b/tests/test_screen.py
new file mode 100644
index 0000000..efd0c76
--- /dev/null
+++ b/tests/test_screen.py
@@ -0,0 +1,294 @@
+"""Tests for ``libvt._grid`` and ``libvt.screen`` rows, healing, reflow, and fuzz."""
+
+from __future__ import annotations
+
+import random
+import typing as t
+
+import pytest
+
+import libvt
+from libvt._ucd import WidthRole
+from libvt.config import DEFAULT_PROFILE, XTERM_PROFILE, Profile
+from libvt.events import InBandResize
+from libvt.modes import Mode
+
+
+def _assert_grid_invariants(term: libvt.Terminal) -> None:
+    """Assert cursor bounds and wide-cell head/tail/spacer_head invariants."""
+    scr = term.screen
+    declrmm = term.modes.is_set(Mode.DECLRMM)
+    assert 0 <= scr.cursor.row < scr.rows
+    assert 0 <= scr.cursor.col < scr.cols
+    for r_idx, raw_row in enumerate(scr._rows):
+        assert len(raw_row.chars) == scr.cols
+        assert 0 <= raw_row.used <= scr.cols
+        if raw_row.attrs is None:
+            continue
+        for c_idx in range(scr.cols):
+            role = WidthRole((raw_row.attrs[c_idx] >> 60) & 0b11)
+            if role == WidthRole.WIDE:
+                assert c_idx + 1 < scr.cols, f"orphan WIDE at ({r_idx}, {c_idx})"
+                tail_role = WidthRole((raw_row.attrs[c_idx + 1] >> 60) & 0b11)
+                assert tail_role == WidthRole.SPACER_TAIL
+            elif role == WidthRole.SPACER_TAIL:
+                assert c_idx > 0, f"orphan SPACER_TAIL at ({r_idx}, 0)"
+                head_role = WidthRole((raw_row.attrs[c_idx - 1] >> 60) & 0b11)
+                assert head_role == WidthRole.WIDE
+            elif (
+                role == WidthRole.SPACER_HEAD
+                and not declrmm
+                and c_idx == scr.cols - 1
+                and r_idx + 1 < scr.rows
+                and raw_row.wrapped
+            ):
+                next_row = scr._rows[r_idx + 1]
+                next_role = (
+                    WidthRole((next_row.attrs[0] >> 60) & 0b11)
+                    if next_row.attrs is not None
+                    else WidthRole.NARROW
+                )
+                assert next_role == WidthRole.WIDE
+
+
+class ResizeCase(t.NamedTuple):
+    """Typed scenario for ``Terminal.resize()`` reflow and ``pending_wrap`` rules."""
+
+    test_id: str
+    init_rows: int
+    init_cols: int
+    profile: Profile
+    pre_feed: bytes
+    new_rows: int
+    new_cols: int
+    post_feed: bytes
+    expected_lines: tuple[str, ...]
+    expected_cursor: tuple[int, int, bool]
+
+
+RESIZE_CASES: list[ResizeCase] = [
+    ResizeCase(
+        test_id="same-size-preserves-pending-wrap",
+        init_rows=2,
+        init_cols=4,
+        profile=DEFAULT_PROFILE,
+        pre_feed=b"\x1b[1;2rABCD",
+        new_rows=2,
+        new_cols=4,
+        post_feed=b"E",
+        expected_lines=("ABCD", "E"),
+        expected_cursor=(1, 1, False),
+    ),
+    ResizeCase(
+        test_id="reflow-widen-unwraps-pending-wrap",
+        init_rows=2,
+        init_cols=4,
+        profile=DEFAULT_PROFILE,
+        pre_feed=b"ABCD",
+        new_rows=2,
+        new_cols=8,
+        post_feed=b"E",
+        expected_lines=("ABCDE", ""),
+        expected_cursor=(0, 5, False),
+    ),
+    ResizeCase(
+        test_id="xterm-no-reflow-widen-retains-pending-wrap",
+        init_rows=2,
+        init_cols=4,
+        profile=XTERM_PROFILE,
+        pre_feed=b"ABCD",
+        new_rows=2,
+        new_cols=8,
+        post_feed=b"E",
+        expected_lines=("ABCD", "E"),
+        expected_cursor=(1, 1, False),
+    ),
+    ResizeCase(
+        test_id="reflow-widen-wide-glyph-at-right-margin",
+        init_rows=2,
+        init_cols=4,
+        profile=DEFAULT_PROFILE,
+        pre_feed="AB界".encode(),
+        new_rows=2,
+        new_cols=8,
+        post_feed=b"E",
+        expected_lines=("AB界E", ""),
+        expected_cursor=(0, 5, False),
+    ),
+    ResizeCase(
+        test_id="exact-fit-shrink-no-phantom-blank-row",
+        init_rows=2,
+        init_cols=8,
+        profile=DEFAULT_PROFILE,
+        pre_feed=b"ABCD",
+        new_rows=2,
+        new_cols=4,
+        post_feed=b"E",
+        expected_lines=("ABCD", "E"),
+        expected_cursor=(1, 1, False),
+    ),
+    ResizeCase(
+        test_id="alt-screen-resize-syncs-saved-primary-cursor",
+        init_rows=2,
+        init_cols=4,
+        profile=DEFAULT_PROFILE,
+        pre_feed=b"ABCDabc\x1b[?1049h",
+        new_rows=2,
+        new_cols=8,
+        post_feed=b"\x1b[?1049lX",
+        expected_lines=("ABCDabcX", ""),
+        expected_cursor=(0, 8 - 1, True),
+    ),
+]
+
+
+@pytest.mark.parametrize(
+    "case",
+    RESIZE_CASES,
+    ids=[c.test_id for c in RESIZE_CASES],
+)
+def test_resize_pending_wrap_and_reflow_cases(case: ResizeCase) -> None:
+    """``resize()`` preserves ``pending_wrap``, wide cells, and profile reflow."""
+    term = libvt.Terminal(
+        rows=case.init_rows,
+        cols=case.init_cols,
+        scrollback=10,
+        profile=case.profile,
+    )
+    term.feed(case.pre_feed)
+    term.resize(rows=case.new_rows, cols=case.new_cols)
+    term.feed(case.post_feed)
+    assert term.lines == case.expected_lines
+    assert (
+        term.cursor.row,
+        term.cursor.col,
+        term.cursor.pending_wrap,
+    ) == case.expected_cursor
+
+
+def test_resize_soft_wrap_join_alt_crop_and_inband_2048() -> None:
+    """Primary soft wraps join on widen, alt crops, and ``?2048`` emits reply."""
+    term = libvt.Terminal(rows=4, cols=10, scrollback=20, record_events=True)
+    term.feed(b"\x1b[?2048h0123456789abcdefgh\r\nhard")
+    assert (term[0].text, term[0].wrapped) == ("0123456789", True)
+
+    term.resize(rows=4, cols=20)
+    assert (term[0].text, term[0].wrapped, term[1].text) == (
+        "0123456789abcdefgh",
+        False,
+        "hard",
+    )
+    assert term.drain_replies() == b"\x1b[48;4;20;0;0t"
+    assert InBandResize(rows=4, cols=20) in term.drain_events()
+
+    term.feed(b"\x1b[?1049h\x1b[H0123456789abcdefgh")
+    term.resize(rows=4, cols=10)
+    assert (term[0].text, term[0].wrapped) == ("0123456789", False)
+
+
+def test_row_wide_healing_decslrm_scroll_and_rle_history() -> None:
+    """``SPACER_HEAD`` heals on edit, ``DECSLRM`` scrolls, and ``FrozenRow`` packs."""
+    narrow_term = libvt.Terminal(rows=3, cols=4)
+    narrow_term.feed("abc❤️".encode())
+    assert narrow_term[0, 3].width_role == WidthRole.SPACER_HEAD
+    narrow_term.feed(b"\x1b[2;1HZ")
+    assert (narrow_term[0, 3].width_role, narrow_term[0].wrapped) == (
+        WidthRole.NARROW,
+        False,
+    )
+    assert (narrow_term[1, 0].text, narrow_term[1, 1].width_role) == (
+        "Z",
+        WidthRole.NARROW,
+    )
+
+    w2w = libvt.Terminal(rows=3, cols=4)
+    w2w.feed_str("abc❤️\x1b[2;1H日")
+    assert (w2w[0, 3].width_role, w2w[0].wrapped, w2w[1, 0].text) == (
+        WidthRole.NARROW,
+        False,
+        "日",
+    )
+
+    # DECSLRM horizontal margin scroll_up / scroll_down + partial ECH text_used trim.
+    scr_up = libvt.Terminal(rows=2, cols=6)
+    scr_up.feed(b"\r\nCD\x1b[?69h\x1b[1;2s\x1b[1;1H\x1b[S")
+    assert scr_up[0].text == "CD"
+
+    scr_dn = libvt.Terminal(rows=2, cols=6)
+    scr_dn.feed(b"AB\x1b[?69h\x1b[1;2s\x1b[1;1H\x1b[T")
+    assert scr_dn[1].text == "AB"
+
+    ech_t = libvt.Terminal(rows=2, cols=10)
+    ech_t.feed(b"ABCD\x1b[3G\x1b[2X")
+    assert ech_t[0].text == "AB"
+
+    # Explicit spaces survive EL 0; RowView stays anchored; FrozenRow.used stays tight.
+    term = libvt.Terminal(rows=3, cols=8, scrollback=20)
+    term.feed(b"   \x1b[K")
+    assert term.screen._rows[0].used == 3
+
+    term.reset()
+    term.feed("日本語\x1b[1;2H\x1b[1@".encode())
+    _assert_grid_invariants(term)
+    term.reset()
+    term.feed("日本語\x1b[1;2H\x1b[2P".encode())
+    _assert_grid_invariants(term)
+
+    fr_t = libvt.Terminal(rows=2, cols=80, scrollback=8)
+    top_view = fr_t[0]
+    fr_t.feed(b"\x1b[31mA\x1b[0m\r\nB\r\nC")
+    assert fr_t._screens.primary._history[0].used == 1
+    assert top_view.text == "B"
+    assert len(fr_t.history[0].runs) >= 1
+
+
+def test_seeded_grid_and_reflow_invariants() -> None:
+    """Seeded property fuzzing preserves wide-spacer and cursor bounds."""
+    rng = random.Random(20261121)
+    tokens: tuple[bytes, ...] = (
+        b"abc",
+        "日本".encode(),
+        "🧑‍🌾".encode(),
+        "🇯🇵".encode(),
+        "❤\ufe0f".encode(),
+        "a\u0301".encode(),
+        b"\r",
+        b"\n",
+        b"\x08",
+        b"\t",
+        b"\x1b[A",
+        b"\x1b[B",
+        b"\x1b[C",
+        b"\x1b[D",
+        b"\x1b[2@",
+        b"\x1b[2P",
+        b"\x1b[2X",
+        b"\x1b[K",
+        b"\x1b[1K",
+        b"\x1b[J",
+        b"\x1b[L",
+        b"\x1b[M",
+        b"\x1b[2;5r",
+        b"\x1b[r",
+        b"\x1b[?69h\x1b[2;7s",
+        b"\x1b[?69l",
+        b"\x1b[?1049h",
+        b"\x1b[?1049l",
+    )
+
+    for trial in range(80):
+        term = libvt.Terminal(
+            rows=rng.choice((4, 6, 8)),
+            cols=rng.choice((6, 8, 12)),
+            scrollback=30,
+        )
+        stream = b"".join(rng.choice(tokens) for _ in range(28))
+        idx = 0
+        while idx < len(stream):
+            step = rng.randint(1, 11)
+            term.feed(stream[idx : idx + step])
+            idx += step
+        _assert_grid_invariants(term)
+        if trial % 4 == 0:
+            term.resize(rows=rng.choice((3, 6, 9)), cols=rng.choice((5, 8, 14)))
+            _assert_grid_invariants(term)
diff --git a/tests/test_status.py b/tests/test_status.py
new file mode 100644
index 0000000..6b0c80a
--- /dev/null
+++ b/tests/test_status.py
@@ -0,0 +1,155 @@
+"""Tests for ``libvt.status`` (``OSC 7501`` / ``9;4``) and ``OSC 133/7/52``."""
+
+from __future__ import annotations
+
+import base64
+
+import libvt
+from libvt.config import Policy, Profile
+from libvt.events import (
+    ClipboardWrite,
+    ColorSchemeQueried,
+    Passthrough,
+    ProgramStatusChanged,
+    WorkingDirectoryChanged,
+)
+from libvt.status import BlockKind, StatusState
+
+
+def test_osc_7501_hierarchy_urgency_spoof_rejection_and_pruning() -> None:
+    """Rex ``OSC 7501`` enforces grammar, hierarchy, urgency, and lifecycle pruning."""
+    pull_term = libvt.Terminal(rows=4, cols=30, record_events=False)
+    pull_term.feed(b"\x1b]7501;?\x07")
+    pull_reply = pull_term.drain_replies()
+    assert pull_reply.startswith(b"\x1b]7501;?:")
+    assert pull_reply.endswith(b"\x07")
+
+    suppressed = libvt.Terminal(
+        rows=4,
+        cols=30,
+        policy=Policy(allow_program_status_query=False),
+    )
+    suppressed.feed(b"\x1b]7501;?\x07")
+    assert suppressed.drain_replies() == b""
+
+    term = libvt.Terminal(rows=6, cols=40, record_events=True)
+    term.feed(b"\x1b]7501;?\x1b\\")
+    assert term.drain_replies().endswith(b"\x1b\\")
+
+    term.feed(b"\x1b]9;4;1;35\x07")
+    assert term.program_status is not None
+    assert (term.program_status.state, term.program_status.progress) == (
+        StatusState.WORKING,
+        35,
+    )
+
+    b64_title = base64.b64encode("Compiling 日本".encode()).decode("ascii")
+    term.feed(
+        f"\x1b]7501;state=working:id=build:app=cargo:progress=50:title={b64_title}\x1b\\".encode(),
+    )
+    term.feed(b"\x1b]7501;state=blocked:id=build/sign:kind=auth\x1b\\")
+    term.feed(b"\x1b]9;4;0\x07")
+
+    child = term.program_statuses["build/sign"]
+    assert (child.effective_app, child.kind) == ("cargo", BlockKind.AUTH)
+    assert term.program_statuses["build"].title == "Compiling 日本"
+    assert term.program_status == child
+
+    spoof_b64 = base64.b64encode("ok\u202eevil".encode()).decode("ascii")
+    term.feed(f"\x1b]7501;state=error:id=spoof:title={spoof_b64}\x1b\\".encode())
+    assert "spoof" not in term.program_statuses
+
+    term.feed(b"\x1b]7501;state=working\x1b\\")
+    term.feed(b"\x1b]133;A;k=s\x07")
+    assert "" in term.program_statuses
+    term.feed(b"\x1b]133;A\x07")
+    assert "" not in term.program_statuses
+
+    term.feed(b"\x1b]7501;state=done:id=lint\x1b\\")
+    term.notify_process_exit()
+    assert "lint" in term.program_statuses
+    assert "build" not in term.program_statuses
+
+    term.feed(b"\x1b]7501;state=working:id=tree\x1b\\")
+    term.feed(b"\x1b]7501;state=working:id=tree/leaf\x1b\\")
+    term.feed(b"\x1b]7501;state=clear:id=tree\x1b\\")
+    assert "tree" not in term.program_statuses
+    assert "tree/leaf" not in term.program_statuses
+    assert any(isinstance(e, ProgramStatusChanged) for e in term.drain_events())
+
+
+def test_osc_133_osc_7_osc_52_queries_and_tmux_passthrough() -> None:
+    """``OSC 133/7/52``, terminal queries, and ``DCS tmux;`` passthrough obey policy."""
+    term = libvt.Terminal(
+        rows=3,
+        cols=20,
+        scrollback=20,
+        profile=Profile(color_scheme=libvt.ColorScheme.LIGHT),
+        record_events=True,
+    )
+    for idx in range(4):
+        term.feed(
+            f"\x1b]133;A\x07$ \x1b]133;B\x07c{idx}\r\n"
+            f"\x1b]133;C\x07o\r\n\x1b]133;D;0\x07".encode(),
+        )
+    zones = term.prompt_zones
+    assert [z.abs_row for z in zones] == sorted(z.abs_row for z in zones)
+    assert zones[-1].exit_code == 0
+
+    term.feed(b"\x1b]7;file://localhost/tmp/my%20dir\x07")
+    assert (term.cwd, term.cwd_uri) == ("/tmp/my dir", "file://localhost/tmp/my%20dir")
+    term.feed(b"\x1b]7;file://remote-box.example/srv\x07")
+    assert (term.cwd, term.cwd_uri) == ("", "file://remote-box.example/srv")
+    term.feed(b"\x1b]7;file://localhost/bad%00path\x07")
+    assert term.cwd == ""
+    term.feed(b"\x1b]7;\x07")
+    assert (term.cwd, term.cwd_uri) == ("", "")
+
+    clip_b64 = base64.b64encode(b"copied").decode("ascii")
+    term.feed(f"\x1b]52;c;{clip_b64}\x07\x1b]52;c;?\x07".encode("ascii"))
+    assert term.drain_replies() == b""
+    events = term.drain_events()
+    assert (
+        WorkingDirectoryChanged(uri="file://remote-box.example/srv", path="/srv")
+        in events
+    )
+    assert ClipboardWrite(selection="c", text="copied") in events
+
+    term.feed(
+        b"\x1b[>q\x1bP$qm\x1b\\\x1bP+q544e\x1b\\\x1b]10;?\x07\x1b[?2031h\x1b[?996n",
+    )
+    replies = term.drain_replies()
+    assert b"\x1bP>|libvt" in replies
+    assert b"\x1bP1$r" in replies
+    assert b"\x1bP1+r544e=" in replies
+    assert b"\x1b]10;rgb:" in replies
+    assert b"\x1b[?997;2n" in replies
+    assert ColorSchemeQueried(scheme=libvt.ColorScheme.LIGHT) in term.drain_events()
+
+    term.feed(b"\x1bPtmux;\x1b\x1b]2;spoofed-title\x07\x1b\\")
+    assert term.title == ""
+    assert term.drain_events() == (Passthrough(data=b"\x1b]2;spoofed-title\x07"),)
+
+    allow_term = libvt.Terminal(
+        rows=3,
+        cols=20,
+        policy=Policy(allow_passthrough=True),
+        record_events=True,
+    )
+    allow_term.feed(b"\x1bPtmux;\x1b\x1b]2;hel\x1b\\" + b"\x1bPtmux;lo\x07\x1b\\")
+    assert allow_term.title == "hello"
+    allow_term.feed(
+        b"\x1bPtmux;\x1b\x1bPtmux;"
+        b"\x1b\x1b\x1b\x1b]7501;state=done:id=nested2\x1b\x1b\x1b\x1b\\"
+        b"\x1b\x1b\\\x1b\\",
+    )
+    assert "nested2" in allow_term.program_statuses
+
+    tmux_term = libvt.Terminal(
+        rows=3,
+        cols=20,
+        profile=libvt.TMUX_PROFILE,
+        policy=Policy(strict=True),
+    )
+    tmux_term.feed(b"\x1bkbuild-win\x1b\\OK\x1b]10;rgb:11/22/33\x1b\\\x1b]110\x1b\\")
+    assert (tmux_term.text, tmux_term.window_name) == ("OK", "build-win")
diff --git a/tests/test_terminal.py b/tests/test_terminal.py
index a77517d..dabab74 100644
--- a/tests/test_terminal.py
+++ b/tests/test_terminal.py
@@ -1,174 +1,405 @@
-"""Terminal emulation, charsets, modes, reflow, sync stepping, and format tests."""
+"""Tests for ``libvt.terminal``, ``Profile`` quirks, ``?2026``, and deltas."""
 
 from __future__ import annotations
 
+import time
+import typing as t
+
 import pytest
 
 import libvt
-from libvt.config import TMUX_PROFILE, XTERM_PROFILE, Policy
-from libvt.events import InBandResize, RenderHoldChanged
+from libvt.config import (
+    DEFAULT_PROFILE,
+    TMUX_PROFILE,
+    XTERM_PROFILE,
+    Policy,
+    Profile,
+    SixelErasePolicy,
+)
+from libvt.events import RenderHoldChanged, ScreenErased
 from libvt.exc import ProtocolError
-from libvt.terminal import OutputFormat, StopOn
-
-
-def test_dec_special_graphics_g0_g3_so_si_ss2_ss3_and_decsc() -> None:
-    """``G0..G3`` DEC Special Graphics translate box drawing and ``DECSC``/``DECRC``."""
-    term = libvt.Terminal(rows=4, cols=16)
-    # DECSC at col 5 saves G0='0'; DECRC restores col 5 and G0='0' ('x' -> '│').
+from libvt.modes import Mode
+from libvt.screen import RowView
+from libvt.style import AnsiColor
+from libvt.terminal import OutputFormat, ResyncReason, StopOn
+
+
+class TmuxVersionCase(t.NamedTuple):
+    """Typed version-parsing scenario for :meth:`Profile.tmux`."""
+
+    test_id: str
+    version: str
+    rep_wraps: bool
+    sixel_erase_policy: SixelErasePolicy
+
+
+TMUX_VERSION_CASES: list[TmuxVersionCase] = [
+    TmuxVersionCase("tmux-3.8a", "tmux 3.8a", False, "whole_image"),
+    TmuxVersionCase("tmux-3.8-rc3", "tmux 3.8-rc3", False, "whole_image"),
+    TmuxVersionCase("next-3.9", "next-3.9", True, "cell_mask"),
+    TmuxVersionCase("release-3.9", "3.9", True, "cell_mask"),
+]
+
+
+@pytest.mark.parametrize(
+    "case",
+    TMUX_VERSION_CASES,
+    ids=[c.test_id for c in TMUX_VERSION_CASES],
+)
+def test_tmux_profile_version_matrix(case: TmuxVersionCase) -> None:
+    """``Profile.tmux`` gates ``REP`` wrap and ``SIXEL`` erase policy by version."""
+    prof = Profile.tmux(case.version)
+    assert prof.rep_wraps is case.rep_wraps
+    assert prof.sixel_erase_policy == case.sixel_erase_policy
+    term = libvt.Terminal(rows=2, cols=5, profile=prof)
+    term.feed(b"1234X\x1b[2b")
+    assert term.lines == (("1234X", "XX") if case.rep_wraps else ("1234X", ""))
+
+
+def test_charsets_g0_g3_decsc_and_linux_console_profile() -> None:
+    """``G0..G3`` DEC Special Graphics, ``DECSC``/``DECRC``, and ``linux_console``."""
+    term = libvt.Terminal(rows=3, cols=16)
     term.feed(b"\x1b(0lqqqk\x1b7\x1b(B plain\x1b8x")
     assert term[0].text == "┌───┐│plain"
 
-    # G1 via SO/SI (0x0E / 0x0F), G2 via SS2 (ESC N), G3 via SS3 (ESC O).
     term.reset()
     term.feed(b"\x1b)0\x0emqj\x0fa\x1b*0\x1bNl\x1b+0\x1bOkz")
     assert term[0].text == "└─┘a┌┐z"
 
+    lt = libvt.Terminal(rows=2, cols=8, profile=Profile.linux_console())
+    lt.feed(b"\x0elqqk\x0f")
+    assert lt[0].text == "┌──┐"
 
-def test_cbt_cht_decsca_decsed_decsel_and_csi_22_j() -> None:
-    """``CBT``/``CHT``, ``DECSCA`` selective erase, and ``CSI 22 J`` scroll-push."""
+
+def test_csi_motions_selective_erase_ed3_ed2_and_decstr() -> None:
+    """``CBT/CHT``, ``HPR/VPR``, ``DECSCA``, ``ED 2/3/22``, ``DECALN``, ``DECSTR``."""
     term = libvt.Terminal(rows=4, cols=24, scrollback=20)
-    # CHT 2 jumps 0 -> 16; 'a' prints at 16 (cursor -> 17); CBT 2 steps 17 -> 16 -> 8.
     term.feed(b"\x1b[2Ia\x1b[2Zb")
-    assert term[0, 16].text == "a"
-    assert term[0, 8].text == "b"
+    assert (term[0, 16].text, term[0, 8].text) == ("a", "b")
 
-    # DECSCA: CSI 1 " q protects cells from DECSEL (CSI ? 2 K) & DECSED (CSI ? 2 J).
     term.reset()
-    term.feed(b'\x1b[1"qSAFE\x1b[0"qWIPE\x1b[?2K')
-    assert term[0].text == "SAFE"
-    term.feed(b"\x1b[?2J")
+    term.feed(b'\x1b[1"qSAFE\x1b[0"qWIPE\x1b[?2K\x1b[?2J')
     assert term[0].text == "SAFE"
-    # Unconditional ED 2 erases protected cells too.
     term.feed(b"\x1b[2J")
     assert term[0].text == ""
 
-    # CSI 22 J (xterm / Ghostty E3 scroll-clear) pushes viewport lines into scrollback.
     term.reset()
-    term.feed(b"first\r\nsecond")
-    term.feed(b"\x1b[22J")
-    assert term.text == ""
-    assert [r.text for r in term.history] == ["first", "second"]
+    term.feed(b"first\r\nsecond\x1b[22J")
+    assert (term.text, [r.text for r in term.history]) == ("", ["first", "second"])
+
+    # HPR / VPR obey DECOM and are ignored quietly under TMUX_PROFILE.
+    margin_t = libvt.Terminal(rows=4, cols=8)
+    margin_t.feed(b"\x1b[?69h\x1b[2;3r\x1b[3;6s\x1b[2;3H\x1b[10a\x1b[10e")
+    assert (margin_t.cursor.row, margin_t.cursor.col) == (3, 7)
+    margin_t.feed(b"\x1b[?6h\x1b[1a\x1b[1e\x1b[99a\x1b[99e")
+    assert (margin_t.cursor.row, margin_t.cursor.col) == (2, 5)
+
+    tm_strict = libvt.Terminal(
+        rows=2,
+        cols=8,
+        profile=TMUX_PROFILE,
+        policy=Policy(strict=True),
+    )
+    tm_strict.feed(b"A\x1b[3aB\x1b[2eC\x1b[!p")
+    assert tm_strict[0].text == "ABC"
+
+    # DECALN resets margins/wraps; non-print clears REP; ?47/?1049 share DECRQM truth.
+    aln_t = libvt.Terminal(rows=2, cols=4)
+    aln_t.feed(b"ABCDEF\x1b[?69h\x1b[2;3s\x1b#8")
+    assert (aln_t.lines, aln_t[0].wrapped) == (("EEEE", "EEEE"), False)
+    aln_t.feed(b"\x1b[1;1HA\x1b[C\x1b[3b\x1b[?47h\x1b[?1049l\x1b[?47$p")
+    assert aln_t.drain_replies() == b"\x1b[?47;2$y"
+
+    # ED 3 preserves viewport & pending_wrap; alt ED 3 obeys profile flag.
+    ed3_t = libvt.Terminal(rows=2, cols=4, scrollback=10, record_events=True)
+    ed3_t.feed(b"old\r\nnew\r\nABCD")
+    ed3_t.drain_events()
+    ed3_t.feed(b"\x1b[3J\x1b[?3J\x1b[99J")
+    assert (ed3_t.history, ed3_t.lines, ed3_t.cursor.pending_wrap) == (
+        (),
+        ("new", "ABCD"),
+        True,
+    )
+    assert [e for e in ed3_t.drain_events() if isinstance(e, ScreenErased)] == []
+
+    def_alt = libvt.Terminal(rows=2, cols=6, scrollback=10, profile=DEFAULT_PROFILE)
+    def_alt.feed(b"h1\r\nh2\r\nv\x1b[?1049hALT\x1b[3J")
+    assert [r.text for r in def_alt.history] == ["h1"]
+
+    # TMUX_PROFILE ignores DECSTR and scrolls primary ED 2 / ED 0 at (0,0) to history.
+    tm2 = libvt.Terminal(rows=4, cols=10, scrollback=20, profile=TMUX_PROFILE)
+    tm2.feed(b"ROW_ONE\r\nROW_TWO\x1b[4;5H\x1b[44m\x1b[2J")
+    assert [r.text for r in tm2.history] == ["ROW_ONE", "ROW_TWO"]
+    assert (tm2[0, 0].style.bg, tm2.cursor.row, tm2.cursor.col) == (
+        AnsiColor.BLUE,
+        3,
+        4,
+    )
+    tm2.feed(b"\x1b[0m\x1b[HHOME_ROW\x1b[H\x1b[J\x1b[?1049hALT_LINE\x1b[2J")
+    assert [r.text for r in tm2.history] == [
+        "ROW_ONE",
+        "ROW_TWO",
+        "HOME_ROW",
+        "",
+        "",
+        "",
+    ]
+    assert tm2.history[3][0].style.bg == AnsiColor.BLUE
+
+
+def test_right_margin_vs16_zwsp_bmp_slicing_and_no_autowrap_fast_path() -> None:
+    """Right-margin ``VS16`` preserves SGR/margins/``IRM``, ``ZWSP`` breaks, ``?7l``."""
+    payload = "\x1b[31mabc1\x1b[34m\ufe0f\u20e3Z"
+    for per_byte in (False, True):
+        term = libvt.Terminal(rows=3, cols=4)
+        if per_byte:
+            raw = payload.encode("utf-8")
+            for idx in range(len(raw)):
+                term.feed(raw[idx : idx + 1])
+        else:
+            term.feed_str(payload)
+        assert (term[0].text, term[0].wrapped) == ("abc", True)
+        assert (term[1, 0].text, term[1, 0].width, term[1, 0].style.fg) == (
+            "1\ufe0f\u20e3",
+            2,
+            AnsiColor.RED,
+        )
+        assert (term[1, 2].text, term[1, 2].style.fg) == ("Z", AnsiColor.BLUE)
+
+    bounded = libvt.Terminal(rows=4, cols=4)
+    bounded.feed_str("\x1b[1;2rL0\r\nabc1\ufe0f\u20e3Z")
+    assert (bounded[0].text, bounded[0].wrapped, bounded[1, 0].text) == (
+        "abc",
+        True,
+        "1\ufe0f\u20e3",
+    )
+
+    irm = libvt.Terminal(rows=3, cols=4)
+    irm.feed_str("\x1b[2;1HXY\x1b[1;1H\x1b[4habc1\ufe0f\u20e3")
+    assert (irm[1, 0].text, irm[1, 2].text, irm[1, 3].text) == (
+        "1\ufe0f\u20e3",
+        "X",
+        "Y",
+    )
 
+    zwsp = libvt.Terminal(rows=2, cols=6)
+    zwsp.feed_str("1\u200b\ufe0fA")
+    assert (zwsp[0, 0].width, zwsp[0, 1].text) == (1, "A")
 
-def test_alt_screen_single_truth_decrqm_and_mode_aliases() -> None:
-    """``?47``, ``?1047``, and ``?1049`` report real buffer state via ``DECRQM``."""
-    term = libvt.Terminal(rows=4, cols=12)
-    term.feed(b"primary\x1b[?47h\x1b[?1049l\x1b[?47$p")
-    assert term[0].text == "primary"
-    assert term.screens.active_is_alt is False
-    # Status 2 means recognized & reset (NOT stale 1 = set).
-    assert term.drain_replies() == b"\x1b[?47;2$y"
+    # Narrow-BMP slice fast path + split GCB_PREPEND + ?7l clamp & O(cols) collapse.
+    bmp = libvt.Terminal(rows=3, cols=8)
+    bmp.feed("\x1b[32mcafé\x1b[2b ─│┌┐".encode())
+    assert (bmp[0].text, bmp[0].wrapped, bmp[1].text) == ("cafééé ─", True, "│┌┐")
 
+    split = libvt.Terminal(rows=2, cols=8)
+    split.feed("\u0600".encode())
+    split.feed(b"1")
+    assert split[0, 0].text == "\u06001"
 
-def test_tmux_vs_xterm_pending_wrap_and_reverse_wrap() -> None:
-    """``TMUX_PROFILE`` models phantom-column ``pending_wrap`` and soft-wrap ``BS``."""
+    no_wrap = libvt.Terminal(rows=2, cols=4)
+    no_wrap.feed("\x1b[?7lABC\u26a0\ufe0f".encode())
+    assert (libvt.display_width(no_wrap[0].text) <= 4, no_wrap[0, 3].width) == (True, 1)
+
+    t0 = time.monotonic()
+    no_wrap.feed_str("\x1b[1;1H" + ("ABCD" * 2_500) + "!")
+    assert time.monotonic() - t0 < 0.1
+    assert no_wrap[0].text == "ABC!"
+
+
+def test_tmux_phantom_column_reverse_wrap_and_il_dl() -> None:
+    """``TMUX_PROFILE`` models phantom col ``cols``, reverse ``BS``, and ``IL/DL``."""
     xt = libvt.Terminal(rows=3, cols=5, profile=XTERM_PROFILE)
     xt.feed(b"12345\x1b[1DX")
     assert xt[0].text == "123X5"
+    xt.reset()
+    xt.feed(b"\x1b[?45habcdef\x08\x08Z")
+    assert xt[0].text == "abcdZ"
 
     tm = libvt.Terminal(rows=3, cols=5, profile=TMUX_PROFILE)
     tm.feed(b"12345\x1b[1DX")
     assert tm[0].text == "1234X"
-
-    # Soft-wrap BS across row boundary in TMUX_PROFILE vs XTERM_PROFILE with ?45h.
     tm.reset()
     tm.feed(b"abcdef\x08\x08Z")
     assert tm[0].text == "abcdZ"
 
-    xt.reset()
-    xt.feed(b"\x1b[?45habcdef\x08\x08Z")
-    assert xt[0].text == "abcdZ"
+    tm.reset()
+    tm.feed(b"\x1b[7mHEAD!\x1b[K\x1b[0m")
+    assert (tm[0].text, tm[0, 4].style.reverse, tm.cursor.pending_wrap) == (
+        "HEAD!",
+        True,
+        True,
+    )
+
+    tm.reset()
+    tm.feed(b"12345\r\nrow-2\x1b[1;1H12345\x1b[J\x1b[X\x1b[@\x1b[P\x1b[6n")
+    assert (tm.lines, tm.cursor.pending_wrap, tm.drain_replies()) == (
+        ("12345", "", ""),
+        True,
+        b"\x1b[1;6R",
+    )
 
+    tm.reset()
+    tm.feed(b"12345\nX")
+    assert tm.lines == ("12345", "", "X")
+    tm.reset()
+    tm.feed(b"\x1b[2;1H12345\x1bMX")
+    assert tm.lines == ("", "X2345", "")
+    tm.reset()
+    tm.feed(b"12345\x1b7\x1b8X")
+    assert tm[0].text == "1234X"
 
-def test_resize_reflow_primary_vs_alt_and_inband_2048() -> None:
-    """Primary soft-wrapped lines reflow on resize; alt crops; ``?2048`` notifies."""
-    term = libvt.Terminal(rows=4, cols=10, scrollback=20, record_events=True)
-    term.feed(b"\x1b[?2048h0123456789abcdefgh\r\nhard")
-    assert term[0].text == "0123456789"
-    assert term[0].wrapped is True
-    assert term[1].text == "abcdefgh"
-    assert term[2].text == "hard"
-
-    term.resize(rows=4, cols=20)
-    assert term[0].text == "0123456789abcdefgh"
-    assert term[0].wrapped is False
-    assert term[1].text == "hard"
-    assert term.drain_replies() == b"\x1b[48;4;20;0;0t"
-    events = term.drain_events()
-    assert InBandResize(rows=4, cols=20) in events
-
-    # Alt screen never reflows logical lines.
-    term.feed(b"\x1b[?1049h\x1b[H0123456789abcdefgh")
-    term.resize(rows=4, cols=10)
-    assert term[0].text == "0123456789"
-    assert term[0].wrapped is False
-
-
-def test_synchronized_output_cow_feed_until_and_generation_expiry() -> None:
-    """``?2026`` CoW holds ``committed``, ``feed_until`` steps, and expiry checks."""
-    term = libvt.Terminal(rows=4, cols=16, record_events=True)
-    term.feed(b"frame-0")
-    assert term.committed[0].text == "frame-0"
-
-    batch = b"\x1b[?2026h\x1b[Hpartial\x1b[?2026l\x1b[?2026h\x1b[Hframe-2"
-    res1 = term.feed_until(batch, stop=StopOn.SYNC_END)
-    assert res1.stopped_on == StopOn.SYNC_END
-    assert term.synchronized is False
-    assert term.committed[0].text == "partial"
-
-    term.feed(batch[res1.offset :])
-    assert term.synchronized is True
-    assert term.committed[0].text == "partial"
-    assert term.snapshot()[0].text == "frame-2"
-
-    cur_gen = term.sync_generation
-    assert term.expire_synchronized_output(cur_gen - 1) is False
-    assert term.synchronized is True
-    assert term.expire_synchronized_output(cur_gen) is True
-    assert term.synchronized is False
-    assert term.committed[0].text == "frame-2"
-    hold_events = [e for e in term.drain_events() if isinstance(e, RenderHoldChanged)]
-    assert hold_events[-1] == RenderHoldChanged(
-        active=False,
-        sync_generation=cur_gen,
-        expired=True,
+    tm.reset()
+    tm.feed(b"abcde\r\n12345\x1b[2;4H\x1b[L\x1b[M")
+    assert tm.cursor.col == 3
+
+
+def test_sync_2026_cow_feed_until_and_expiry() -> None:
+    """``?2026`` freezes pre-``BSU`` state across cuts, steps, and expires safely."""
+    payload = b"B\x1b[?2026hC"
+    for chunks in (
+        [payload],
+        [bytes([b]) for b in payload],
+        [payload[:3], payload[3:]],
+    ):
+        term = libvt.Terminal(rows=2, cols=8)
+        term.feed(b"A")
+        assert term.committed[0].text == "A"
+        for chunk in chunks:
+            term.feed(chunk)
+        held = term.committed
+        assert (held[0].text, held.cursor.col) == ("AB", 2)
+        assert Mode.SYNCHRONIZED_OUTPUT not in held.modes
+        term.feed(b"\x1b[?2026l")
+        assert term.committed[0].text == "ABC"
+
+    term2 = libvt.Terminal(rows=3, cols=16, record_events=True)
+    term2.feed(b"A\x1b[?2026h\x1b[2;3H\x1b[?25l\x1b]2;Next\x07\x1b[6n\x1b[?2026$p")
+    held2 = term2.committed
+    assert (held2.cursor.row, held2.cursor.col, held2.cursor.visible, held2.title) == (
+        0,
+        1,
+        True,
+        "",
     )
+    assert term2.drain_replies() == b"\x1b[2;3R\x1b[?2026;1$y"
 
-    # StopOn.GROUND must not fire in the middle of a multi-byte UTF-8 sequence.
+    cur_gen = term2.sync_generation
+    assert term2.expire_synchronized_output(cur_gen - 1) is False
+    assert term2.expire_synchronized_output(cur_gen) is True
+    assert term2.committed.title == "Next"
+    hold_events = [e for e in term2.drain_events() if isinstance(e, RenderHoldChanged)]
+    assert hold_events[-1].expired is True
+
+    # StopOn.GROUND waits for complete multi-byte UTF-8 scalar.
     utf8_term = libvt.Terminal(rows=2, cols=10)
-    part1 = utf8_term.feed_until("日".encode()[:2], stop=StopOn.GROUND)
-    assert part1.stopped_on == StopOn.EOF
+    assert utf8_term.feed_until("日".encode()[:2], stop=StopOn.GROUND).stopped_on == (
+        StopOn.EOF
+    )
     part2 = utf8_term.feed_until("日A".encode()[2:], stop=StopOn.GROUND)
-    assert part2.stopped_on == StopOn.GROUND
-    assert part2.offset == 1
-    assert utf8_term[0, 0].text == "日"
+    assert (part2.stopped_on, part2.offset, utf8_term[0, 0].text) == (
+        StopOn.GROUND,
+        1,
+        "日",
+    )
 
 
-def test_formatter_plain_vt_html_xss_and_snapshot_to_dict() -> None:
-    """Formatters roundtrip VT, coalesce HTML spans, block XSS URIs, and serialize."""
-    term = libvt.Terminal(rows=3, cols=20)
+def test_formatters_bce_xss_and_snapshot_immutability() -> None:
+    """``Formatter`` preserves VT BCE, sanitizes HTML URIs, and freezes ``Snapshot``."""
+    term = libvt.Terminal(rows=2, cols=20)
     term.feed(
-        b"\x1b[1;38;2;200;40;40mhi\x1b[0m "
-        b"\x1b]8;;https://example.com\x07ok\x1b]8;;\x07 "
+        b"\x1b[42;31;4:3;9;53mHI\x1b[K\r\n"
+        b"\x1b[0m\x1b]8;;https://example.com\x07ok\x1b]8;;\x07 "
         b"\x1b]8;;javascript:alert(1)\x07bad\x1b]8;;\x07",
     )
     snap = term.snapshot()
-    assert snap.format(OutputFormat.PLAIN) == "hi ok bad"
+    assert snap.format(OutputFormat.PLAIN) == "HI\nok bad"
+    assert snap[0, 19].style.bg == AnsiColor.GREEN
+
+    rt = libvt.Terminal(rows=2, cols=20)
+    rt.feed_str(snap.format(OutputFormat.VT))
+    assert (rt[0].text, rt[0, 19].style.bg) == ("HI", AnsiColor.GREEN)
 
     html_out = snap.format(OutputFormat.HTML)
     assert 'href="https://example.com"' in html_out
     assert "javascript:" not in html_out
+    assert "text-decoration-style:wavy" in html_out
+    assert snap.to_dict()["rows"] == 2
 
-    vt_text = snap.format(OutputFormat.VT)
-    roundtrip = libvt.Terminal(rows=3, cols=20)
-    roundtrip.feed_str(vt_text)
-    assert roundtrip.text == snap.text
-    assert roundtrip[0, 0].style == snap[0, 0].style
-
-    payload_dict = snap.to_dict()
-    assert payload_dict["rows"] == 3
-    assert payload_dict["cols"] == 20
+    with pytest.raises(AttributeError):
+        snap.title = "mutated"
+    with pytest.raises(TypeError):
+        t.cast("dict[str, object]", snap.program_statuses)["x"] = None
 
     strict_term = libvt.Terminal(rows=2, cols=10, policy=Policy(strict=True))
     with pytest.raises(ProtocolError):
         strict_term.feed(b"\x1b[999z")
+
+
+def test_changes_since_watermarks_and_replica_equivalence() -> None:
+    """``changes_since`` and ``apply_lines``/``apply_rows`` maintain exact replicas."""
+    term = libvt.Terminal(rows=4, cols=6, scrollback=6, profile=TMUX_PROFILE)
+    rep_lines_hist: list[str] = []
+    rep_lines_view: list[str] = []
+    rep_rows_hist: list[RowView] = []
+    rep_rows_view: list[RowView] = []
+
+    def _step(tok: libvt.SyncToken | None) -> libvt.ScreenDelta:
+        delta = term.changes_since(tok)
+        delta.apply_lines(rep_lines_hist, rep_lines_view)
+        delta.apply_rows(rep_rows_hist, rep_rows_view)
+        snap = delta.snapshot
+        assert rep_lines_hist == [r.text for r in snap.history]
+        assert rep_lines_view == list(snap.lines)
+        assert [(r.text, r.wrapped) for r in rep_rows_view] == [
+            (snap[i].text, snap[i].wrapped) for i in range(snap.rows)
+        ]
+        return delta
+
+    d = _step(None)
+    assert d.resync_reason == ResyncReason.INITIAL
+
+    term.feed_str("abcde中\r\nLINE_2")
+    d = _step(d.token)
+    assert rep_rows_view[0].wrapped is True
+    term.feed_str("\x1b[2;1H\x1b[P")
+    d = _step(d.token)
+    assert rep_rows_view[0].wrapped is False
+
+    term.feed_str("\x1b[4;1H\r\nS1\r\nS2\r\nS3\r\nS4\r\nS5")
+    d = _step(d.token)
+    assert (d.resync_reason, d.viewport_scroll_up) == (ResyncReason.NONE, 5)
+
+    term.feed_str("\x1b[1;3r\x1b[3;1H\nTOP_SC\x1b[r\x1b[3J\x1b[4;1H\r\nPOST_CLR")
+    d = _step(d.token)
+    assert d.history_cleared is True
+
+    term.feed(b"\x1b]7501;state=working:id=build\x07")
+    d = _step(d.token)
+    assert d.metadata_changed is True
+    term.feed(b"\x1b]7;file://remote-box.example/srv/app\x07")
+    d = _step(d.token)
+    assert (d.metadata_changed, d.snapshot.cwd_uri) == (
+        True,
+        "file://remote-box.example/srv/app",
+    )
+
+    c_tok = term.sync_token(view="committed")
+    term.feed(b"\x1b[?2026h\x1b[1;1HTORN")
+    assert term.changes_since(c_tok, view="committed").has_changes is False
+    assert 0 in term.changes_since(c_tok, view="working").dirty_rows
+    term.feed(b"\x1b[?2026l")
+    d = _step(c_tok)
+
+    stale_pre_alt = d.token
+    term.feed(b"\x1b[?1049hALT\x1b[?1049l")
+    d = _step(stale_pre_alt)
+    assert d.resync_reason == ResyncReason.EPOCH_CHANGED
+
+    stale_same_epoch = d.token
+    f_tok = d.token
+    for idx in range(10):
+        term.feed(f"\r\nEV{idx}".encode("ascii"))
+        f_tok = term.changes_since(f_tok).token
+    assert term.changes_since(stale_same_epoch).resync_reason == (
+        ResyncReason.HISTORY_EVICTED
+    )
diff --git a/tests/test_testing.py b/tests/test_testing.py
new file mode 100644
index 0000000..35b635f
--- /dev/null
+++ b/tests/test_testing.py
@@ -0,0 +1,78 @@
+"""Tests for ``libvt.testing`` assertions and ``libvt.pytest_plugin`` fixtures."""
+
+from __future__ import annotations
+
+import pytest
+
+import libvt
+from libvt.pytest_plugin import TerminalFactory
+from libvt.terminal import FlightRecorder, Terminal
+from libvt.testing import assert_screen, assert_screen_box
+
+
+def test_pytest_fixtures_and_assert_screen_literal_borders(
+    vt_terminal: Terminal,
+    vt_factory: TerminalFactory,
+    vt_parser: libvt.Parser,
+    vt_recorder: FlightRecorder,
+) -> None:
+    """``vt_*`` fixtures wire recorders; ``assert_screen`` keeps ACS borders."""
+    assert (vt_terminal.rows, vt_terminal.cols) == (24, 80)
+    assert vt_terminal.recorder is vt_recorder
+    assert isinstance(vt_parser, libvt.Parser)
+
+    bordered = vt_factory(rows=3, cols=5)
+    bordered.feed(b"\x1b(0lqqqk\r\nx X x\r\nmqqqj\x1b(B")
+    assert bordered.text == "┌───┐\n│ X │\n└───┘"
+    assert_screen(bordered, bordered.text)
+    assert_screen(
+        bordered,
+        """
+        ┌───┐
+        │ X │
+        └───┘
+        """,
+    )
+
+
+def test_assert_screen_box_wide_soft_wrap_and_bidi_diagnostics(
+    vt_factory: TerminalFactory,
+    vt_recorder: FlightRecorder,
+) -> None:
+    """``assert_screen_box`` validates widths, ``W`` markers, and BiDi escapes."""
+    small = vt_factory(rows=2, cols=8)
+    small.feed("日本ok\r\nline2  W".encode())
+    assert_screen_box(
+        small,
+        """
+        ┌────────┐
+        │日本ok  │
+        │line2  W│
+        └────────┘
+        """,
+    )
+
+    wrapped = vt_factory(rows=2, cols=4)
+    wrapped.feed(b"abcdef")
+    assert_screen_box(
+        wrapped,
+        """
+        ┌────┐
+        │abcd│W
+        │ef  │
+        └────┘
+        """,
+        cursor=(1, 2),
+    )
+
+    with pytest.raises(ValueError, match="display width"):
+        assert_screen_box(small, "┌────┐\n│short│\n└────┘")
+
+    spoof_term = vt_factory(rows=1, cols=10, recorder=vt_recorder)
+    spoof_term.feed(b"\x1b[31mhi")
+    spoof_term.screen._rows[0].write_narrow(2, "\u202e", 0, None)
+    with pytest.raises(AssertionError) as exc_info:
+        assert_screen_box(spoof_term, "┌──────────┐\n│mismatch  │\n└──────────┘")
+    msg = str(exc_info.value)
+    assert "\\u202e" in msg
+    assert "Flight Recorder:" in msg
diff --git a/tests/test_tmux.py b/tests/test_tmux.py
new file mode 100644
index 0000000..8b9d9f1
--- /dev/null
+++ b/tests/test_tmux.py
@@ -0,0 +1,222 @@
+"""Tests for ``libvt.tmux`` ``capture-pane`` reconstruction and ``-CC`` unescape."""
+
+from __future__ import annotations
+
+import shutil
+import subprocess
+import time
+import zlib
+
+import pytest
+
+import libvt
+from libvt.modes import Mode
+from libvt.style import AnsiColor
+from libvt.tmux import (
+    TMUX_METADATA_FORMAT,
+    TmuxLineFlags,
+    TmuxPaneMetadata,
+    decode_tmux_capture,
+    unescape_tmux_control_output,
+)
+
+
+def test_control_mode_unescape_and_metadata_format_parsing() -> None:
+    """``unescape_tmux_control_output`` and ``TmuxPaneMetadata`` handle tmux quirks."""
+    assert unescape_tmux_control_output(r"\033[31mhi\134there\015\012") == (
+        b"\x1b[31mhi\\there\r\n"
+    )
+    raw_utf8_line = b"caf\xc3\xa9\\012".decode("utf-8", errors="surrogateescape")
+    assert unescape_tmux_control_output(raw_utf8_line) == b"caf\xc3\xa9\n"
+
+    assert "#{bracket_paste_flag}" in TMUX_METADATA_FORMAT
+    assert "#{mouse_all_flag}" in TMUX_METADATA_FORMAT
+    assert "#{pane_private_modes}" in TMUX_METADATA_FORMAT
+    raw_fmt = (
+        "8\t3\t0\t2\t1\t0\t4294967295\t4294967295\t0\t2\t"
+        "0\t0\t1\t0\t1\t0\t0\t1\t1\t1004,2004\t"
+        "0,4\t0\t2000\t1\t7\t/tmp\ttitle"
+    )
+    parsed_meta = TmuxPaneMetadata.from_format_line(raw_fmt)
+    assert (parsed_meta.alternate_saved_x, parsed_meta.alternate_saved_y) == (
+        None,
+        None,
+    )
+    assert (
+        parsed_meta.bracketed_paste_flag,
+        parsed_meta.mouse_any_flag,
+        parsed_meta.focus_events_flag,
+        parsed_meta.synchronized,
+    ) == (True, True, True, True)
+
+    sync_term = libvt.Terminal.from_tmux_capture(["HOLD_LIN", "", ""], metadata=raw_fmt)
+    sync_term.feed(b"\x1b[1;1HDIRTY")
+    assert sync_term.committed[0].text == "HOLD_LIN"
+    sync_term.feed(b"\x1b[?2026l")
+    assert sync_term.committed[0].text == "DIRTYLIN"
+
+
+def test_capture_decoder_acs_tabs_joined_wraps_and_prompt_zones() -> None:
+    """``decode_tmux_capture`` reconstructs ACS, tabs, ``-J`` wraps, and zones."""
+    cjk_meta = TmuxPaneMetadata(cols=4, rows=5, history_size=2)
+    cjk_term = libvt.Terminal.from_tmux_capture(
+        ["H0", "H1", "ABCD", "EFGH", "IJ", "abc ", "中文"],
+        metadata=cjk_meta,
+        scrollback=1,
+        joined_capture=["H0", "H1", "ABCDEFGHIJ", "abc中文"],
+    )
+    assert [r.text for r in cjk_term.history] == ["H1"]
+    assert (cjk_term[0].wrapped, cjk_term[1].wrapped, cjk_term[3].wrapped) == (
+        True,
+        True,
+        True,
+    )
+    cjk_term.resize(rows=5, cols=10)
+    assert cjk_term.lines[:3] == ("H1", "ABCDEFGHIJ", "abc中文")
+
+    pz_snap = libvt.Snapshot.from_tmux_capture(
+        ["P H0", "P H1", "- V0", "O V1", "- V2", "- V3", "- V4"],
+        metadata=cjk_meta,
+        scrollback=1,
+        flagged=True,
+    )
+    assert [(z.row, z.kind.value) for z in pz_snap.prompt_zones] == [
+        (-1, "A"),
+        (1, "C"),
+    ]
+
+    meta = TmuxPaneMetadata(
+        cols=8,
+        rows=3,
+        cursor_x=8,
+        cursor_y=2,
+        wrap_flag=True,
+        pane_tabs=(4, 8),
+        output_generation=42,
+    )
+    captured = (
+        "- HIST_0  \n"
+        "X \x1b[31m\x0elqqk\x0f    \n"
+        "WX ABCDEFGH\n"
+        "X \x1b[44m\t\x1b[49m1234\n"
+    )
+    res = decode_tmux_capture(
+        captured,
+        metadata=meta,
+        post_metadata=meta,
+        flagged=True,
+    )
+    assert (
+        res.completeness.exact_wraps,
+        res.completeness.exact_generation_bracket,
+    ) == (
+        True,
+        True,
+    )
+    assert TmuxLineFlags.WRAPPED in res.line_flags[2]
+    assert [r.text for r in res.snapshot.history] == ["HIST_0"]
+    assert (res.terminal[0].text, res.terminal[0, 0].style.fg) == (
+        "┌──┐",
+        AnsiColor.RED,
+    )
+    assert (res.terminal[1].wrapped, res.terminal[1, 0].style.fg) == (
+        True,
+        AnsiColor.RED,
+    )
+    assert (
+        res.terminal[2].text,
+        res.terminal[2, 0].style.bg,
+        res.terminal[2, 4].style.bg,
+    ) == ("    1234", AnsiColor.BLUE, None)
+    assert (
+        res.terminal.cursor.row,
+        res.terminal.cursor.col,
+        res.terminal.cursor.pending_wrap,
+    ) == (2, 7, True)
+    res.terminal.feed(b"\x1b[0m!\x0el\x0f")
+    assert res.terminal[2].text == "!l"
+
+
+@pytest.mark.integration
+@pytest.mark.skipif(shutil.which("tmux") is None, reason="tmux binary not installed")
+def test_live_tmux_capture_pane_roundtrip() -> None:
+    """Live ``tmux capture-pane -F -e -p -N`` reconstructs ACS, wraps, and modes."""
+    sock = f"libvt-test-{zlib.crc32(b'tmux-capture')}"
+    try:
+        subprocess.run(
+            [
+                "tmux",
+                "-L",
+                sock,
+                "-f",
+                "/dev/null",
+                "new-session",
+                "-d",
+                "-x",
+                "10",
+                "-y",
+                "3",
+                "sh",
+                "-c",
+                (
+                    "printf '\\033[?2004h\\033(0lqqk\\033(B\\r\\n"
+                    "1234567890WRAP\\r\\n\\t\\033[42mX\\033[0m'; sleep 30"
+                ),
+            ],
+            check=True,
+        )
+        for _ in range(100):
+            chk = subprocess.run(
+                ["tmux", "-L", sock, "capture-pane", "-p"],
+                check=True,
+                capture_output=True,
+                text=True,
+            )
+            if "X" in chk.stdout:
+                break
+            time.sleep(0.01)
+        else:
+            pytest.fail("timed out waiting for tmux pane output")
+        meta_raw = subprocess.run(
+            ["tmux", "-L", sock, "display-message", "-p", TMUX_METADATA_FORMAT],
+            check=True,
+            capture_output=True,
+            text=True,
+        ).stdout.rstrip("\n")
+        cap_raw = subprocess.run(
+            [
+                "tmux",
+                "-L",
+                sock,
+                "capture-pane",
+                "-S",
+                "-",
+                "-E",
+                "-",
+                "-F",
+                "-e",
+                "-p",
+                "-N",
+            ],
+            check=True,
+            capture_output=True,
+            text=True,
+        ).stdout
+        live_res = decode_tmux_capture(cap_raw, metadata=meta_raw, flagged=True)
+        assert live_res.terminal.modes.is_set(Mode.BRACKETED_PASTE) is True
+        assert [r.text for r in live_res.snapshot.history] == ["┌──┐"]
+        assert (live_res.terminal[0].text, live_res.terminal[0].wrapped) == (
+            "1234567890",
+            True,
+        )
+        assert (live_res.terminal[1].text, live_res.terminal[2].text) == (
+            "WRAP",
+            "        X",
+        )
+        assert live_res.terminal[2, 8].style.bg == AnsiColor.GREEN
+    finally:
+        subprocess.run(
+            ["tmux", "-L", sock, "kill-server"],
+            check=False,
+            capture_output=True,
+        )
diff --git a/tests/test_ucd.py b/tests/test_ucd.py
new file mode 100644
index 0000000..e94b0bd
--- /dev/null
+++ b/tests/test_ucd.py
@@ -0,0 +1,180 @@
+"""Tests for ``libvt._ucd`` Unicode 17 width, UAX #29 clustering, and BMP regex."""
+
+from __future__ import annotations
+
+import collections.abc
+import pathlib
+import time
+import typing as t
+import unicodedata
+
+import pytest
+
+import libvt
+from libvt import _ucd
+from libvt._ucd import (
+    EXT_PICT_BIT,
+    SAFE_NARROW_BMP_RE,
+    char_width,
+    display_width,
+    segment_graphemes,
+    ucd_lookup,
+)
+from libvt.config import DEFAULT_PROFILE, TMUX_PROFILE, Profile
+
+
+class DisplayWidthCase(t.NamedTuple):
+    """Typed ``display_width`` scenario under DEC ``?2027``."""
+
+    test_id: str
+    text: str
+    profile: Profile
+    expected_width: int
+
+
+DISPLAY_WIDTH_CASES: list[DisplayWidthCase] = [
+    DisplayWidthCase("ascii-ignores-vs16", "a\ufe0f", DEFAULT_PROFILE, 1),
+    DisplayWidthCase("cjk-ignores-vs15", "日\ufe0e", DEFAULT_PROFILE, 2),
+    DisplayWidthCase("heart-vs16-widens", "❤\ufe0f", DEFAULT_PROFILE, 2),
+    DisplayWidthCase("keycap-hash-vs16", "#\ufe0f\u20e3", DEFAULT_PROFILE, 2),
+    DisplayWidthCase("watch-vs15-narrows", "⌚\ufe0e", DEFAULT_PROFILE, 1),
+    DisplayWidthCase("watch-vs15-then-vs16", "⌚\ufe0e\ufe0f", DEFAULT_PROFILE, 1),
+    DisplayWidthCase("watch-mark-blocks-vs15", "⌚\u0301\ufe0e", DEFAULT_PROFILE, 2),
+    DisplayWidthCase("watch-vs15-tmux-stays-wide", "⌚\ufe0e", TMUX_PROFILE, 2),
+    DisplayWidthCase("devanagari-conjunct", "क्ष", DEFAULT_PROFILE, 2),
+    DisplayWidthCase("bengali-split-vowel", "\u0995\u09cb", DEFAULT_PROFILE, 2),
+    DisplayWidthCase("arabic-prepend-digit", "\u06001", DEFAULT_PROFILE, 1),
+    DisplayWidthCase("hangul-jamo-lvt", "\u1100\u1161\u11a8", DEFAULT_PROFILE, 2),
+]
+
+
+@pytest.mark.parametrize(
+    "case",
+    DISPLAY_WIDTH_CASES,
+    ids=[c.test_id for c in DISPLAY_WIDTH_CASES],
+)
+def test_display_width_cases(case: DisplayWidthCase) -> None:
+    """``display_width`` obeys ``?2027`` UAX #29 and variation-selector rules."""
+    assert display_width(case.text, profile=case.profile) == case.expected_width
+
+
+def test_unicode_17_grapheme_break_vectors() -> None:
+    """All 766 official Unicode 17.0.0 ``GraphemeBreakTest.txt`` vectors pass."""
+    fixture = (
+        pathlib.Path(__file__).resolve().parent
+        / "fixtures"
+        / "GraphemeBreakTest-17.0.0.txt"
+    )
+    count = 0
+    for raw in fixture.read_text(encoding="utf-8").splitlines():
+        line = raw.split("#", 1)[0].strip()
+        if not line:
+            continue
+        expected = [
+            "".join(chr(int(tok, 16)) for tok in chunk.strip().split("\u00d7"))
+            for chunk in line.split("\u00f7")
+            if chunk.strip()
+        ]
+        assert segment_graphemes("".join(expected)) == expected, raw
+        count += 1
+    assert count == 766
+
+
+def test_unicode_17_stdlib_stage_table_parity() -> None:
+    """Every ``_STAGE2`` block and ``_STAGE1`` slot matches ``unicodedata`` 17.0."""
+    if unicodedata.unidata_version != "17.0.0" or not hasattr(
+        unicodedata,
+        "grapheme_cluster_break",
+    ):
+        return
+
+    gcb_names = (
+        "Other",
+        "CR",
+        "LF",
+        "Control",
+        "Extend",
+        "ZWJ",
+        "Regional_Indicator",
+        "Prepend",
+        "SpacingMark",
+        "L",
+        "V",
+        "T",
+        "LV",
+        "LVT",
+    )
+    incb_names = ("None", "Linker", "Consonant", "Extend")
+    gcb_fn = unicodedata.grapheme_cluster_break
+    incb_fn = unicodedata.indic_conjunct_break
+    ep_fn = unicodedata.extended_pictographic
+
+    seen_blocks: set[int] = set()
+    for hi, block_id in enumerate(_ucd._STAGE1):
+        offsets: collections.abc.Iterable[int]
+        if block_id not in seen_blocks:
+            seen_blocks.add(block_id)
+            offsets = range(256)
+        else:
+            offsets = (0x00, 0x7F, 0x80, 0xFF)
+        base = hi << 8
+        for lo in offsets:
+            cp = base | lo
+            if 0xD800 <= cp <= 0xDFFF:
+                continue
+            ch = chr(cp)
+            word = ucd_lookup(cp)
+            assert gcb_names[(word >> 2) & 0x0F] == gcb_fn(ch), hex(cp)
+            assert incb_names[(word >> 6) & 0x03] == incb_fn(ch), hex(cp)
+            assert bool(word & EXT_PICT_BIT) == ep_fn(ch), hex(cp)
+
+
+def test_safe_narrow_bmp_regex_and_streaming_clusters() -> None:
+    """``SAFE_NARROW_BMP_RE`` covers narrow BMP runs and matches scalar feeding."""
+    assert (char_width("\u09cb"), char_width("\u1161"), char_width("\u0600")) == (
+        0,
+        0,
+        0,
+    )
+    bmp_all = "".join(chr(cp) for cp in range(0x10000) if not (0xD800 <= cp <= 0xDFFF))
+    matched_count = sum(len(m.group(0)) for m in SAFE_NARROW_BMP_RE.finditer(bmp_all))
+    assert matched_count >= 18_000
+    for sample in ("┌", "─", "│", "█", "Ω", "д", "→", "⠿"):
+        assert SAFE_NARROW_BMP_RE.match(sample) is not None
+    for unsafe in (
+        "\u0301",
+        "\ufe0f",
+        "\u200d",
+        "中",
+        "\u202e",
+        "\x00",
+        "\x7f",
+        "\x85",
+    ):
+        assert SAFE_NARROW_BMP_RE.match(unsafe) is None
+
+    mixed = "┌── Ωμέγα 🚀 Кириллица ──┐#1\ufe0f\u20e3*2\ufe0f🇯🇵🧑‍🌾क्ष"
+    bulk = libvt.Terminal(rows=4, cols=16)
+    bulk.feed_str(mixed)
+    scalar = libvt.Terminal(rows=4, cols=16)
+    for b in mixed.encode("utf-8"):
+        scalar.feed(bytes([b]))
+    assert (bulk.lines, bulk.cursor) == (scalar.lines, scalar.cursor)
+
+    # Disabling ?2027 leaves narrow base + VS16 at width 1.
+    legacy = libvt.Terminal(rows=2, cols=6)
+    legacy.feed(b"\x1b[?2027l" + "❤\ufe0fX".encode())
+    assert (legacy[0, 0].width, legacy[0, 1].text) == (1, "X")
+
+
+def test_combining_mark_cap_and_cluster_anchor_invalidation() -> None:
+    """Combining floods stay ``O(1)`` capped and cursor moves clear cluster anchors."""
+    term = libvt.Terminal(rows=2, cols=10)
+    t0 = time.perf_counter()
+    term.feed(("a" + ("\u0301" * 1_000)).encode("utf-8"))
+    assert time.perf_counter() - t0 < 0.1
+    assert len(term[0, 0].text) == term.limits.max_grapheme_codepoints
+
+    term.reset()
+    term.feed(b"ab\x1b[1;1H" + "\u0301".encode())
+    assert (term[0, 0].text, term[0, 1].text) == ("a", "b")
diff --git a/tests/test_ucd_and_grid.py b/tests/test_ucd_and_grid.py
deleted file mode 100644
index 69c0430..0000000
--- a/tests/test_ucd_and_grid.py
+++ /dev/null
@@ -1,354 +0,0 @@
-"""Unicode 17 clustering, cell-grid invariants, RLE scrollback, and fuzz tests."""
-
-from __future__ import annotations
-
-import pathlib
-import random
-import time
-import unicodedata
-
-import libvt
-from libvt._ucd import (
-    EXT_PICT_BIT,
-    WidthRole,
-    char_width,
-    display_width,
-    segment_graphemes,
-    ucd_lookup,
-)
-from libvt.config import TMUX_PROFILE, XTERM_PROFILE
-from libvt.modes import Mode
-from libvt.terminal import Formatter, OutputFormat
-
-
-def test_unicode_17_grapheme_break_test_vectors() -> None:
-    """All 766 official Unicode 17.0.0 ``GraphemeBreakTest.txt`` vectors pass."""
-    fixture = (
-        pathlib.Path(__file__).resolve().parent
-        / "fixtures"
-        / "GraphemeBreakTest-17.0.0.txt"
-    )
-    count = 0
-    for raw in fixture.read_text(encoding="utf-8").splitlines():
-        line = raw.split("#", 1)[0].strip()
-        if not line:
-            continue
-        expected: list[str] = []
-        for chunk in line.split("\u00f7"):
-            chunk = chunk.strip()
-            if not chunk:
-                continue
-            expected.append(
-                "".join(chr(int(tok, 16)) for tok in chunk.split("\u00d7")),
-            )
-        text = "".join(expected)
-        assert segment_graphemes(text) == expected, raw
-        count += 1
-    assert count == 766
-
-
-def test_unicode_17_stdlib_parity_when_available() -> None:
-    """Verify 0 property mismatches against Python 3.15+ Unicode 17 ``unicodedata``."""
-    if unicodedata.unidata_version != "17.0.0" or not hasattr(
-        unicodedata, "grapheme_cluster_break"
-    ):
-        return
-
-    gcb_names = (
-        "Other",
-        "CR",
-        "LF",
-        "Control",
-        "Extend",
-        "ZWJ",
-        "Regional_Indicator",
-        "Prepend",
-        "SpacingMark",
-        "L",
-        "V",
-        "T",
-        "LV",
-        "LVT",
-    )
-    incb_names = ("None", "Linker", "Consonant", "Extend")
-    gcb_fn = unicodedata.grapheme_cluster_break
-    incb_fn = unicodedata.indic_conjunct_break
-    ep_fn = unicodedata.extended_pictographic
-
-    for cp in range(0x110000):
-        if 0xD800 <= cp <= 0xDFFF:
-            continue
-        ch = chr(cp)
-        word = ucd_lookup(cp)
-        assert gcb_names[(word >> 2) & 0x0F] == gcb_fn(ch), hex(cp)
-        assert incb_names[(word >> 6) & 0x03] == incb_fn(ch), hex(cp)
-        assert bool(word & EXT_PICT_BIT) == ep_fn(ch), hex(cp)
-
-
-def test_unicode_width_flags_zwj_incb_and_variation_selectors() -> None:
-    """Flags, ZWJ emoji, Indic conjuncts, and VS15/VS16 obey ``?2027`` width rules."""
-    # Non-emoji bases (ASCII 'a', CJK '日') ignore VS16/VS15 width overrides!
-    assert display_width("a\ufe0f") == 1
-    assert display_width("日\ufe0e") == 2
-    assert display_width("❤\ufe0f") == 2
-    assert display_width("#\ufe0f\u20e3") == 2
-    assert display_width("⌚\ufe0e") == 1
-    assert display_width("⌚\ufe0e\ufe0f") == 1
-    assert display_width("⌚\u0301\ufe0e") == 2
-    assert display_width("⌚\ufe0e", profile=TMUX_PROFILE) == 2
-    assert display_width("क्ष") == 2
-    assert display_width("स्त्र") == 2
-    assert display_width("\u0995\u09cb") == 2
-    assert char_width("\u09cb") == 0
-    assert char_width("\u1161") == 0
-    assert char_width("\u0600") == 0
-    assert display_width("\u06001") == 1
-    assert display_width("\u1100\u1161\u11a8") == 2
-
-    term = libvt.Terminal(rows=4, cols=10)
-    term.feed("🇯🇵🇺🇸!".encode())
-    assert term.cursor.col == 5
-    assert term[0, 0].text == "🇯🇵"
-    assert term[0, 0].width == 2
-    assert term[0, 2].text == "🇺🇸"
-    assert term[0, 2].width == 2
-    assert term[0, 4].text == "!"
-
-    # Streaming 1-byte chunks of ZWJ emoji and Indic conjuncts.
-    term.reset()
-    for b in "🧑‍🌾क्षA".encode():
-        term.feed(bytes([b]))
-    assert term[0, 0].text == "🧑‍🌾"
-    assert term[0, 0].width == 2
-    assert term[0, 2].text == "क्ष"
-    assert term[0, 2].width == 2
-    assert term[0, 4].text == "A"
-
-    # Prepend + narrow ASCII stays 1 column on Terminal as well as display_width.
-    term.reset()
-    term.feed_str("\u06001!")
-    assert term[0, 0].text == "\u06001"
-    assert term[0, 0].width == 1
-    assert term[0, 1].text == "!"
-
-    # TMUX_PROFILE preserves width 2 on VS15 (matching live tmux 3.8a).
-    tmux_term = libvt.Terminal(rows=2, cols=10, profile=TMUX_PROFILE)
-    tmux_term.feed_str("⌚\ufe0e!")
-    assert tmux_term[0, 0].width == 2
-    assert tmux_term.cursor.col == 3
-    assert XTERM_PROFILE.name == "xterm"
-
-    # VS16 widening at right margin (col == cols - 1) wraps cleanly with SPACER_HEAD.
-    narrow_term = libvt.Terminal(rows=3, cols=4)
-    narrow_term.feed("abc❤️".encode())
-    assert narrow_term[0].text == "abc"
-    assert narrow_term[0].wrapped is True
-    assert narrow_term[0, 3].width_role == WidthRole.SPACER_HEAD
-    assert narrow_term[1, 0].text == "❤️"
-    assert narrow_term[1, 0].width == 2
-    assert narrow_term.cursor.row == 1
-    assert narrow_term.cursor.col == 2
-
-    # Overwriting (1, 0) with narrow 'Z' heals (0, 3) SPACER_HEAD and clears wrapped!
-    narrow_term.feed(b"\x1b[2;1HZ")
-    assert narrow_term[0, 3].width_role == WidthRole.NARROW
-    assert narrow_term[0, 3].text == " "
-    assert narrow_term[0].wrapped is False
-    assert narrow_term[1, 0].text == "Z"
-    assert narrow_term[1, 1].text == " "
-    assert narrow_term[1, 1].width_role == WidthRole.NARROW
-    vt_replayed = libvt.render(
-        Formatter(OutputFormat.VT).format_snapshot(narrow_term.snapshot()),
-        rows=3,
-        cols=8,
-    )
-    narrow_term.resize(rows=3, cols=8)
-    assert narrow_term.text == "abc\nZ"
-    assert vt_replayed == narrow_term.text
-    narrow_term.resize(rows=3, cols=4)
-    assert narrow_term.screen._rows[0].used == 3
-
-    # Wide-to-wide CUP overwrite at (1, 0) also repairs pre-edit SPACER_HEAD!
-    w2w_term = libvt.Terminal(rows=3, cols=4)
-    w2w_term.feed_str("abc❤️")
-    w2w_term.feed_str("\x1b[2;1H日")
-    assert w2w_term[0, 3].width_role == WidthRole.NARROW
-    assert w2w_term[0].wrapped is False
-    assert w2w_term[1, 0].text == "日"
-
-    # BCE EL 0 with colored background keeps background style without padding .text!
-    bce_term = libvt.Terminal(rows=3, cols=80)
-    bce_term.feed(b"\x1b[44mfoo\x1b[K\r\nbar")
-    assert bce_term[0].text == "foo"
-    assert bce_term[1].text == "bar"
-    assert bce_term[0, 10].style.bg is not None
-    bce_term.resize(rows=3, cols=40)
-    assert bce_term[0].text == "foo"
-    assert bce_term[1].text == "bar"
-
-    # RowView stays anchored to viewport row coordinates across scroll recycling!
-    scroll_term = libvt.Terminal(rows=2, cols=10, scrollback=5)
-    scroll_term.feed(b"row-0\r\nrow-1")
-    top_view = scroll_term[0]
-    assert top_view.text == "row-0"
-    scroll_term.feed(b"\r\nrow-2")
-    assert top_view.text == "row-1"
-
-    # Disabling ?2027 leaves narrow base + VS16 at width 1.
-    legacy = libvt.Terminal(rows=2, cols=6)
-    legacy.feed(b"\x1b[?2027l" + "❤\ufe0fX".encode())
-    assert legacy[0, 0].width == 1
-    assert legacy[0, 1].text == "X"
-
-
-def test_combining_mark_cap_and_cluster_anchor_invalidation() -> None:
-    """Combining floods stay O(1) capped and cursor moves clear cluster anchors."""
-    term = libvt.Terminal(rows=4, cols=10)
-    t0 = time.perf_counter()
-    term.feed(("a" + ("\u0301" * 5_000)).encode("utf-8"))
-    elapsed = time.perf_counter() - t0
-    assert elapsed < 0.25
-    assert len(term[0, 0].text) == term.limits.max_grapheme_codepoints
-
-    term.reset()
-    term.feed(b"ab")
-    term.feed(b"\x1b[1;1H" + "\u0301".encode())
-    assert term[0, 0].text == "a"
-    assert term[0, 1].text == "b"
-
-
-def test_row_clear_range_ich_dch_wide_healing_and_frozen_rle() -> None:
-    """Explicit spaces survive ``EL 0``, ``ICH``/``DCH`` heal pairs, and RLE works."""
-    term = libvt.Terminal(rows=3, cols=6, scrollback=20)
-    term.feed(b"   \x1b[K")
-    assert term.screen._rows[0].used == 3
-
-    # DCH clears pending_wrap and clears wrapped when shifting to right edge.
-    term.reset()
-    term.feed(b"12345678")
-    assert term[0].wrapped is True
-    term.feed(b"\x1b[1;6H!\x1b[P")
-    assert term.cursor.pending_wrap is False
-    assert term[0].wrapped is False
-    assert term[0].text == "12345"
-
-    term.reset()
-    term.feed("日本語".encode())
-    term.feed(b"\x1b[1;2H\x1b[1@")
-    _assert_grid_invariants(term)
-
-    term.reset()
-    term.feed("日本語".encode())
-    term.feed(b"\x1b[1;2H\x1b[2P")
-    _assert_grid_invariants(term)
-
-    term.reset()
-    for idx in range(8):
-        term.feed(f"\x1b[38;2;10;20;{idx * 20}m日{idx}\r\n".encode())
-    assert len(term.history) >= 5
-    hist_row = term.history[0]
-    assert hist_row.text == "日0"
-    assert hist_row[0].text == "日"
-    assert hist_row[0].width == 2
-    assert len(hist_row.runs) >= 1
-
-
-def _assert_grid_invariants(term: libvt.Terminal) -> None:
-    """Assert cursor bounds and wide-cell head/tail/spacer_head invariants."""
-    scr = term.screen
-    declrmm = term.modes.is_set(Mode.DECLRMM)
-    assert 0 <= scr.cursor.row < scr.rows
-    assert 0 <= scr.cursor.col < scr.cols
-    for r_idx, raw_row in enumerate(scr._rows):
-        assert len(raw_row.chars) == scr.cols
-        assert 0 <= raw_row.used <= scr.cols
-        if raw_row.attrs is None:
-            continue
-        for c_idx in range(scr.cols):
-            role = WidthRole((raw_row.attrs[c_idx] >> 60) & 0b11)
-            if role == WidthRole.WIDE:
-                assert c_idx + 1 < scr.cols, f"orphan WIDE at ({r_idx}, {c_idx})"
-                tail_role = WidthRole((raw_row.attrs[c_idx + 1] >> 60) & 0b11)
-                assert tail_role == WidthRole.SPACER_TAIL
-            elif role == WidthRole.SPACER_TAIL:
-                assert c_idx > 0, f"orphan SPACER_TAIL at ({r_idx}, 0)"
-                head_role = WidthRole((raw_row.attrs[c_idx - 1] >> 60) & 0b11)
-                assert head_role == WidthRole.WIDE
-            elif (
-                role == WidthRole.SPACER_HEAD
-                and not declrmm
-                and c_idx == scr.cols - 1
-                and r_idx + 1 < scr.rows
-                and raw_row.wrapped
-            ):
-                next_row = scr._rows[r_idx + 1]
-                next_role = (
-                    WidthRole((next_row.attrs[0] >> 60) & 0b11)
-                    if next_row.attrs is not None
-                    else WidthRole.NARROW
-                )
-                assert next_role == WidthRole.WIDE, (
-                    f"stale SPACER_HEAD at ({r_idx}, {c_idx}) before {next_role}"
-                )
-
-
-def test_randomized_invariants_400_trials() -> None:
-    """400-trial seeded fuzzing preserves grid, wide-spacer, and cursor invariants."""
-    rng = random.Random(20261121)
-    tokens: tuple[bytes, ...] = (
-        b"abc",
-        "日本".encode(),
-        "🧑‍🌾".encode(),
-        "🇯🇵".encode(),
-        "❤\ufe0f".encode(),
-        "a\u0301".encode(),
-        b"\r",
-        b"\n",
-        b"\x08",
-        b"\t",
-        b"\x1b[A",
-        b"\x1b[B",
-        b"\x1b[C",
-        b"\x1b[D",
-        b"\x1b[Z",
-        b"\x1b[I",
-        b"\x1b[2@",
-        b"\x1b[2P",
-        b"\x1b[2X",
-        b"\x1b[K",
-        b"\x1b[1K",
-        b"\x1b[2K",
-        b"\x1b[J",
-        b"\x1b[L",
-        b"\x1b[M",
-        b"\x1b[2;5r",
-        b"\x1b[r",
-        b"\x1b[?69h\x1b[2;7s",
-        b"\x1b[?69l",
-        b"\x1b(0lqqqk\x1b(B",
-        b"\x1b[38;2;12;34;56;4:3m",
-        b"\x1b[0m",
-        b"\x1b[?1049h",
-        b"\x1b[?1049l",
-        b"\x1b[?2026h",
-        b"\x1b[?2026l",
-    )
-
-    for trial in range(400):
-        rows = rng.choice((4, 6, 8))
-        cols = rng.choice((6, 8, 12))
-        term = libvt.Terminal(rows=rows, cols=cols, scrollback=50)
-        stream = b"".join(rng.choice(tokens) for _ in range(32))
-        idx = 0
-        while idx < len(stream):
-            step = rng.randint(1, 9)
-            term.feed(stream[idx : idx + step])
-            idx += step
-            _assert_grid_invariants(term)
-        if trial % 5 == 0:
-            term.resize(rows=rng.choice((3, 6, 9)), cols=rng.choice((5, 8, 14)))
-            _assert_grid_invariants(term)
-        if term.modes.is_set(Mode.ALT_SCREEN):
-            term.feed(b"\x1b[?1049l")
-        snap = term.snapshot()
-        assert snap.rows == term.rows

From feccc670ecf0a0f325eedeeede65e329f309cb07 Mon Sep 17 00:00:00 2001
From: Tony Narlock 
Date: Sun, 22 Nov 2026 14:35:03 -0600
Subject: [PATCH 24/29] tmux(fix[capture]): Support pre-3.8 capture-pane (#18)

why: GitHub Actions ubuntu-latest ships tmux < 3.8 without capture-pane
-F, and TMUX_METADATA_FORMAT queried synchronize-panes instead of DEC
?2026 synchronized_output_flag.

what:
- Query #{synchronized_output_flag} in TMUX_METADATA_FORMAT
- Fall back from capture-pane -F to -e -p -N plus -p -J in the live tmux
  integration test when running against tmux < 3.8
---
 src/libvt/tmux.py  |  5 +++--
 tests/test_tmux.py | 51 +++++++++++++++++++++++++++++++++++++++-------
 2 files changed, 47 insertions(+), 9 deletions(-)

diff --git a/src/libvt/tmux.py b/src/libvt/tmux.py
index c2ce13b..8c20bdd 100644
--- a/src/libvt/tmux.py
+++ b/src/libvt/tmux.py
@@ -34,7 +34,7 @@
     "#{bracket_paste_flag}\t#{mouse_standard_flag}\t#{mouse_button_flag}\t"
     "#{mouse_all_flag}\t#{mouse_sgr_flag}\t#{pane_private_modes}\t"
     "#{pane_tabs}\t#{history_size}\t#{history_limit}\t"
-    "#{pane_synchronized}\t#{pane_output_generation}\t"
+    "#{synchronized_output_flag}\t#{pane_output_generation}\t"
     "#{pane_current_path}\t#{pane_title}"
 )
 
@@ -223,7 +223,8 @@ class TmuxPaneMetadata:
     history_limit : int
         Pane ``history-limit`` (``#{history_limit}``).
     synchronized : bool
-        ``?2026`` synchronized-output hold state (``#{pane_synchronized}``).
+        ``?2026`` synchronized-output hold state
+        (``#{synchronized_output_flag}``).
     output_generation : int | None
         ``#{pane_output_generation}`` counter on ``tmux >= 3.8``, else ``None``.
     cwd : str
diff --git a/tests/test_tmux.py b/tests/test_tmux.py
index 8b9d9f1..2f90c12 100644
--- a/tests/test_tmux.py
+++ b/tests/test_tmux.py
@@ -32,6 +32,7 @@ def test_control_mode_unescape_and_metadata_format_parsing() -> None:
     assert "#{bracket_paste_flag}" in TMUX_METADATA_FORMAT
     assert "#{mouse_all_flag}" in TMUX_METADATA_FORMAT
     assert "#{pane_private_modes}" in TMUX_METADATA_FORMAT
+    assert "#{synchronized_output_flag}" in TMUX_METADATA_FORMAT
     raw_fmt = (
         "8\t3\t0\t2\t1\t0\t4294967295\t4294967295\t0\t2\t"
         "0\t0\t1\t0\t1\t0\t0\t1\t1\t1004,2004\t"
@@ -140,7 +141,7 @@ def test_capture_decoder_acs_tabs_joined_wraps_and_prompt_zones() -> None:
 @pytest.mark.integration
 @pytest.mark.skipif(shutil.which("tmux") is None, reason="tmux binary not installed")
 def test_live_tmux_capture_pane_roundtrip() -> None:
-    """Live ``tmux capture-pane -F -e -p -N`` reconstructs ACS, wraps, and modes."""
+    """Live ``tmux capture-pane`` reconstructs ACS, wraps, tabs, and modes."""
     sock = f"libvt-test-{zlib.crc32(b'tmux-capture')}"
     try:
         subprocess.run(
@@ -159,7 +160,7 @@ def test_live_tmux_capture_pane_roundtrip() -> None:
                 "sh",
                 "-c",
                 (
-                    "printf '\\033[?2004h\\033(0lqqk\\033(B\\r\\n"
+                    "printf '\\033[?1000h\\033(0lqqk\\033(B\\r\\n"
                     "1234567890WRAP\\r\\n\\t\\033[42mX\\033[0m'; sleep 30"
                 ),
             ],
@@ -183,7 +184,7 @@ def test_live_tmux_capture_pane_roundtrip() -> None:
             capture_output=True,
             text=True,
         ).stdout.rstrip("\n")
-        cap_raw = subprocess.run(
+        flagged_proc = subprocess.run(
             [
                 "tmux",
                 "-L",
@@ -198,12 +199,48 @@ def test_live_tmux_capture_pane_roundtrip() -> None:
                 "-p",
                 "-N",
             ],
-            check=True,
+            check=False,
             capture_output=True,
             text=True,
-        ).stdout
-        live_res = decode_tmux_capture(cap_raw, metadata=meta_raw, flagged=True)
-        assert live_res.terminal.modes.is_set(Mode.BRACKETED_PASTE) is True
+        )
+        if flagged_proc.returncode == 0:
+            live_res = decode_tmux_capture(
+                flagged_proc.stdout,
+                metadata=meta_raw,
+                flagged=True,
+            )
+        else:
+            cap_raw = subprocess.run(
+                [
+                    "tmux",
+                    "-L",
+                    sock,
+                    "capture-pane",
+                    "-S",
+                    "-",
+                    "-E",
+                    "-",
+                    "-e",
+                    "-p",
+                    "-N",
+                ],
+                check=True,
+                capture_output=True,
+                text=True,
+            ).stdout
+            joined_raw = subprocess.run(
+                ["tmux", "-L", sock, "capture-pane", "-S", "-", "-E", "-", "-p", "-J"],
+                check=True,
+                capture_output=True,
+                text=True,
+            ).stdout
+            live_res = decode_tmux_capture(
+                cap_raw,
+                metadata=meta_raw,
+                flagged=False,
+                joined_capture=joined_raw,
+            )
+        assert live_res.terminal.modes.is_set(Mode.MOUSE_VT200) is True
         assert [r.text for r in live_res.snapshot.history] == ["┌──┐"]
         assert (live_res.terminal[0].text, live_res.terminal[0].wrapped) == (
             "1234567890",

From d1ab911f588fe039cec12fe2bafa23427053476f Mon Sep 17 00:00:00 2001
From: Tony Narlock 
Date: Sun, 22 Nov 2026 15:16:18 -0600
Subject: [PATCH 25/29] tmux(fix[capture]): Decode ACS and tabs in -J wraps
 (#18)

---
 src/libvt/config.py |   2 +-
 src/libvt/parser.py |   6 +-
 src/libvt/tmux.py   | 141 ++++++++++++++++++++++++++++++++---------
 tests/test_tmux.py  | 151 ++++++++++++++++++++++++++++----------------
 4 files changed, 215 insertions(+), 85 deletions(-)

diff --git a/src/libvt/config.py b/src/libvt/config.py
index 0e831d0..de514d5 100644
--- a/src/libvt/config.py
+++ b/src/libvt/config.py
@@ -331,7 +331,7 @@ class Limits:
 TMUX_PROFILE = Profile.tmux("3.8a")
 LINUX_CONSOLE_PROFILE = Profile.linux_console()
 DEFAULT_POLICY = Policy()
-TMUX_CAPTURE_POLICY = Policy(allow_passthrough=True)
+TMUX_CAPTURE_POLICY = Policy(allow_passthrough=False)
 DEFAULT_LIMITS = Limits()
 
 __all__ = [
diff --git a/src/libvt/parser.py b/src/libvt/parser.py
index 2ff2d81..d1a48b7 100644
--- a/src/libvt/parser.py
+++ b/src/libvt/parser.py
@@ -479,7 +479,11 @@ def parse_sgr(
             sub_ul = grp[1] if len(grp) >= 2 else 1
             underline = _UL_MAP.get(sub_ul, UnderlineStyle.SINGLE)
         elif code in (5, 6):
-            blink = True
+            if code == 5 and len(grp) == 2 and grp[1] == 3:
+                # Work around tmux grid_string_cells_code encoding SGR 53 as 5:3m.
+                overline = True
+            else:
+                blink = True
         elif code == 7:
             reverse = True
         elif code == 8:
diff --git a/src/libvt/tmux.py b/src/libvt/tmux.py
index 8c20bdd..a6bab9a 100644
--- a/src/libvt/tmux.py
+++ b/src/libvt/tmux.py
@@ -416,11 +416,12 @@ def on_print(self, text: str) -> None:
     def on_execute(self, byte: int) -> None:
         if byte == 0x09:
             cur_col = self._scratch.screen._cur_col
-            nxt = next(
-                (t_col for t_col in self._tabstops if cur_col < t_col < self._cols),
-                self._cols,
+            mod_col = cur_col % self._cols if self._cols > 0 else cur_col
+            nxt_mod = next(
+                (t_col for t_col in self._tabstops if mod_col < t_col < self._cols),
+                max(mod_col, self._cols - 1),
             )
-            span = max(1, min(self._cols - cur_col, nxt - cur_col))
+            span = max(1, nxt_mod - mod_col)
             self._scratch._handle_print(" " * span)
             return
         if byte in (0x0E, 0x0F):
@@ -478,19 +479,66 @@ def _row_trimmed_text_and_cols(row: _Row) -> tuple[str, int]:
     return "".join(row.chars[:t_end]), t_end
 
 
+def _decode_joined_lines(
+    joined_raw: CaptureInput,
+    *,
+    stripped_trailing: int = 0,
+    max_physical_rows: int,
+    cols: int,
+    tabstops: tuple[int, ...],
+    profile: Profile,
+    policy: Policy,
+    limits: Limits,
+) -> list[str]:
+    raw_lines = _split_capture_lines(joined_raw)
+    if (
+        stripped_trailing > 0
+        and isinstance(joined_raw, collections.abc.Sequence)
+        and not isinstance(joined_raw, (str, bytes, bytearray))
+    ):
+        raw_lines.extend([""] * stripped_trailing)
+    if not raw_lines:
+        return []
+    max_span = max(1, min(64, max_physical_rows - len(raw_lines) + 2))
+    wide_cols = max(cols, cols * max_span)
+    scratch = Terminal(
+        rows=1,
+        cols=wide_cols,
+        scrollback=0,
+        profile=profile,
+        policy=policy,
+        limits=limits,
+    )
+    scratch.modes.set_mode(Mode.DECAWM, enabled=False)
+    scratch._g_sets = ["B", "0", "B", "B"]
+    scratch._gl = 0
+    parser = Parser(limits=limits)
+    sink = _CaptureRowSink(scratch, cols, tabstops)
+    out: list[str] = []
+    for ln in raw_lines:
+        row = scratch.screen._rows[0]
+        row.reset_blank(wide_cols)
+        scratch._set_cursor(scratch.screen, 0, 0, pending_wrap=False)
+        parser.reset()
+        parser.feed_to(ln.encode("utf-8", errors="surrogateescape"), sink)
+        txt, _ = _row_trimmed_text_and_cols(row)
+        out.append(txt)
+    return out
+
+
 def _infer_wraps_from_joined(
     plain_rows: list[str],
     row_used_cols: list[int],
-    joined_raw: CaptureInput,
+    joined_lines: list[str],
     cols: int,
-) -> list[bool] | None:
-    joined_lines = _split_capture_lines(joined_raw)
+) -> tuple[list[bool], list[bool]] | None:
     n = len(plain_rows)
     if len(joined_lines) == n:
-        return [False] * n
+        return [False] * n, [False] * n
     if len(joined_lines) > n:
         return None
     wraps = [False] * n
+    spacer_heads = [False] * n
     r_idx = 0
     for j_line in joined_lines:
         if r_idx >= n or not j_line.startswith(plain_rows[r_idx]):
@@ -499,24 +547,23 @@ def _infer_wraps_from_joined(
         while r_idx + 1 < n and pos < len(j_line):
             pad = max(0, cols - row_used_cols[r_idx])
             nxt = plain_rows[r_idx + 1]
-            if (
-                pad > 0
-                and j_line.startswith(" " * pad, pos)
-                and j_line.startswith(nxt, pos + pad)
-            ):
-                wraps[r_idx] = True
-                pos += pad + len(nxt)
-                r_idx += 1
-            elif j_line.startswith(nxt, pos):
-                wraps[r_idx] = True
-                pos += len(nxt)
-                r_idx += 1
-            else:
+            matched_k = -1
+            for k in range(pad, -1, -1):
+                if (k == 0 or j_line.startswith(" " * k, pos)) and j_line.startswith(
+                    nxt, pos + k
+                ):
+                    matched_k = k
+                    break
+            if matched_k < 0:
                 break
+            wraps[r_idx] = True
+            spacer_heads[r_idx] = (pad - matched_k) == 1
+            pos += matched_k + len(nxt)
+            r_idx += 1
         if pos != len(j_line):
             return None
         r_idx += 1
-    return wraps if r_idx == n else None
+    return (wraps, spacer_heads) if r_idx == n else None
 
 
 def _trim_unwrapped_row(row: _Row) -> None:
@@ -540,6 +587,7 @@ def _populate_screen_from_lines(
     tabstops: tuple[int, ...],
     flagged: bool,
     joined_capture: CaptureInput | None,
+    stripped_trailing: int = 0,
     profile: Profile,
     policy: Policy,
     limits: Limits,
@@ -581,6 +629,7 @@ def _populate_screen_from_lines(
         decoded_rows.append(scratch_row.clone())
 
     row_wraps: list[bool]
+    inferred_spacers: list[bool] | None = None
     exact_wraps = flagged
     if flagged:
         row_wraps = [bool(fl & TmuxLineFlags.WRAPPED) for fl in flags_list]
@@ -588,12 +637,22 @@ def _populate_screen_from_lines(
         trimmed_pairs = [_row_trimmed_text_and_cols(r) for r in decoded_rows]
         plain_texts = [pair[0] for pair in trimmed_pairs]
         used_cols = [pair[1] for pair in trimmed_pairs]
+        decoded_joined = _decode_joined_lines(
+            joined_capture,
+            stripped_trailing=stripped_trailing,
+            max_physical_rows=len(decoded_rows),
+            cols=cols,
+            tabstops=tabstops,
+            profile=profile,
+            policy=policy,
+            limits=limits,
+        )
         inferred = _infer_wraps_from_joined(
-            plain_texts, used_cols, joined_capture, cols
+            plain_texts, used_cols, decoded_joined, cols
         )
         if inferred is not None:
             exact_wraps = True
-            row_wraps = inferred
+            row_wraps, inferred_spacers = inferred
         else:
             row_wraps = [False] * len(decoded_rows)
     else:
@@ -607,10 +666,22 @@ def _populate_screen_from_lines(
     for i in range(len(decoded_rows) - 1):
         cur_r = decoded_rows[i]
         nxt_r = decoded_rows[i + 1]
-        if cur_r.wrapped and raw_width_bits(nxt_r.attr_at(0)) == int(WidthRole.WIDE):
-            _, trimmed_cols = _row_trimmed_text_and_cols(cur_r)
-            if trimmed_cols == cols - 1:
-                cur_r.write_spacer_head(cols - 1, 0, None)
+        if (
+            cols > 0
+            and cur_r.wrapped
+            and raw_width_bits(nxt_r.attr_at(0)) == int(WidthRole.WIDE)
+        ):
+            if inferred_spacers is not None:
+                is_spacer = inferred_spacers[i]
+            else:
+                _, trimmed_cols = _row_trimmed_text_and_cols(cur_r)
+                is_spacer = trimmed_cols == cols - 1
+            if is_spacer:
+                cur_r.write_spacer_head(
+                    cols - 1,
+                    cur_r.attr_at(cols - 1),
+                    cur_r.ext_at(cols - 1),
+                )
                 cur_r.wrapped = True
 
     total = len(decoded_rows)
@@ -704,7 +775,7 @@ def decode_tmux_capture(
     flagged : bool
         ``True`` when *captured* includes ``capture-pane -F`` line prefixes.
     joined_capture : CaptureInput | None
-        Optional ``capture-pane -S - -E - -p -J`` output used to infer soft
+        Optional ``capture-pane -S - -E - -e -p -J`` output used to infer soft
         wraps on ``tmux < 3.8`` when ``flagged=False``.
     saved_primary_capture : CaptureInput | None
         Optional ``capture-pane -a -q -S - -E - -e -p -N [-F]`` output restoring
@@ -769,6 +840,17 @@ def decode_tmux_capture(
     term._tabstops_from_list(term.screens.alternate, tabstops)
 
     raw_lines = _split_capture_lines(captured)
+    stripped_trailing = 0
+    if (
+        not meta.alternate_on
+        and metadata is not None
+        and not flagged
+        and meta.history_size > 0
+        and len(raw_lines) > meta.history_size
+        and len(raw_lines) < meta.history_size + eff_rows
+    ):
+        stripped_trailing = meta.history_size + eff_rows - len(raw_lines)
+        raw_lines.extend([""] * stripped_trailing)
     if meta.alternate_on:
         if saved_primary_capture is not None:
             prim_lines = _split_capture_lines(saved_primary_capture)
@@ -831,6 +913,7 @@ def decode_tmux_capture(
             tabstops=tabstops,
             flagged=flagged,
             joined_capture=joined_capture,
+            stripped_trailing=stripped_trailing,
             profile=profile,
             policy=policy,
             limits=limits,
diff --git a/tests/test_tmux.py b/tests/test_tmux.py
index 2f90c12..811a108 100644
--- a/tests/test_tmux.py
+++ b/tests/test_tmux.py
@@ -59,25 +59,51 @@ def test_control_mode_unescape_and_metadata_format_parsing() -> None:
 
 def test_capture_decoder_acs_tabs_joined_wraps_and_prompt_zones() -> None:
     """``decode_tmux_capture`` reconstructs ACS, tabs, ``-J`` wraps, and zones."""
-    cjk_meta = TmuxPaneMetadata(cols=4, rows=5, history_size=2)
+    cjk_meta = TmuxPaneMetadata(cols=4, rows=6, history_size=2)
     cjk_term = libvt.Terminal.from_tmux_capture(
-        ["H0", "H1", "ABCD", "EFGH", "IJ", "abc ", "中文"],
+        [
+            "\x0elqqk\x0f",
+            "\x1b[5:3mH1\x1b[0m",
+            "ABCD",
+            "EFGH",
+            "ab  ",
+            "中文",
+            "abc ",
+            "中文",
+        ],
         metadata=cjk_meta,
-        scrollback=1,
-        joined_capture=["H0", "H1", "ABCDEFGHIJ", "abc中文"],
+        scrollback=2,
+        joined_capture=[
+            "\x0elqqk\x0f",
+            "\x1b[5:3mH1\x1b[0m",
+            "ABCDEFGH",
+            "ab 中文",
+            "abc 中文",
+        ],
     )
-    assert [r.text for r in cjk_term.history] == ["H1"]
-    assert (cjk_term[0].wrapped, cjk_term[1].wrapped, cjk_term[3].wrapped) == (
+    assert [r.text for r in cjk_term.history] == ["┌──┐", "H1"]
+    assert cjk_term.history[1][0].style.overline is True
+    assert cjk_term.history[1][0].style.blink is False
+    assert (cjk_term[0].wrapped, cjk_term[2].wrapped, cjk_term[4].wrapped) == (
         True,
         True,
         True,
     )
-    cjk_term.resize(rows=5, cols=10)
-    assert cjk_term.lines[:3] == ("H1", "ABCDEFGHIJ", "abc中文")
+    cjk_term.resize(rows=6, cols=10)
+    assert cjk_term.lines == ("┌──┐", "H1", "ABCDEFGH", "ab 中文", "abc 中文", "")
+
+    stripped_res = decode_tmux_capture(
+        ["H0", "\tX"],
+        metadata=TmuxPaneMetadata(cols=4, rows=3, history_size=1),
+        joined_capture=["H0", "\tX"],
+    )
+    assert stripped_res.completeness.exact_wraps is True
+    assert [r.text for r in stripped_res.snapshot.history] == ["H0"]
+    assert stripped_res.snapshot.lines == ("   X", "", "")
 
     pz_snap = libvt.Snapshot.from_tmux_capture(
         ["P H0", "P H1", "- V0", "O V1", "- V2", "- V3", "- V4"],
-        metadata=cjk_meta,
+        metadata=TmuxPaneMetadata(cols=4, rows=5, history_size=2),
         scrollback=1,
         flagged=True,
     )
@@ -184,6 +210,50 @@ def test_live_tmux_capture_pane_roundtrip() -> None:
             capture_output=True,
             text=True,
         ).stdout.rstrip("\n")
+        cap_raw = subprocess.run(
+            [
+                "tmux",
+                "-L",
+                sock,
+                "capture-pane",
+                "-S",
+                "-",
+                "-E",
+                "-",
+                "-e",
+                "-p",
+                "-N",
+            ],
+            check=True,
+            capture_output=True,
+            text=True,
+        ).stdout
+        joined_raw = subprocess.run(
+            [
+                "tmux",
+                "-L",
+                sock,
+                "capture-pane",
+                "-S",
+                "-",
+                "-E",
+                "-",
+                "-e",
+                "-p",
+                "-J",
+            ],
+            check=True,
+            capture_output=True,
+            text=True,
+        ).stdout
+        candidates = [
+            decode_tmux_capture(
+                cap_raw,
+                metadata=meta_raw,
+                flagged=False,
+                joined_capture=joined_raw,
+            ),
+        ]
         flagged_proc = subprocess.run(
             [
                 "tmux",
@@ -204,53 +274,26 @@ def test_live_tmux_capture_pane_roundtrip() -> None:
             text=True,
         )
         if flagged_proc.returncode == 0:
-            live_res = decode_tmux_capture(
-                flagged_proc.stdout,
-                metadata=meta_raw,
-                flagged=True,
+            candidates.append(
+                decode_tmux_capture(
+                    flagged_proc.stdout,
+                    metadata=meta_raw,
+                    flagged=True,
+                ),
             )
-        else:
-            cap_raw = subprocess.run(
-                [
-                    "tmux",
-                    "-L",
-                    sock,
-                    "capture-pane",
-                    "-S",
-                    "-",
-                    "-E",
-                    "-",
-                    "-e",
-                    "-p",
-                    "-N",
-                ],
-                check=True,
-                capture_output=True,
-                text=True,
-            ).stdout
-            joined_raw = subprocess.run(
-                ["tmux", "-L", sock, "capture-pane", "-S", "-", "-E", "-", "-p", "-J"],
-                check=True,
-                capture_output=True,
-                text=True,
-            ).stdout
-            live_res = decode_tmux_capture(
-                cap_raw,
-                metadata=meta_raw,
-                flagged=False,
-                joined_capture=joined_raw,
+        for live_res in candidates:
+            assert live_res.completeness.exact_wraps is True
+            assert live_res.terminal.modes.is_set(Mode.MOUSE_VT200) is True
+            assert [r.text for r in live_res.snapshot.history] == ["┌──┐"]
+            assert (live_res.terminal[0].text, live_res.terminal[0].wrapped) == (
+                "1234567890",
+                True,
             )
-        assert live_res.terminal.modes.is_set(Mode.MOUSE_VT200) is True
-        assert [r.text for r in live_res.snapshot.history] == ["┌──┐"]
-        assert (live_res.terminal[0].text, live_res.terminal[0].wrapped) == (
-            "1234567890",
-            True,
-        )
-        assert (live_res.terminal[1].text, live_res.terminal[2].text) == (
-            "WRAP",
-            "        X",
-        )
-        assert live_res.terminal[2, 8].style.bg == AnsiColor.GREEN
+            assert (live_res.terminal[1].text, live_res.terminal[2].text) == (
+                "WRAP",
+                "        X",
+            )
+            assert live_res.terminal[2, 8].style.bg == AnsiColor.GREEN
     finally:
         subprocess.run(
             ["tmux", "-L", sock, "kill-server"],

From 83dd0a5e414a8ab4ca441110067b38b7a5bdb9c4 Mon Sep 17 00:00:00 2001
From: Tony Narlock 
Date: Sun, 22 Nov 2026 18:36:22 -0600
Subject: [PATCH 26/29] exc(fix[timeout]): Initialize C OSError slots in
 reconstructor (#15)

why: Skipping OSError.__init__ on empty or falsy os_args leaves C
OSError slots uninitialized on subclasses overriding __init__, while
unconditional __dict__.clear() and __dict__.update() in __setstate__
wiped state on None or invalid inputs and bypassed C descriptors.

what:
- Call OSError.__init__(obj, *os_args) unconditionally in
  _reconstruct_timeout_error and preserve non-errno multi-element args
  and mutated OSError descriptors
- Validate str-keyed dict state upfront in __setstate__ and restore
  entries via setattr while keeping None as a no-op
- Preserve unmangled double-underscore slots on all-underscore classes
  and test all 6 subclass, copy, pickle, and ExceptionGroup shapes
---
 src/libvt/exc.py  |  64 ++++++++---
 tests/test_exc.py | 275 +++++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 319 insertions(+), 20 deletions(-)

diff --git a/src/libvt/exc.py b/src/libvt/exc.py
index 8920467..6d83109 100644
--- a/src/libvt/exc.py
+++ b/src/libvt/exc.py
@@ -32,24 +32,29 @@ def _iter_slot_names(cls: type[BaseException]) -> list[str]:
         for slot in slots:
             if slot in ("__dict__", "__weakref__"):
                 continue
-            attr = (
-                f"_{base.__name__.lstrip('_')}{slot}"
-                if slot.startswith("__") and not slot.endswith("__")
-                else slot
-            )
+            if slot.startswith("__") and not slot.endswith("__"):
+                stripped = base.__name__.lstrip("_")
+                attr = f"_{stripped}{slot}" if stripped else slot
+            else:
+                attr = slot
             if attr not in seen:
                 seen.add(attr)
                 names.append(attr)
     return names
 
 
+_OS_DESCRIPTOR_NAMES = ("errno", "strerror", "filename", "filename2")
+
+
 def _reconstruct_timeout_error(
     cls: type[TerminalTimeoutError],
     os_args: tuple[object, ...],
+    raw_args: tuple[object, ...] | None = None,
 ) -> TerminalTimeoutError:
     obj = OSError.__new__(cls, *os_args)
-    if os_args:
-        OSError.__init__(obj, *os_args)
+    OSError.__init__(obj, *os_args)
+    if raw_args is not None and obj.args != raw_args:
+        obj.args = raw_args
     return obj
 
 
@@ -138,17 +143,32 @@ def format_diagnostics(self) -> str:
 
     def __reduce__(self) -> tuple[object, ...]:
         """Serialize args, ``__dict__``, ``__notes__``, and subclass ``__slots__``."""
-        os_args = OSError.__reduce__(self)[1]
         dict_state = dict(self.__dict__)
         if isinstance(dict_state.get("__notes__"), list):
             dict_state["__notes__"] = list(dict_state["__notes__"])
+        if len(self.args) == 2 and self.errno is not None and self.strerror is not None:
+            os_args = OSError.__reduce__(self)[1]
+        elif (
+            len(self.args) <= 1
+            and self.errno is None
+            and self.strerror is None
+            and self.filename is None
+            and self.filename2 is None
+        ):
+            os_args = self.args
+        else:
+            os_args = ()
+            for attr_name in _OS_DESCRIPTOR_NAMES:
+                val = getattr(self, attr_name)
+                if val is not None:
+                    dict_state.setdefault(attr_name, val)
         slot_state = {
             name: getattr(self, name)
             for name in _iter_slot_names(type(self))
             if hasattr(self, name)
         }
         state: object = (dict_state, slot_state) if slot_state else dict_state
-        return (_reconstruct_timeout_error, (type(self), os_args), state)
+        return (_reconstruct_timeout_error, (type(self), os_args, self.args), state)
 
     def __setstate__(self, state: object) -> None:
         """Restore instance ``__dict__``, ``__notes__`` copy, and ``__slots__``."""
@@ -156,12 +176,26 @@ def __setstate__(self, state: object) -> None:
             dict_state, slot_state = state
         else:
             dict_state, slot_state = state, None
-        self.__dict__.clear()
-        if isinstance(dict_state, dict):
-            self.__dict__.update(dict_state)
-            if isinstance(self.__dict__.get("__notes__"), list):
-                self.__dict__["__notes__"] = list(self.__dict__["__notes__"])
-        if isinstance(slot_state, dict):
+        if dict_state is not None and (
+            not isinstance(dict_state, dict)
+            or not all(isinstance(k, str) for k in dict_state)
+        ):
+            msg = "state must be a str-keyed dictionary"
+            raise TypeError(msg)
+        if slot_state is not None and (
+            not isinstance(slot_state, dict)
+            or not all(isinstance(k, str) for k in slot_state)
+        ):
+            msg = "slot state must be a str-keyed dictionary"
+            raise TypeError(msg)
+        if dict_state is not None:
+            for key, val in dict_state.items():
+                setattr(
+                    self,
+                    key,
+                    list(val) if key == "__notes__" and isinstance(val, list) else val,
+                )
+        if slot_state is not None:
             for key, val in slot_state.items():
                 setattr(self, key, val)
 
diff --git a/tests/test_exc.py b/tests/test_exc.py
index ef99ab4..ceafb5d 100644
--- a/tests/test_exc.py
+++ b/tests/test_exc.py
@@ -3,10 +3,14 @@
 from __future__ import annotations
 
 import copy
+import errno
 import pickle
+import sys
 import traceback
 
-from libvt.exc import TerminalTimeoutError
+import pytest
+
+from libvt.exc import TerminalTimeoutError, _reconstruct_timeout_error
 from libvt.parser import ParserState
 
 
@@ -17,7 +21,7 @@ class _SlottedTimeoutError(TerminalTimeoutError):
 
     def __init__(
         self,
-        message: str,
+        message: str | None = None,
         *,
         attempt: int,
         parser_state: ParserState = ParserState.GROUND,
@@ -34,19 +38,120 @@ def __init__(
         self.attempt = attempt
 
 
+class _CustomSigTimeoutError(TerminalTimeoutError):
+    """Subclass with required positional arguments mismatching ``self.args``."""
+
+    def __init__(self, host: str, port: int) -> None:
+        super().__init__(f"{host}:{port}", eof=True)
+        self.host = host
+        self.port = port
+
+
+class _ErrnoTimeoutError(TerminalTimeoutError):
+    """Subclass populating C ``OSError`` ``errno``, ``strerror``, and filenames."""
+
+    def __init__(
+        self,
+        code: int,
+        strerror: str,
+        filename: str | None = None,
+        filename2: str | None = None,
+    ) -> None:
+        super().__init__(strerror, eof=True)
+        if filename2 is not None:
+            OSError.__init__(self, code, strerror, filename, None, filename2)
+        elif filename is not None:
+            OSError.__init__(self, code, strerror, filename)
+        else:
+            OSError.__init__(self, code, strerror)
+
+
 class _DynamicTimeoutError(TerminalTimeoutError):
     """Subclass allowing dynamic ``__dict__`` attributes."""
 
     extra_context: str = ""
 
 
+class _FalsyArgs(tuple[object, ...]):
+    """Tuple subclass returning ``False`` from ``__bool__`` while non-empty."""
+
+    def __bool__(self) -> bool:
+        return False
+
+
+_UNDERSCORE_SLOT_CLS = type(
+    "___",
+    (TerminalTimeoutError,),
+    {"__module__": __name__, "__slots__": ("__raw_tag",)},
+)
+globals()["___"] = _UNDERSCORE_SLOT_CLS
+
+
 def test_timeout_error_zero_arg_and_attach_note_suppression() -> None:
     """Zero-arg construction keeps ``args == ()``; ``attach_note=False`` omits notes."""
+    raw_buf = bytearray(b"\x1b[31m")
+    buf_exc = TerminalTimeoutError(recent_bytes=raw_buf)
+    raw_buf[0] ^= 0xFF
+    assert buf_exc.recent_bytes == b"\x1b[31m"
+
     empty = TerminalTimeoutError()
     assert isinstance(empty, TimeoutError)
     assert empty.args == ()
     assert str(empty) == ""
     assert empty.errno is None
+    empty.add_note("zero-arg-note")
+    for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+        empty_rt = pickle.loads(pickle.dumps(empty, protocol=proto))
+        assert type(empty_rt) is TerminalTimeoutError
+        assert empty_rt.args == ()
+        assert empty_rt.errno is None
+        assert empty_rt.__notes__ == ["zero-arg-note"]
+
+    falsy_rebuilt = _reconstruct_timeout_error(
+        TerminalTimeoutError,
+        _FalsyArgs(("stalled",)),
+    )
+    assert falsy_rebuilt.args == ("stalled",)
+
+    if hasattr(sys, "monitoring"):
+        calls: list[object] = []
+        tool_id = next(tid for tid in range(6) if sys.monitoring.get_tool(tid) is None)
+        sys.monitoring.use_tool_id(tool_id, "libvt_test_exc")
+        try:
+            sys.monitoring.register_callback(
+                tool_id,
+                sys.monitoring.events.CALL,
+                lambda _code, _off, fn, _arg0: calls.append(fn),
+            )
+            sys.monitoring.set_local_events(
+                tool_id,
+                _reconstruct_timeout_error.__code__,
+                sys.monitoring.events.CALL,
+            )
+            rebuilt_empty = _reconstruct_timeout_error(TerminalTimeoutError, ())
+        finally:
+            sys.monitoring.set_local_events(
+                tool_id,
+                _reconstruct_timeout_error.__code__,
+                0,
+            )
+            sys.monitoring.register_callback(
+                tool_id,
+                sys.monitoring.events.CALL,
+                None,
+            )
+            sys.monitoring.free_tool_id(tool_id)
+        assert type(rebuilt_empty) is TerminalTimeoutError
+        assert OSError.__init__ in calls
+
+    uslot = _UNDERSCORE_SLOT_CLS("underscore-slot")
+    setattr(uslot, "__raw_tag", "kept")
+    for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+        uslot_rt = pickle.loads(pickle.dumps(uslot, protocol=proto))
+        assert getattr(uslot_rt, "__raw_tag") == "kept"
+    for clone_fn in (copy.copy, copy.deepcopy):
+        uslot_cp = clone_fn(uslot)
+        assert getattr(uslot_cp, "__raw_tag") == "kept"
 
     quiet = TerminalTimeoutError(
         "quiet timeout",
@@ -55,14 +160,30 @@ def test_timeout_error_zero_arg_and_attach_note_suppression() -> None:
     )
     assert not hasattr(quiet, "__notes__")
     assert "secret-viewport" in quiet.format_diagnostics()
-    for proto in (0, pickle.HIGHEST_PROTOCOL):
+    for proto in range(pickle.HIGHEST_PROTOCOL + 1):
         quiet_rt = pickle.loads(pickle.dumps(quiet, protocol=proto))
         assert not hasattr(quiet_rt, "__notes__")
         assert quiet_rt.screen_text == "secret-viewport"
+    for clone_fn in (copy.copy, copy.deepcopy):
+        quiet_cp = clone_fn(quiet)
+        assert not hasattr(quiet_cp, "__notes__")
+        assert quiet_cp.screen_text == "secret-viewport"
+
+    quiet.add_note("late-note")
+    for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+        quiet_late = pickle.loads(pickle.dumps(quiet, protocol=proto))
+        assert quiet_late.__notes__ == ["late-note"]
+        quiet_late.add_note("clone-only")
+        assert quiet.__notes__ == ["late-note"]
+    for clone_fn in (copy.copy, copy.deepcopy):
+        quiet_late_cp = clone_fn(quiet)
+        assert quiet_late_cp.__notes__ == ["late-note"]
+        quiet_late_cp.add_note("clone-only")
+        assert quiet.__notes__ == ["late-note"]
 
 
 def test_timeout_error_slots_subclasses_copy_pickle_and_exception_group() -> None:
-    """``TerminalTimeoutError`` preserves slots, dynamic attrs, and unaliased notes."""
+    """``TerminalTimeoutError`` preserves slots, args, descriptors, and notes."""
     slotted = _SlottedTimeoutError(
         "slotted timeout",
         attempt=4,
@@ -71,7 +192,7 @@ def test_timeout_error_slots_subclasses_copy_pickle_and_exception_group() -> Non
         recent_bytes=b"\x1b[1;",
     )
     slotted.add_note("slot-note")
-    for proto in (0, pickle.HIGHEST_PROTOCOL):
+    for proto in range(pickle.HIGHEST_PROTOCOL + 1):
         slotted_rt = pickle.loads(pickle.dumps(slotted, protocol=proto))
         assert type(slotted_rt) is _SlottedTimeoutError
         assert slotted_rt.attempt == 4
@@ -81,6 +202,114 @@ def test_timeout_error_slots_subclasses_copy_pickle_and_exception_group() -> Non
         assert type(cloned_slot) is _SlottedTimeoutError
         assert cloned_slot.attempt == 4
         assert cloned_slot.__notes__ == slotted.__notes__
+        cloned_slot.add_note("slot-clone-only")
+        assert "slot-clone-only" not in slotted.__notes__
+
+    custom_sig = _CustomSigTimeoutError("127.0.0.1", 2222)
+    custom_sig.add_note("sig-note")
+    errno_2 = _ErrnoTimeoutError(errno.ETIMEDOUT, "PTY stalled")
+    errno_3 = _ErrnoTimeoutError(errno.ETIMEDOUT, "PTY stalled", "/dev/pts/9")
+    errno_3.add_note("errno-note")
+    errno_5 = _ErrnoTimeoutError(
+        errno.EXDEV,
+        "Cross-device link",
+        "/dev/pts/9",
+        "/dev/pts/10",
+    )
+    slotted_empty = _SlottedTimeoutError(attempt=9)
+    slotted_empty.add_note("slot-empty-note")
+
+    multi_args = TerminalTimeoutError("initial")
+    multi_args.args = ("%1", "127.0.0.1", 2222)
+
+    one_arg_os = TerminalTimeoutError("stalled")
+    one_arg_os.errno = errno.ETIMEDOUT
+    one_arg_os.filename = "/dev/pts/0"
+    one_arg_os.filename2 = "/dev/pts/1"
+
+    for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+        cs_rt = pickle.loads(pickle.dumps(custom_sig, protocol=proto))
+        assert type(cs_rt) is _CustomSigTimeoutError
+        assert (cs_rt.host, cs_rt.port, cs_rt.args, cs_rt.eof) == (
+            "127.0.0.1",
+            2222,
+            ("127.0.0.1:2222",),
+            True,
+        )
+        assert cs_rt.__notes__ == custom_sig.__notes__
+
+        e2_rt = pickle.loads(pickle.dumps(errno_2, protocol=proto))
+        assert (e2_rt.errno, e2_rt.strerror, e2_rt.filename) == (
+            errno.ETIMEDOUT,
+            "PTY stalled",
+            None,
+        )
+
+        er_rt = pickle.loads(pickle.dumps(errno_3, protocol=proto))
+        assert type(er_rt) is _ErrnoTimeoutError
+        assert (er_rt.errno, er_rt.strerror, er_rt.filename) == (
+            errno.ETIMEDOUT,
+            "PTY stalled",
+            "/dev/pts/9",
+        )
+        assert er_rt.__notes__ == errno_3.__notes__
+
+        e5_rt = pickle.loads(pickle.dumps(errno_5, protocol=proto))
+        assert (e5_rt.errno, e5_rt.strerror, e5_rt.filename, e5_rt.filename2) == (
+            errno.EXDEV,
+            "Cross-device link",
+            "/dev/pts/9",
+            "/dev/pts/10",
+        )
+
+        se_rt = pickle.loads(pickle.dumps(slotted_empty, protocol=proto))
+        assert (type(se_rt), se_rt.args, se_rt.attempt, se_rt.errno) == (
+            _SlottedTimeoutError,
+            (),
+            9,
+            None,
+        )
+        assert se_rt.__notes__ == slotted_empty.__notes__
+
+        ma_rt = pickle.loads(pickle.dumps(multi_args, protocol=proto))
+        assert ma_rt.args == ("%1", "127.0.0.1", 2222)
+        assert (ma_rt.errno, ma_rt.strerror, ma_rt.filename) == (None, None, None)
+
+        oa_rt = pickle.loads(pickle.dumps(one_arg_os, protocol=proto))
+        assert oa_rt.args == ("stalled",)
+        assert (oa_rt.errno, oa_rt.strerror, oa_rt.filename, oa_rt.filename2) == (
+            errno.ETIMEDOUT,
+            None,
+            "/dev/pts/0",
+            "/dev/pts/1",
+        )
+
+    for clone_fn in (copy.copy, copy.deepcopy):
+        cs_cp = clone_fn(custom_sig)
+        cs_cp.add_note("mutated")
+        assert "mutated" not in custom_sig.__notes__
+        assert (cs_cp.host, cs_cp.port) == ("127.0.0.1", 2222)
+
+        e5_cp = clone_fn(errno_5)
+        assert (e5_cp.errno, e5_cp.strerror, e5_cp.filename, e5_cp.filename2) == (
+            errno.EXDEV,
+            "Cross-device link",
+            "/dev/pts/9",
+            "/dev/pts/10",
+        )
+
+        ma_cp = clone_fn(multi_args)
+        assert (ma_cp.args, ma_cp.errno) == (("%1", "127.0.0.1", 2222), None)
+
+    eg_orig = ExceptionGroup("multi", [custom_sig, errno_3])
+    eg_derived = eg_orig.derive([custom_sig])
+    assert eg_derived.exceptions[0].__notes__ == custom_sig.__notes__
+    eg_rt = pickle.loads(pickle.dumps(eg_orig, protocol=pickle.HIGHEST_PROTOCOL))
+    assert type(eg_rt.exceptions[0]) is _CustomSigTimeoutError
+    assert type(eg_rt.exceptions[1]) is _ErrnoTimeoutError
+    eg_dc = copy.deepcopy(eg_orig)
+    eg_dc.exceptions[0].add_note("dc-only")
+    assert "dc-only" not in custom_sig.__notes__
 
     sub = _DynamicTimeoutError(
         "timed out waiting for prompt",
@@ -110,6 +339,10 @@ def test_timeout_error_slots_subclasses_copy_pickle_and_exception_group() -> Non
     assert restored.__notes__ == sub.__notes__
     assert restored.extra_context == "pane-%1"
 
+    del restored.__notes__
+    del_rt = pickle.loads(pickle.dumps(restored, protocol=pickle.HIGHEST_PROTOCOL))
+    assert not hasattr(del_rt, "__notes__")
+
     caught: list[TerminalTimeoutError] = []
     group_msg = "batch"
     other_msg = "other"
@@ -121,3 +354,35 @@ def test_timeout_error_slots_subclasses_copy_pickle_and_exception_group() -> Non
         pass
     assert len(caught) == 1
     assert caught[0].__notes__ == sub.__notes__
+
+
+def test_timeout_error_setstate_validation_and_descriptors() -> None:
+    """``__setstate__`` keeps ``None`` as a no-op, validates dicts, and sets causes."""
+    live = TerminalTimeoutError(
+        "live",
+        parser_state=ParserState.CSI_PARAM,
+        screen_text="hello",
+    )
+    live.__setstate__(None)
+    assert live.screen_text == "hello"
+    assert live.format_diagnostics() != ""
+
+    for bad_state in (
+        "corrupt",
+        123,
+        (1, 2, 3),
+        ("bad", {}),
+        ({}, "bad"),
+        (None, "bad"),
+        {123: "non-str-key"},
+        {"screen_text": "wiped", 99: "bad"},
+        ({"screen_text": "wiped"}, {99: "bad"}),
+    ):
+        with pytest.raises(TypeError):
+            live.__setstate__(bad_state)
+        assert live.screen_text == "hello"
+
+    cause = KeyError("root")
+    live.__setstate__({"__cause__": cause})
+    assert live.__cause__ is cause
+    assert "__cause__" not in live.__dict__

From 25ec9eac4844ea18038568e4555bb0f8e5ec35c6 Mon Sep 17 00:00:00 2001
From: Tony Narlock 
Date: Sun, 22 Nov 2026 19:07:34 -0600
Subject: [PATCH 27/29] grid(fix[cluster]): Copy base pen to SPACER_TAIL (#16)

why:
- Widening a narrow cell via VS16 or spacing continuation stamped the
  active stream pen onto SPACER_TAIL, dropping base SGR, hyperlinks,
  and DECSCA protection when attributes changed mid-cluster.
- Stage-1 boundary checks in test_ucd skipped non-17.0 stdlib runtimes
  and left interior block-index aliasing unchecked on Python 3.12-3.14.

what:
- Inherit base_pen and base_ext from target onto SPACER_TAIL on
  width_override == 2 and clear vacated VS15 cells with BCE background
  only via _PEN_BG_MASK.
- Emit EXPANDED_UCD_SHA256 from scripts/generate_ucd.py and verify all
  4,352 expanded stage-1 UCD blocks via SHA-256 in tests/test_ucd.py.
---
 scripts/generate_ucd.py |  12 ++-
 src/libvt/_grid.py      |  19 ++--
 src/libvt/_ucd.py       |   2 +
 src/libvt/terminal.py   |  11 ++-
 tests/test_ucd.py       | 186 ++++++++++++++++++++++++++++++++++++++++
 5 files changed, 214 insertions(+), 16 deletions(-)

diff --git a/scripts/generate_ucd.py b/scripts/generate_ucd.py
index e9a6c69..c62fcc0 100644
--- a/scripts/generate_ucd.py
+++ b/scripts/generate_ucd.py
@@ -293,6 +293,12 @@ def build_safe_narrow_bmp_pattern(stage1: bytes, stage2: bytes) -> str:
 
 def render_module(stage1: bytes, stage2: bytes) -> str:
     """Format ``src/libvt/_ucd.py`` source text."""
+    expanded_hasher = hashlib.sha256()
+    for i in range(0, len(stage1), 2):
+        b_idx = int.from_bytes(stage1[i : i + 2], "little")
+        expanded_hasher.update(stage2[b_idx * 512 : (b_idx + 1) * 512])
+    expanded_sha256 = expanded_hasher.hexdigest()
+
     blob = len(stage1).to_bytes(4, "little") + stage1 + stage2
     compressed = base64.b85encode(zlib.compress(blob, level=9)).decode("ascii")
     lines = [compressed[i : i + 76] for i in range(0, len(compressed), 76)]
@@ -374,6 +380,7 @@ class WidthRole(enum.IntEnum):
 _ACTIVE_BIT = 1
 
 UNICODE_VERSION = "{UNICODE_VERSION}"
+EXPANDED_UCD_SHA256 = "{expanded_sha256}"
 
 SAFE_NARROW_BMP_RE: t.Final[re.Pattern[str]] = re.compile(
 {bmp_pat_literal}
@@ -553,9 +560,7 @@ def step_cluster(
                 next_incb = 0
 
             next_vs = 1 if (entry & EMOJI_VS_BASE_BIT) else 0
-            next_sp = (
-                1 if (has_spacing or w >= 1 or gcb == GCB_SPACING_MARK) else 0
-            )
+            next_sp = 1 if (has_spacing or w >= 1 or gcb == GCB_SPACING_MARK) else 0
             next_multi = 0 if (not has_spacing and w >= 1) else 1
             return (
                 True,
@@ -669,6 +674,7 @@ def sanitize_terminal_text(text: str) -> str:
 __all__ = [
     "BIDI_SPOOF_BIT",
     "CLUSTER_NONE",
+    "EXPANDED_UCD_SHA256",
     "SAFE_NARROW_BMP_RE",
     "UNICODE_VERSION",
     "WidthRole",
diff --git a/src/libvt/_grid.py b/src/libvt/_grid.py
index e6f76b5..2e44053 100644
--- a/src/libvt/_grid.py
+++ b/src/libvt/_grid.py
@@ -65,6 +65,8 @@ def current_row_gen() -> int:
 _WIDTH_CLEAR_MASK = ~(_WIDTH_MASK << _WIDTH_SHIFT) & ((1 << 64) - 1)
 _OVERLINE_BIT = 1 << 62
 _HAS_EXT_BIT = 1 << 63
+_PEN_BASE_MASK = _WIDTH_CLEAR_MASK & ~_HAS_EXT_BIT
+_PEN_BG_MASK = _COLOR_MASK << _BG_SHIFT
 
 
 @dataclass(frozen=True, slots=True)
@@ -516,8 +518,7 @@ def append_grapheme(
         ch: str,
         *,
         width_override: int,
-        pen_word: int,
-        cell_ext: _CellExt | None,
+        bce_word: int = 0,
     ) -> None:
         """Append zero-width or cluster-extending *ch* onto cell *col*."""
         cols = len(self.chars)
@@ -538,13 +539,13 @@ def append_grapheme(
             and cur_role == int(WidthRole.NARROW)
             and target + 1 < cols
         ):
+            base_pen = self.attr_at(target) & _PEN_BASE_MASK
+            base_ext = self.ext_at(target)
             self._heal_wide_boundary(target + 1)
-            attrs = self._ensure_attrs()
-            attrs[target] = (attrs[target] & _WIDTH_CLEAR_MASK) | (
-                int(WidthRole.WIDE) << _WIDTH_SHIFT
+            self._set_raw(
+                target, self.chars[target], base_pen, WidthRole.WIDE, base_ext
             )
-            self.has_wide = True
-            self._set_raw(target + 1, "", pen_word, WidthRole.SPACER_TAIL, cell_ext)
+            self._set_raw(target + 1, "", base_pen, WidthRole.SPACER_TAIL, base_ext)
             self.used = max(self.used, target + 2)
             self.text_used = max(self.text_used, target + 2)
         elif (
@@ -554,10 +555,10 @@ def append_grapheme(
         ):
             attrs = self._ensure_attrs()
             attrs[target] &= _WIDTH_CLEAR_MASK
-            self._set_raw(target + 1, " ", pen_word, WidthRole.NARROW, cell_ext)
+            self._set_raw(target + 1, " ", bce_word, WidthRole.NARROW, None)
             if self.text_used == target + 2:
                 self.text_used = target + 1
-                if self.used == target + 2 and pen_word == 0 and cell_ext is None:
+                if self.used == target + 2 and bce_word == 0:
                     self.used = target + 1
         bump_row_gen(self)
 
diff --git a/src/libvt/_ucd.py b/src/libvt/_ucd.py
index f63e466..75b8618 100644
--- a/src/libvt/_ucd.py
+++ b/src/libvt/_ucd.py
@@ -64,6 +64,7 @@ class WidthRole(enum.IntEnum):
 _ACTIVE_BIT = 1
 
 UNICODE_VERSION = "17.0.0"
+EXPANDED_UCD_SHA256 = "a6a2bbf94b9ebb25bb22b06a46a605b468b0a398bd9ee64e60dbc717c2484cb3"
 
 SAFE_NARROW_BMP_RE: t.Final[re.Pattern[str]] = re.compile(
     r"[ -~\xa0-\xa8\xaa-\xac\xaf-\u02ff\u0370-\u0482\u048a-\u0590\u05be\u05c0"
@@ -445,6 +446,7 @@ def sanitize_terminal_text(text: str) -> str:
 __all__ = [
     "BIDI_SPOOF_BIT",
     "CLUSTER_NONE",
+    "EXPANDED_UCD_SHA256",
     "SAFE_NARROW_BMP_RE",
     "UNICODE_VERSION",
     "WidthRole",
diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py
index 415bdc2..0f3a757 100644
--- a/src/libvt/terminal.py
+++ b/src/libvt/terminal.py
@@ -16,7 +16,8 @@
 from dataclasses import dataclass
 
 from libvt._grid import (
-    _WIDTH_CLEAR_MASK,
+    _PEN_BASE_MASK,
+    _PEN_BG_MASK,
     FrozenRow,
     _CellExt,
     _Row,
@@ -2344,7 +2345,7 @@ def _handle_print(self, text: str) -> None:
                         ):
                             prev_cluster_len = self._cluster_len
                             combined = row_obj.chars[pc] + ch
-                            base_pen = row_obj.attr_at(pc) & _WIDTH_CLEAR_MASK
+                            base_pen = row_obj.attr_at(pc) & _PEN_BASE_MASK
                             base_ext = row_obj.ext_at(pc)
                             bce_w, bce_e = self._bce_pair()
                             full_row_wrap = eff_left == 0 and eff_right == scr.cols - 1
@@ -2446,12 +2447,14 @@ def _handle_print(self, text: str) -> None:
                                     scrolled_total=scr._scrolled_total,
                                     policy=sixel_pol,
                                 )
+                        vacated_bce = (
+                            (self._pen_word & _PEN_BG_MASK) if w_override == 1 else 0
+                        )
                         row_obj.append_grapheme(
                             pc,
                             ch,
                             width_override=w_override,
-                            pen_word=self._pen_word,
-                            cell_ext=self._cell_ext,
+                            bce_word=vacated_bce,
                         )
                         if pc == 0 and w_override == 1:
                             scr.heal_wrapped_spacer_head(pr)
diff --git a/tests/test_ucd.py b/tests/test_ucd.py
index e94b0bd..360d60e 100644
--- a/tests/test_ucd.py
+++ b/tests/test_ucd.py
@@ -2,8 +2,11 @@
 
 from __future__ import annotations
 
+import array
 import collections.abc
+import hashlib
 import pathlib
+import sys
 import time
 import typing as t
 import unicodedata
@@ -15,12 +18,18 @@
 from libvt._ucd import (
     EXT_PICT_BIT,
     SAFE_NARROW_BMP_RE,
+    WidthRole,
     char_width,
     display_width,
     segment_graphemes,
     ucd_lookup,
 )
 from libvt.config import DEFAULT_PROFILE, TMUX_PROFILE, Profile
+from libvt.style import AnsiColor, Hyperlink, RgbColor, UnderlineStyle
+
+EXPECTED_EXPANDED_UCD_SHA256 = (
+    "a6a2bbf94b9ebb25bb22b06a46a605b468b0a398bd9ee64e60dbc717c2484cb3"
+)
 
 
 class DisplayWidthCase(t.NamedTuple):
@@ -178,3 +187,180 @@ def test_combining_mark_cap_and_cluster_anchor_invalidation() -> None:
     term.reset()
     term.feed(b"ab\x1b[1;1H" + "\u0301".encode())
     assert (term[0, 0].text, term[0, 1].text) == ("a", "b")
+
+
+def _expanded_stage_sha256(
+    stage1: collections.abc.Sequence[int],
+    stage2: array.array[int],
+) -> str:
+    s2 = stage2
+    if sys.byteorder != "little":
+        s2 = array.array("H", s2)
+        s2.byteswap()
+    s2_bytes = memoryview(s2).cast("B")
+    hasher = hashlib.sha256()
+    for block_id in stage1:
+        off = block_id * 512
+        hasher.update(s2_bytes[off : off + 512])
+    return hasher.hexdigest()
+
+
+def test_expanded_ucd_4352_block_sha256_parity() -> None:
+    """All 4,352 expanded ``_STAGE1`` blocks match the pinned UCD 17.0.0 digest."""
+    assert len(_ucd._STAGE1) == 4352
+    digest = _expanded_stage_sha256(_ucd._STAGE1, _ucd._STAGE2)
+    assert _ucd.EXPANDED_UCD_SHA256 == EXPECTED_EXPANDED_UCD_SHA256
+    assert digest == EXPECTED_EXPANDED_UCD_SHA256
+
+    mutated_stage1 = array.array("H", _ucd._STAGE1)
+    mutated_stage1[0] = (
+        mutated_stage1[1] if mutated_stage1[0] != mutated_stage1[1] else 1
+    )
+    assert (
+        _expanded_stage_sha256(mutated_stage1, _ucd._STAGE2)
+        != EXPECTED_EXPANDED_UCD_SHA256
+    )
+
+
+def test_append_grapheme_spacer_tail_inherits_base_pen_and_decsca() -> None:
+    """Widening a base cell copies SGR, hyperlink, and ``DECSCA`` to ``SPACER_TAIL``."""
+    term = libvt.Terminal(rows=2, cols=8)
+    term.feed(
+        b"\x1b[31;44;4:3;53;58:2::0:255:0m"
+        b'\x1b[1"q'
+        b"\x1b]8;id=h1;https://example.com\x07"
+        + "❤".encode()
+        + b'\x1b[0m\x1b[0"q\x1b]8;;\x07'
+        + "\ufe0f".encode()
+        + b"Z"
+    )
+    snap = term.snapshot()
+    head = snap[0, 0]
+    tail = snap[0, 1]
+    expected_link = Hyperlink(uri="https://example.com", id="h1")
+
+    assert (head.text, head.width, head.width_role, head.protected) == (
+        "❤\ufe0f",
+        2,
+        WidthRole.WIDE,
+        True,
+    )
+    assert (tail.text, tail.width, tail.width_role, tail.protected) == (
+        "",
+        0,
+        WidthRole.SPACER_TAIL,
+        True,
+    )
+    assert head.style.fg == AnsiColor.RED
+    assert head.style.bg == AnsiColor.BLUE
+    assert head.style.underline == UnderlineStyle.CURLY
+    assert head.style.overline is True
+    assert head.style.underline_color == RgbColor(0, 255, 0)
+    assert tail.style == head.style
+    assert head.hyperlink == expected_link
+    assert tail.hyperlink == expected_link
+
+    runs = snap[0].runs
+    assert len(runs) == 2
+    assert (runs[0].start_col, runs[0].end_col, runs[0].text) == (0, 2, "❤\ufe0f")
+    assert runs[0].hyperlink == expected_link
+    assert (runs[1].start_col, runs[1].end_col, runs[1].text) == (2, 3, "Z")
+
+    term.feed(b"\x1b[?2K")
+    after_decsel = term.snapshot()
+    assert after_decsel[0, 0].text == "❤\ufe0f"
+    assert after_decsel[0, 0].width_role == WidthRole.WIDE
+    assert after_decsel[0, 1].width_role == WidthRole.SPACER_TAIL
+    assert after_decsel[0, 2].text == " "
+
+    term.reset()
+    term.feed(b'\x1b[0"q' + "❤".encode() + b'\x1b[1"q' + "\ufe0f".encode())
+    term.feed(b"\x1b[?2K")
+    assert term.lines[0] == ""
+
+    term.reset()
+    term.feed(
+        b'\x1b[31;44;7;4m\x1b[1"q\x1b]8;;https://example.com\x07' + "⌚\ufe0e".encode()
+    )
+    narrowed = term.snapshot()
+    assert (
+        narrowed[0, 0].text,
+        narrowed[0, 0].width,
+        narrowed[0, 0].width_role,
+        narrowed[0, 0].protected,
+    ) == ("⌚\ufe0e", 1, WidthRole.NARROW, True)
+    vacated = narrowed[0, 1]
+    assert (vacated.text, vacated.width_role, vacated.protected) == (
+        " ",
+        WidthRole.NARROW,
+        False,
+    )
+    assert vacated.style.fg is None
+    assert vacated.style.bg == AnsiColor.BLUE
+    assert vacated.style.reverse is False
+    assert vacated.style.underline == UnderlineStyle.NONE
+    assert vacated.hyperlink is None
+    term.feed(b'\x1b[0m\x1b[0"q\x1b]8;;\x07\x1b[?2K')
+    assert term[0, 0].text == "⌚\ufe0e"
+
+    wrap_term = libvt.Terminal(rows=2, cols=4)
+    wrap_term.feed(
+        b"ABC"
+        b"\x1b[31;44;4:3;53;58:2::0:255:0m"
+        b'\x1b[1"q'
+        b"\x1b]8;id=w1;https://example.com\x07"
+        b"1"
+        b'\x1b[0m\x1b[0"q\x1b]8;;\x07' + "\ufe0f\u20e3".encode() + b"Z"
+    )
+    wrap_link = Hyperlink(uri="https://example.com", id="w1")
+    wrap_snap = wrap_term.snapshot()
+    assert wrap_snap[0].wrapped is True
+    assert (wrap_snap[0, 3].width_role, wrap_snap[0, 3].protected) == (
+        WidthRole.SPACER_HEAD,
+        False,
+    )
+    assert (
+        wrap_snap[1, 0].text,
+        wrap_snap[1, 0].width_role,
+        wrap_snap[1, 0].protected,
+    ) == ("1\ufe0f\u20e3", WidthRole.WIDE, True)
+    assert (
+        wrap_snap[1, 1].text,
+        wrap_snap[1, 1].width_role,
+        wrap_snap[1, 1].protected,
+    ) == ("", WidthRole.SPACER_TAIL, True)
+    assert wrap_snap[1, 1].style == wrap_snap[1, 0].style
+    assert wrap_snap[1, 0].hyperlink == wrap_link
+    assert wrap_snap[1, 1].hyperlink == wrap_link
+
+    wrap_term.feed(b"\r\n\n")
+    hist_row = wrap_term.history[1]
+    assert (hist_row[0].text, hist_row[0].width_role, hist_row[0].protected) == (
+        "1\ufe0f\u20e3",
+        WidthRole.WIDE,
+        True,
+    )
+    assert (hist_row[1].text, hist_row[1].width_role, hist_row[1].protected) == (
+        "",
+        WidthRole.SPACER_TAIL,
+        True,
+    )
+    assert hist_row[1].style == hist_row[0].style
+    assert hist_row[1].hyperlink == wrap_link
+    assert (hist_row.runs[0].start_col, hist_row.runs[0].end_col) == (0, 2)
+
+    wrap_term.resize(rows=4, cols=6)
+    reflow_snap = wrap_term.snapshot()
+    assert reflow_snap[0].text == "ABC1\ufe0f\u20e3Z"
+    assert (reflow_snap[0, 3].width_role, reflow_snap[0, 3].protected) == (
+        WidthRole.WIDE,
+        True,
+    )
+    assert (reflow_snap[0, 4].width_role, reflow_snap[0, 4].protected) == (
+        WidthRole.SPACER_TAIL,
+        True,
+    )
+    assert reflow_snap[0, 4].style == reflow_snap[0, 3].style
+    assert reflow_snap[0, 4].hyperlink == wrap_link
+    wrap_term.feed(b"\x1b[1;1H\x1b[?2K")
+    assert wrap_term.lines[0] == "   1\ufe0f\u20e3"

From 7524975a672d600ff74485881c838316d498c895 Mon Sep 17 00:00:00 2001
From: Tony Narlock 
Date: Sun, 22 Nov 2026 19:42:12 -0600
Subject: [PATCH 28/29] terminal(feat[coords]): Resolve rows via at_abs (#19)

why:
- Signed row fields on PromptZone and ImagePlacement turned negative
  once scrolled into history, causing snap[z.row] to index from the
  bottom of the active viewport instead of scrollback.
- Allocating new PromptZone and ImagePlacement tuples on every snapshot
  to recompute viewport-relative row coordinates went stale after the
  next scroll linefeed.

what:
- Store monotonic abs_row and col on PromptZone and ImagePlacement and
  replace occupies_cell with ImagePlacement.occupies_abs.
- Add Snapshot.at_abs, Snapshot.viewport_row, Snapshot.scrolled_total,
  and Snapshot.evicted_total, preserving scrolled_total == evicted_total
  + len(history) across scrollback=0, ED 3, bulk scrolls, and reflow.
- Crop top-clipped SIXEL and Kitty placements in abs_row space and
  include scrolled_total and evicted_total in Snapshot.to_dict.
---
 CHANGES                                       |  16 +-
 ...501-program-status-and-semantic-prompts.md |   7 +-
 src/libvt/events.py                           |  11 +-
 src/libvt/graphics.py                         | 148 ++++++++++---
 src/libvt/screen.py                           |  95 ++++----
 src/libvt/terminal.py                         | 202 ++++++++++++++----
 src/libvt/tmux.py                             |   8 +-
 tests/test_graphics.py                        |  63 +++++-
 tests/test_status.py                          |  75 +++++++
 tests/test_tmux.py                            |  13 +-
 10 files changed, 489 insertions(+), 149 deletions(-)

diff --git a/CHANGES b/CHANGES
index 380c3bc..b54b628 100644
--- a/CHANGES
+++ b/CHANGES
@@ -78,7 +78,7 @@ and `vt_pty` fixtures alongside {func}`~libvt.testing.assert_screen`,
 {class}`~libvt.terminal.FlightRecorder` ring buffers. See
 {doc}`topics/sync-and-asyncio` for details.
 
-#### Incremental sync deltas, `tmux` capture reconstruction, and graphics (#13–#18)
+#### Incremental sync deltas, `tmux` capture reconstruction, and graphics (#13–#19)
 
 {meth}`~libvt.terminal.Terminal.sync_token` and
 {meth}`~libvt.terminal.Terminal.changes_since` emit non-destructive
@@ -95,11 +95,15 @@ 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).
 {mod}`libvt.graphics` tracks zero-dependency `SIXEL` and Kitty `APC G`
-image metadata ({class}`~libvt.graphics.ImageMeta`) and grid placements
-({class}`~libvt.graphics.ImagePlacement`) across scroll regions and
-profile-specific erase policies. {exc}`~libvt.exc.TerminalTimeoutError`
-attaches multi-line viewport and flight-recorder diagnostics via PEP 678
-`__notes__` while keeping `str(exc)` single-line.
+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`.
+{exc}`~libvt.exc.TerminalTimeoutError` attaches multi-line viewport and
+flight-recorder diagnostics via PEP 678 `__notes__` while keeping
+`str(exc)` single-line.
 
 ### Documentation
 
diff --git a/docs/project/adr/0007-rex-osc-7501-program-status-and-semantic-prompts.md b/docs/project/adr/0007-rex-osc-7501-program-status-and-semantic-prompts.md
index e937cda..63abe45 100644
--- a/docs/project/adr/0007-rex-osc-7501-program-status-and-semantic-prompts.md
+++ b/docs/project/adr/0007-rex-osc-7501-program-status-and-semantic-prompts.md
@@ -68,10 +68,11 @@ capability query:
      `blocked`, and `idle` entries while retaining `done` and `error`; survive
      `DECSTR` soft reset and clear all records on `RIS`.
 2. **Monotonic `OSC 133` prompt zones and host queries (`libvt.terminal`)**:
-   - Store `PromptZone(kind: PromptKind, row: int, abs_row: int, col: int,
+   - Store `PromptZone(kind: PromptKind, abs_row: int, col: int,
      exit_code: int | None)` in a `collections.deque` bounded by
-     `Limits.max_prompt_zones` (`1,024`), updating viewport `row` via
-     `abs_row - scr.scrolled_total` so scrolling never desyncs prompt zones.
+     `Limits.max_prompt_zones` (`1,024`), resolving rows on demand via
+     `Snapshot.at_abs(abs_row)` and `Snapshot.viewport_row(abs_row)` so
+     scrolling never invalidates stored prompt coordinates.
    - Support `OSC 7` and `OSC 9;9` (`term.cwd_uri` for any URI, `term.cwd`
      filtered by `Policy.osc7_hosts` without host syscalls, plus
      `WorkingDirectoryChanged`), `OSC 52` write (`ClipboardWrite` when
diff --git a/src/libvt/events.py b/src/libvt/events.py
index 3fdfa5d..bf5a9d3 100644
--- a/src/libvt/events.py
+++ b/src/libvt/events.py
@@ -30,22 +30,19 @@ class PromptZone:
     ----------
     kind : PromptKind
         Marker kind (``A``, ``B``, ``C``, or ``D``).
-    row : int
-        Zero-based viewport row (negative once scrolled into ``history``).
+    abs_row : int
+        Monotonic row index from the top of primary scroll history so scrolling
+        never invalidates stored coordinates.
     col : int
         Zero-based column index when the marker arrived.
     exit_code : int | None
         Parsed exit status on ``D`` markers when supplied, else ``None``.
-    abs_row : int
-        Monotonic row index from the top of primary scroll history so scrolling
-        never invalidates stored coordinates.
     """
 
     kind: PromptKind
-    row: int
+    abs_row: int
     col: int
     exit_code: int | None = None
-    abs_row: int = 0
 
 
 class EraseCause(enum.StrEnum):
diff --git a/src/libvt/graphics.py b/src/libvt/graphics.py
index ba112b7..681f5fe 100644
--- a/src/libvt/graphics.py
+++ b/src/libvt/graphics.py
@@ -88,16 +88,14 @@ class ImagePlacement:
         Referenced :attr:`ImageMeta.image_id`.
     placement_id : int
         Kitty ``p=`` placement identifier (``0`` when default/unnumbered).
-    row : int
-        Zero-based viewport row (negative when scrolled into history).
+    abs_row : int
+        Monotonic absolute grid row anchor.
     col : int
         Zero-based starting column.
     rows : int
         Height in terminal cells.
     cols : int
         Width in terminal cells.
-    abs_row : int
-        Absolute grid row anchor (``scrolled_total + row``).
     z_index : int
         Signed 32-bit z-index (``0`` default).
     virtual : bool
@@ -127,11 +125,10 @@ class ImagePlacement:
     protocol: GraphicsProtocol
     image_id: int
     placement_id: int
-    row: int
+    abs_row: int
     col: int
     rows: int
     cols: int
-    abs_row: int
     z_index: int = 0
     virtual: bool = False
     parent_image_id: int = 0
@@ -155,18 +152,45 @@ def layer(self) -> ZLayer:
             return ZLayer.BELOW_TEXT
         return ZLayer.ABOVE_TEXT
 
-    def occupies_cell(self, row: int, col: int) -> bool:
-        """Return ``True`` when viewport cell ``(row, col)`` is covered."""
+    def occupies_abs(self, abs_row: int, col: int) -> bool:
+        """Return ``True`` when absolute grid cell ``(abs_row, col)`` is covered.
+
+        Parameters
+        ----------
+        abs_row : int
+            Monotonic absolute row coordinate (for a viewport row ``0 <= r < rows``,
+            pass ``snap.scrolled_total + r``).
+        col : int
+            Zero-based column coordinate.
+
+        Returns
+        -------
+        bool
+            ``True`` when this non-virtual placement covers ``(abs_row, col)``
+            and its cell mask bit (if any) remains set; ``False`` for virtual
+            placements or uncovered cells.
+
+        Raises
+        ------
+        TypeError
+            When *abs_row* or *col* is not an :class:`int` (or is a :class:`bool`).
+        """
+        if isinstance(abs_row, bool) or not isinstance(abs_row, int):
+            msg = f"abs_row must be int, got {type(abs_row).__name__}"
+            raise TypeError(msg)
+        if isinstance(col, bool) or not isinstance(col, int):
+            msg = f"col must be int, got {type(col).__name__}"
+            raise TypeError(msg)
         if self.virtual:
             return False
         if not (
-            self.row <= row < self.row + self.rows
+            self.abs_row <= abs_row < self.abs_row + self.rows
             and self.col <= col < self.col + self.cols
         ):
             return False
         if self.visible_mask is None:
             return True
-        bit = (row - self.row) * self.cols + (col - self.col)
+        bit = (abs_row - self.abs_row) * self.cols + (col - self.col)
         return bool((self.visible_mask >> bit) & 1)
 
 
@@ -299,16 +323,15 @@ class _MutablePlacement:
     cell_offset_y: int = 0
     visible_mask: int | None = None
 
-    def freeze(self, scrolled_total: int) -> ImagePlacement:
+    def freeze(self) -> ImagePlacement:
         return ImagePlacement(
             protocol=self.protocol,
             image_id=self.image_id,
             placement_id=self.placement_id,
-            row=self.abs_row - scrolled_total,
+            abs_row=self.abs_row,
             col=self.col,
             rows=self.rows,
             cols=self.cols,
-            abs_row=self.abs_row,
             z_index=self.z_index,
             virtual=self.virtual,
             parent_image_id=self.parent_image_id,
@@ -476,11 +499,11 @@ def images(self) -> dict[int, ImageMeta]:
         """Return shallow copy of stored :class:`ImageMeta` entries."""
         return dict(self._images)
 
-    def snapshot_placements(self, scrolled_total: int) -> tuple[ImagePlacement, ...]:
-        """Freeze placements relative to *scrolled_total*."""
+    def snapshot_placements(self) -> tuple[ImagePlacement, ...]:
+        """Freeze stored placements into immutable :class:`ImagePlacement` records."""
         if not self._placements:
             return ()
-        return tuple(p.freeze(scrolled_total) for p in self._placements)
+        return tuple(p.freeze() for p in self._placements)
 
     def has_placement_on_row(self, row: int, scrolled_total: int) -> bool:
         """Return ``True`` when any non-virtual placement covers viewport *row*."""
@@ -600,7 +623,30 @@ def on_non_reflow_resize(
                 kept.append(p)
                 continue
             if top_drop_without_history > 0:
-                p.abs_row -= top_drop_without_history
+                new_abs = p.abs_row - top_drop_without_history
+                if new_abs < scrolled_total:
+                    clip_top = scrolled_total - new_abs
+                    if clip_top >= p.rows:
+                        changed = True
+                        continue
+                    keep_rows = p.rows - clip_top
+                    if p.source_height > 0:
+                        crop_px = (p.source_height * clip_top) // p.rows
+                        p.source_y += crop_px
+                        p.source_height = max(1, p.source_height - crop_px)
+                    if (
+                        p.visible_mask is not None
+                        and keep_rows * p.cols <= _MAX_MASK_CELLS
+                    ):
+                        shifted = p.visible_mask >> (clip_top * p.cols)
+                        p.visible_mask = shifted & ((1 << (keep_rows * p.cols)) - 1)
+                        if p.visible_mask == 0:
+                            changed = True
+                            continue
+                    p.rows = keep_rows
+                    p.abs_row = scrolled_total
+                else:
+                    p.abs_row = new_abs
                 changed = True
             if p.abs_row + p.rows <= scrolled_total or p.abs_row >= max_abs:
                 changed = True
@@ -851,16 +897,23 @@ def commit_sixel(
         rows: int,
         cols: int,
         scrolled_total: int,
+        min_abs: int = 0,
     ) -> None:
         """Record a scanned ``SIXEL`` image and placement at post-scroll *row*."""
-        eff_row = row
+        abs_r = scrolled_total + row
         eff_rows = rows
-        if eff_row < 0 and scrolled_total == 0:
-            clip = -eff_row
+        eff_h_px = height_px
+        eff_src_y = 0
+        if abs_r < min_abs:
+            clip = min_abs - abs_r
             if clip >= eff_rows:
                 return
+            if eff_h_px > 0 and eff_rows > 0:
+                crop_px = (eff_h_px * clip) // eff_rows
+                eff_src_y = crop_px
+                eff_h_px = max(1, eff_h_px - crop_px)
             eff_rows -= clip
-            eff_row = 0
+            abs_r = min_abs
         img_id = self._next_auto_id
         self._next_auto_id += 1
         meta = ImageMeta(
@@ -877,12 +930,13 @@ def commit_sixel(
                 protocol=GraphicsProtocol.SIXEL,
                 image_id=img_id,
                 placement_id=0,
-                abs_row=scrolled_total + eff_row,
+                abs_row=max(0, abs_r),
                 col=col,
                 rows=eff_rows,
                 cols=cols,
+                source_y=eff_src_y,
                 source_width=width_px,
-                source_height=height_px,
+                source_height=eff_h_px,
             ),
         )
 
@@ -979,6 +1033,7 @@ def handle_kitty(
         scrolled_total: int = 0,
         cell_width_px: int = 8,
         cell_height_px: int = 16,
+        min_row: int = 0,
         advance_cursor: collections.abc.Callable[[int, int], int] | None = None,
     ) -> bytes | None:
         """Process one Kitty ``APC G`` packet and return optional reply bytes.
@@ -1006,6 +1061,9 @@ def handle_kitty(
             Nominal cell width in pixels.
         cell_height_px : int
             Nominal cell height in pixels.
+        min_row : int
+            Minimum viewport row ceiling when cursor scrolling does not advance
+            scrollback (``0`` default, or active ``DECSTBM`` top margin).
         advance_cursor : collections.abc.Callable[[int, int], int] | None
             Callback invoked with ``(rows, cols)`` prior to committing a
             cursor-moving ``C=0`` placement, returning the post-scroll anchor
@@ -1078,6 +1136,7 @@ def handle_kitty(
                     scrolled_total=cur_scrolled,
                     cell_width_px=cell_width_px,
                     cell_height_px=cell_height_px,
+                    min_row=min_row,
                     advance_cursor=advance_cursor,
                 )
 
@@ -1139,6 +1198,7 @@ def handle_kitty(
                 scrolled_total=cur_scrolled,
                 cell_width_px=cell_width_px,
                 cell_height_px=cell_height_px,
+                min_row=min_row,
                 advance_cursor=advance_cursor,
             )
 
@@ -1152,6 +1212,7 @@ def handle_kitty(
                 scrolled_total=cur_scrolled,
                 cell_width_px=cell_width_px,
                 cell_height_px=cell_height_px,
+                min_row=min_row,
                 advance_cursor=advance_cursor,
             )
 
@@ -1168,6 +1229,7 @@ def _complete_kitty_upload(
         scrolled_total: int,
         cell_width_px: int,
         cell_height_px: int,
+        min_row: int = 0,
         advance_cursor: collections.abc.Callable[[int, int], int] | None,
     ) -> bytes | None:
         ctrl = up.control
@@ -1243,6 +1305,7 @@ def _complete_kitty_upload(
                 scrolled_total=scrolled_total,
                 cell_width_px=cell_width_px,
                 cell_height_px=cell_height_px,
+                min_row=min_row,
                 advance_cursor=advance_cursor,
                 target_meta=meta,
                 reply_image_id=reply_id,
@@ -1310,6 +1373,7 @@ def _place_kitty_image(
         scrolled_total: int,
         cell_width_px: int,
         cell_height_px: int,
+        min_row: int = 0,
         advance_cursor: collections.abc.Callable[[int, int], int] | None,
         target_meta: ImageMeta | None = None,
         reply_image_id: int | None = None,
@@ -1390,11 +1454,22 @@ def _place_kitty_image(
             not virtual and parent_id == 0 and _parse_int(control, "C", 0) == 0
         )
 
+        eff_reply_id = (
+            reply_image_id
+            if target_meta is not None
+            else (
+                meta.image_id
+                if (_parse_int(control, "i", 0) > 0 or _parse_int(control, "I", 0) > 0)
+                else None
+            )
+        )
+
         if parent_pl is not None:
             abs_r = parent_pl.abs_row + _parse_int(control, "V", 0)
             col_pos = max(
                 0, min(screen_cols - 1, parent_pl.col + _parse_int(control, "H", 0))
             )
+            min_abs = 0
         else:
             anchor_r = cursor_row
             if move_cursor and advance_cursor is not None:
@@ -1406,13 +1481,29 @@ def _place_kitty_image(
             )
             abs_r = post_scrolled + anchor_r
             col_pos = cursor_col
+            min_abs = (
+                (post_scrolled + min_row) if post_scrolled == scrolled_total else 0
+            )
+
+        if not virtual and abs_r < min_abs:
+            clip_top = min_abs - abs_r
+            if clip_top >= rows:
+                return _kitty_reply(
+                    control, "OK", is_error=False, reply_image_id=eff_reply_id
+                )
+            if src_h > 0 and rows > 0:
+                crop_px = (src_h * clip_top) // rows
+                src_y += crop_px
+                src_h = max(1, src_h - crop_px)
+            rows -= clip_top
+            abs_r = min_abs
 
         self._append_placement(
             _MutablePlacement(
                 protocol=GraphicsProtocol.KITTY,
                 image_id=meta.image_id,
                 placement_id=pid,
-                abs_row=abs_r,
+                abs_row=max(0, abs_r),
                 col=col_pos,
                 rows=rows,
                 cols=cols,
@@ -1428,15 +1519,6 @@ def _place_kitty_image(
                 cell_offset_y=off_y,
             ),
         )
-        eff_reply_id = (
-            reply_image_id
-            if target_meta is not None
-            else (
-                meta.image_id
-                if (_parse_int(control, "i", 0) > 0 or _parse_int(control, "I", 0) > 0)
-                else None
-            )
-        )
         return _kitty_reply(control, "OK", is_error=False, reply_image_id=eff_reply_id)
 
     def _prune_orphans(self, *, free_images: bool = False) -> None:
diff --git a/src/libvt/screen.py b/src/libvt/screen.py
index 2a35f55..a5eecd9 100644
--- a/src/libvt/screen.py
+++ b/src/libvt/screen.py
@@ -445,6 +445,7 @@ class Screen:
         "_history",
         "_history_clear_at",
         "_history_clear_seq",
+        "_is_alt",
         "_max_image_dimension",
         "_max_images",
         "_max_placements",
@@ -468,6 +469,7 @@ def __init__(
         max_images: int = 256,
         max_placements: int = 1_024,
         max_image_dimension: int = 10_000,
+        is_alt: bool = False,
     ) -> None:
         if rows < 1 or cols < 1:
             msg = f"rows and cols must be >= 1, got ({rows}, {cols})"
@@ -481,6 +483,7 @@ def __init__(
         self._evicted_total: int = 0
         self._history_clear_at: int = 0
         self._history_clear_seq: int = 0
+        self._is_alt: bool = is_alt
         self._cell_height_px: int = max(1, cell_height_px)
         self._max_images: int = max_images
         self._max_placements: int = max_placements
@@ -567,6 +570,7 @@ def clear_all_tabstops(self) -> None:
 
     def clear_history(self) -> None:
         """Clear all sealed scrollback rows (``ED 3``)."""
+        self._evicted_total += len(self._history)
         self._history.clear()
         self._history_clear_at = self._scrolled_total
         self._history_clear_seq += 1
@@ -593,7 +597,7 @@ def placements(self) -> tuple[ImagePlacement, ...]:
         """Return active + scrollback :class:`ImagePlacement` records."""
         if self._gfx is None:
             return ()
-        return self._gfx.snapshot_placements(self._scrolled_total)
+        return self._gfx.snapshot_placements()
 
     def _append_history(self, frozen: FrozenRow) -> None:
         maxlen = self._history.maxlen
@@ -731,14 +735,10 @@ def scroll_up(
                     self._rows[b_row].wrapped = False
                     bump_row_gen(self._rows[b_row])
                 self._clear_row_spacer_head(self._rows[b_row])
-            can_save = (
-                save_history
-                and t_row == 0
-                and self._history.maxlen is not None
-                and self._history.maxlen > 0
-            )
-            hist_adv = shift if (can_save and not full_screen) else 0
-            if self._gfx is not None and not (full_screen and can_save):
+            advances_abs = save_history and t_row == 0 and not self._is_alt
+            has_hist_cap = self._history.maxlen is not None and self._history.maxlen > 0
+            hist_adv = shift if (advances_abs and not full_screen) else 0
+            if self._gfx is not None and not (full_screen and advances_abs):
                 self._gfx.on_region_scroll(
                     top=t_row,
                     bottom=b_row,
@@ -748,26 +748,29 @@ def scroll_up(
                     is_scroll=not is_line_op,
                     scrolled_total=self._scrolled_total,
                     cell_height_px=self._cell_height_px,
-                    history_advanced=(count if (can_save and not full_screen) else 0),
+                    history_advanced=(
+                        count if (advances_abs and not full_screen) else 0
+                    ),
                 )
             evicted = self._rows[t_row : t_row + shift]
-            if can_save:
-                for row_ev in evicted:
-                    self._append_history(row_ev.freeze())
-                extra = count - shift
-                if extra > 0:
-                    maxlen = self._history.maxlen or 0
-                    blank_row = _Row(self._cols)
-                    blank_row.reset_blank(self._cols, bce_word, bce_ext)
-                    blank_frozen = blank_row.freeze()
-                    skip_evict = max(0, extra - maxlen)
-                    if skip_evict > 0:
-                        dropped_existing = min(len(self._history), skip_evict)
-                        for _ in range(dropped_existing):
-                            self._history.popleft()
-                        self._evicted_total += skip_evict
-                    for _ in range(extra - skip_evict):
-                        self._append_history(blank_frozen)
+            if advances_abs:
+                if has_hist_cap:
+                    for row_ev in evicted:
+                        self._append_history(row_ev.freeze())
+                    extra = count - shift
+                    if extra > 0:
+                        maxlen = self._history.maxlen or 0
+                        blank_row = _Row(self._cols)
+                        blank_row.reset_blank(self._cols, bce_word, bce_ext)
+                        blank_frozen = blank_row.freeze()
+                        skip_evict = max(0, extra - maxlen)
+                        if skip_evict > 0:
+                            self._evicted_total += len(self._history) + skip_evict
+                            self._history.clear()
+                        for _ in range(extra - skip_evict):
+                            self._append_history(blank_frozen)
+                else:
+                    self._evicted_total += count
                 self._scrolled_total += count
                 if self._gfx is not None:
                     self._gfx.reap_evicted_history(
@@ -777,7 +780,7 @@ def scroll_up(
             for row_ev in evicted:
                 row_ev.reset_blank(self._cols, bce_word, bce_ext)
             self._rows[b_row - shift + 1 : b_row - shift + 1] = evicted
-            if not (full_screen and can_save):
+            if not (full_screen and advances_abs):
                 stamp_end = len(self._rows) if hist_adv > 0 else (b_row + 1)
                 for idx_s in range(t_row, stamp_end):
                     bump_row_gen(self._rows[idx_s])
@@ -920,13 +923,12 @@ def push_scrollback_and_clear(
             ):
                 last_used = idx
                 break
-        if (
-            last_used >= 0
-            and self._history.maxlen is not None
-            and self._history.maxlen > 0
-        ):
-            for idx in range(last_used + 1):
-                self._append_history(self._rows[idx].freeze())
+        if last_used >= 0 and not self._is_alt:
+            if self._history.maxlen is not None and self._history.maxlen > 0:
+                for idx in range(last_used + 1):
+                    self._append_history(self._rows[idx].freeze())
+            else:
+                self._evicted_total += last_used + 1
             self._scrolled_total += last_used + 1
             if self._gfx is not None:
                 self._gfx.reap_evicted_history(
@@ -1070,12 +1072,20 @@ def _reflow_primary(self, *, rows: int, cols: int) -> None:
         hist_cut = max(0, len(new_all) - rows)
         hist_cut = min(hist_cut, new_cur_abs)
 
+        prev_scrolled = self._scrolled_total
+        prev_evicted = self._evicted_total
         self._history.clear()
         self._evicted_total = 0
         if self._history.maxlen is not None and self._history.maxlen > 0:
             for r_h in new_all[:hist_cut]:
                 self._append_history(r_h.freeze())
-        self._scrolled_total = len(self._history)
+        hist_len = len(self._history)
+        new_evicted = max(
+            prev_evicted + (hist_cut - hist_len),
+            prev_scrolled - hist_len,
+        )
+        self._evicted_total = new_evicted
+        self._scrolled_total = new_evicted + hist_len
 
         viewport = new_all[hist_cut : hist_cut + rows]
         while len(viewport) < rows:
@@ -1117,9 +1127,15 @@ def resize(self, *, rows: int, cols: int, reflow: bool = True) -> None:
                 top_excess = max(0, self._cur_row - (rows - 1))
                 top_drop = min(drop_needed, top_excess)
                 if top_drop > 0:
-                    if self._history.maxlen is not None and self._history.maxlen > 0:
-                        for r_ev in self._rows[:top_drop]:
-                            self._append_history(r_ev.freeze())
+                    if not self._is_alt:
+                        if (
+                            self._history.maxlen is not None
+                            and self._history.maxlen > 0
+                        ):
+                            for r_ev in self._rows[:top_drop]:
+                                self._append_history(r_ev.freeze())
+                        else:
+                            self._evicted_total += top_drop
                         self._scrolled_total += top_drop
                         if self._gfx is not None:
                             self._gfx.reap_evicted_history(
@@ -1255,6 +1271,7 @@ def __init__(
             max_images=max_images,
             max_placements=max_placements,
             max_image_dimension=max_image_dimension,
+            is_alt=True,
         )
         self.active_is_alt: bool = False
 
diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py
index 0f3a757..e4817b1 100644
--- a/src/libvt/terminal.py
+++ b/src/libvt/terminal.py
@@ -497,7 +497,8 @@ class Snapshot:
     active_is_alt : bool
         ``True`` when the alternate screen buffer is active.
     prompt_zones : tuple[PromptZone, ...]
-        Recorded ``OSC 133`` semantic prompt zones adjusted to this viewport.
+        Recorded primary-screen ``OSC 133`` semantic prompt zones (empty when
+        :attr:`active_is_alt` is ``True``).
     program_status : ProgramStatus | None
         Highest-urgency active ``OSC 7501`` / ``OSC 9;4`` status record.
     program_statuses : collections.abc.Mapping[str, ProgramStatus]
@@ -512,9 +513,11 @@ class Snapshot:
 
     __slots__ = (
         "_cols",
+        "_evicted_total",
         "_frozen",
         "_history",
         "_rows",
+        "_scrolled_total",
         "active_is_alt",
         "cursor",
         "cwd",
@@ -547,11 +550,24 @@ def __init__(
         generation: int,
         images: collections.abc.Mapping[int, ImageMeta] | None = None,
         placements: tuple[ImagePlacement, ...] = (),
+        scrolled_total: int | None = None,
+        evicted_total: int | None = None,
     ) -> None:
         object.__setattr__(self, "_frozen", False)
         self._rows = rows
         self._history = history
         self._cols = cols
+        eff_scrolled = (
+            (0 if active_is_alt else len(history))
+            if scrolled_total is None
+            else scrolled_total
+        )
+        self._scrolled_total = eff_scrolled
+        self._evicted_total = (
+            (0 if active_is_alt else max(0, eff_scrolled - len(history)))
+            if evicted_total is None
+            else evicted_total
+        )
         self.cursor = cursor
         self.title = title
         self.cwd = cwd
@@ -622,6 +638,78 @@ def cols(self) -> int:
         """Return snapshot width in columns."""
         return self._cols
 
+    @property
+    def scrolled_total(self) -> int:
+        """Return monotonic count of rows scrolled off the active screen's top."""
+        return self._scrolled_total
+
+    @property
+    def evicted_total(self) -> int:
+        """Return count of scrollback rows evicted from the active screen."""
+        return self._evicted_total
+
+    def viewport_row(self, abs_row: int) -> int | None:
+        """Return zero-based viewport row for *abs_row*, or ``None``.
+
+        Parameters
+        ----------
+        abs_row : int
+            Monotonic absolute row coordinate (e.g.
+            :attr:`~libvt.events.PromptZone.abs_row` or
+            :attr:`~libvt.graphics.ImagePlacement.abs_row`).
+
+        Returns
+        -------
+        int | None
+            ``0 <= row < rows`` when *abs_row* is visible in this snapshot's
+            active viewport, else ``None``.
+        """
+        if isinstance(abs_row, bool) or not isinstance(abs_row, int):
+            msg = f"abs_row must be int, got {type(abs_row).__name__}"
+            raise TypeError(msg)
+        rel = abs_row - self._scrolled_total
+        if 0 <= rel < len(self._rows):
+            return rel
+        return None
+
+    def at_abs(self, abs_row: int) -> RowView:
+        """Return :class:`~libvt.screen.RowView` at *abs_row* in history or viewport.
+
+        Parameters
+        ----------
+        abs_row : int
+            Monotonic absolute row coordinate.
+
+        Returns
+        -------
+        RowView
+            Immutable view of the row from scrollback or the active viewport.
+
+        Raises
+        ------
+        IndexError
+            When *abs_row* has been evicted from history or is out of range.
+        """
+        if isinstance(abs_row, bool) or not isinstance(abs_row, int):
+            msg = f"abs_row must be int, got {type(abs_row).__name__}"
+            raise TypeError(msg)
+        if self.active_is_alt:
+            if 0 <= abs_row < len(self._rows):
+                return RowView(self._rows[abs_row])
+            msg = f"abs_row {abs_row} out of range for alternate screen"
+            raise IndexError(msg)
+        first_abs = self._scrolled_total - len(self._history)
+        if abs_row < first_abs:
+            msg = f"abs_row {abs_row} was evicted (earliest retained is {first_abs})"
+            raise IndexError(msg)
+        if abs_row < self._scrolled_total:
+            return RowView(self._history[abs_row - first_abs])
+        rel = abs_row - self._scrolled_total
+        if rel < len(self._rows):
+            return RowView(self._rows[rel])
+        msg = f"abs_row {abs_row} out of range"
+        raise IndexError(msg)
+
     @property
     def history(self) -> tuple[RowView, ...]:
         """Return immutable :class:`RowView` sequence over scrollback rows."""
@@ -681,6 +769,8 @@ def to_dict(self) -> dict[str, t.Any]:
         return {
             "rows": self.rows,
             "cols": self.cols,
+            "scrolled_total": self.scrolled_total,
+            "evicted_total": self.evicted_total,
             "lines": list(self.lines),
             "history_lines": [fr.text for fr in self._history],
             "cursor": {
@@ -719,7 +809,8 @@ def to_dict(self) -> dict[str, t.Any]:
                     "protocol": p.protocol.value,
                     "image_id": p.image_id,
                     "placement_id": p.placement_id,
-                    "row": p.row,
+                    "abs_row": p.abs_row,
+                    "viewport_row": self.viewport_row(p.abs_row),
                     "col": p.col,
                     "rows": p.rows,
                     "cols": p.cols,
@@ -1324,18 +1415,8 @@ def sync_generation(self) -> int:
 
     @property
     def prompt_zones(self) -> tuple[PromptZone, ...]:
-        """Return recorded ``OSC 133`` prompt zones adjusted to current viewport."""
-        scrolled = self._screens.primary.scrolled_total
-        return tuple(
-            PromptZone(
-                kind=z.kind,
-                row=z.abs_row - scrolled,
-                col=z.col,
-                exit_code=z.exit_code,
-                abs_row=z.abs_row,
-            )
-            for z in self._prompt_zones
-        )
+        """Return recorded primary-screen ``OSC 133`` semantic prompt zones."""
+        return tuple(self._prompt_zones)
 
     @property
     def program_status(self) -> ProgramStatus | None:
@@ -1394,6 +1475,7 @@ def _build_snapshot(
         modes = self._modes.enabled_modes()
         if exclude_modes:
             modes = modes - exclude_modes
+        active_alt = self._screens.active_is_alt
         return Snapshot(
             rows=tuple(r.clone() for r in scr._rows),
             history=tuple(self._screens.primary._history),
@@ -1403,13 +1485,15 @@ def _build_snapshot(
             cwd=self._cwd,
             cwd_uri=self._cwd_uri,
             modes=modes,
-            active_is_alt=self._screens.active_is_alt,
-            prompt_zones=self.prompt_zones,
+            active_is_alt=active_alt,
+            prompt_zones=() if active_alt else tuple(self._prompt_zones),
             program_status=self._status_store.most_urgent,
             program_statuses=self._status_store.records,
             generation=self._generation,
             images=scr.images,
             placements=scr.placements,
+            scrolled_total=scr._scrolled_total,
+            evicted_total=scr._evicted_total,
         )
 
     def _live_sync_token(
@@ -1542,26 +1626,37 @@ def _full(reason: ResyncReason) -> ScreenDelta:
 
         hist_cleared = cur_tok.history_clear_seq != token.history_clear_seq
         hist_len = len(cur_snap._history)
+        zero_hist_cap = self._screens.primary._history.maxlen == 0 and hist_len == 0
         if hist_cleared:
-            post_clear = max(0, cur_tok.scrolled_total - cur_tok.history_clear_at)
-            if post_clear > hist_len:
-                return _full(ResyncReason.HISTORY_EVICTED)
-            new_hist = (
-                tuple(RowView(fr) for fr in cur_snap._history[hist_len - post_clear :])
-                if post_clear > 0
-                else ()
-            )
-            evicted_cnt = 0
+            if zero_hist_cap:
+                new_hist = ()
+                evicted_cnt = 0
+            else:
+                post_clear = max(0, cur_tok.scrolled_total - cur_tok.history_clear_at)
+                if post_clear > hist_len:
+                    return _full(ResyncReason.HISTORY_EVICTED)
+                new_hist = (
+                    tuple(
+                        RowView(fr) for fr in cur_snap._history[hist_len - post_clear :]
+                    )
+                    if post_clear > 0
+                    else ()
+                )
+                evicted_cnt = 0
         else:
             added = max(0, cur_tok.scrolled_total - token.scrolled_total)
-            if added > hist_len:
-                return _full(ResyncReason.HISTORY_EVICTED)
-            new_hist = (
-                tuple(RowView(fr) for fr in cur_snap._history[hist_len - added :])
-                if added > 0
-                else ()
-            )
-            evicted_cnt = max(0, cur_tok.evicted_total - token.evicted_total)
+            if zero_hist_cap:
+                new_hist = ()
+                evicted_cnt = 0
+            else:
+                if added > hist_len:
+                    return _full(ResyncReason.HISTORY_EVICTED)
+                new_hist = (
+                    tuple(RowView(fr) for fr in cur_snap._history[hist_len - added :])
+                    if added > 0
+                    else ()
+                )
+                evicted_cnt = max(0, cur_tok.evicted_total - token.evicted_total)
 
         v_scroll = (
             0
@@ -1999,10 +2094,9 @@ def _shift_prompt_zones_below(
                 updated.append(
                     PromptZone(
                         kind=z.kind,
-                        row=z.row,
+                        abs_row=z.abs_row + count,
                         col=z.col,
                         exit_code=z.exit_code,
-                        abs_row=z.abs_row + count,
                     ),
                 )
                 changed = True
@@ -3812,23 +3906,24 @@ def _handle_osc(self, code: int, data: bytes, terminator: bytes) -> None:
                     and parts[1].lstrip("-").isdigit()
                 ):
                     exit_code = int(parts[1])
-                abs_r = self._screens.primary.scrolled_total + scr._cur_row
-                zone = PromptZone(
-                    kind=kind,
-                    row=scr._cur_row,
-                    col=scr._cur_col,
-                    exit_code=exit_code,
-                    abs_row=abs_r,
-                )
-                self._prompt_zones.append(zone)
-                self._aux_revision += 1
-                self._step_event |= StopOn.PROMPT_MARK
-                self._emit_event(PromptMark(zone=zone))
+                if not self._screens.active_is_alt:
+                    abs_r = self._screens.primary.scrolled_total + scr._cur_row
+                    zone = PromptZone(
+                        kind=kind,
+                        abs_row=abs_r,
+                        col=scr._cur_col,
+                        exit_code=exit_code,
+                    )
+                    self._prompt_zones.append(zone)
+                    self._aux_revision += 1
+                    self._step_event |= StopOn.PROMPT_MARK
+                    self._emit_event(PromptMark(zone=zone))
                 if (
                     kind == PromptKind.PROMPT_START
                     and not is_continuation
                     and self._status_store.on_prompt_start()
                 ):
+                    self._aux_revision += 1
                     self._emit_event(
                         ProgramStatusChanged(status=self._status_store.most_urgent),
                     )
@@ -3972,12 +4067,21 @@ def _handle_dcs(
                 )
                 if prepared is not None:
                     w_px, h_px, s_rows, s_cols = prepared
+                    pre_scrolled = scr._scrolled_total
+                    top, bottom, left, right = self._effective_margins(scr)
+                    in_margins = top <= orig_row <= bottom and left <= orig_col <= right
                     if decsdm:
                         post_r = anchor_r
                         eff_rows = max(1, min(s_rows, scr.rows - anchor_r))
+                        min_sixel_abs = 0
                     else:
                         post_r = self._advance_rows(scr, s_rows, final_col=0)
                         eff_rows = min(s_rows, max(1, scr.rows - post_r))
+                        min_sixel_abs = (
+                            scr._scrolled_total + (top if in_margins else 0)
+                            if scr._scrolled_total == pre_scrolled
+                            else scr._scrolled_total - len(scr._history)
+                        )
                     gfx.commit_sixel(
                         payload_len=len(data),
                         width_px=w_px,
@@ -3987,6 +4091,7 @@ def _handle_dcs(
                         rows=eff_rows,
                         cols=s_cols,
                         scrolled_total=scr._scrolled_total,
+                        min_abs=min_sixel_abs,
                     )
             if self._record_events or self._on_event is not None:
                 self._emit_event(
@@ -4026,6 +4131,8 @@ def _handle_apc(self, data: bytes) -> None:
                         control[k] = v
                 if self._policy.track_graphics:
                     self._before_mutate()
+                    top, bottom, left, right = self._effective_margins(scr)
+                    in_margins = top <= orig_row <= bottom and left <= orig_col <= right
 
                     def _advance_kitty(p_rows: int, p_cols: int) -> int:
                         target_x = orig_col + p_cols
@@ -4045,6 +4152,7 @@ def _advance_kitty(p_rows: int, p_cols: int) -> int:
                         scrolled_total=scr._scrolled_total,
                         cell_width_px=self._profile.cell_width_px,
                         cell_height_px=self._profile.cell_height_px,
+                        min_row=(top if in_margins else 0),
                         advance_cursor=_advance_kitty,
                     )
                     if reply is not None:
diff --git a/src/libvt/tmux.py b/src/libvt/tmux.py
index a6bab9a..9c6b270 100644
--- a/src/libvt/tmux.py
+++ b/src/libvt/tmux.py
@@ -706,24 +706,20 @@ def _populate_screen_from_lines(
     zones: list[PromptZone] = []
     for idx in range(dropped_hist, len(flags_list)):
         fl = flags_list[idx]
-        abs_r = idx
-        rel_r = idx - hist_count
         if fl & TmuxLineFlags.START_PROMPT:
             zones.append(
                 PromptZone(
                     kind=PromptKind.PROMPT_START,
-                    row=rel_r,
+                    abs_row=idx,
                     col=0,
-                    abs_row=abs_r,
                 ),
             )
         if fl & TmuxLineFlags.START_OUTPUT:
             zones.append(
                 PromptZone(
                     kind=PromptKind.COMMAND_EXECUTED,
-                    row=rel_r,
+                    abs_row=idx,
                     col=0,
-                    abs_row=abs_r,
                 ),
             )
 
diff --git a/tests/test_graphics.py b/tests/test_graphics.py
index 730d4a3..a5b252f 100644
--- a/tests/test_graphics.py
+++ b/tests/test_graphics.py
@@ -36,7 +36,8 @@ def test_kitty_chunked_upload_validation_and_relative_placements() -> None:
     assert b"\x1b_Gi=7,p=1;OK\x1b\\" in term.drain_replies()
     assert len(term.placements) == 1
     kp = term.placements[0]
-    assert (kp.protocol, kp.row, kp.col, kp.rows, kp.cols, kp.layer) == (
+    assert not hasattr(kp, "row")
+    assert (kp.protocol, kp.abs_row, kp.col, kp.rows, kp.cols, kp.layer) == (
         GraphicsProtocol.KITTY,
         1,
         2,
@@ -44,6 +45,7 @@ def test_kitty_chunked_upload_validation_and_relative_placements() -> None:
         2,
         ZLayer.BELOW_TEXT,
     )
+    assert term.snapshot().viewport_row(kp.abs_row) == 1
     assert (term.cursor.row, term.cursor.col) == (2, 4)
 
     # U=0 overlay survives text overwrite; d=y with missing y=0 is a safe no-op.
@@ -83,7 +85,8 @@ def test_kitty_chunked_upload_validation_and_relative_placements() -> None:
     term.drain_replies()
     child = [p for p in term.placements if p.image_id == 20 and p.placement_id == 4]
     assert len(child) == 1
-    assert (child[0].row, child[0].col) == (2, 3)
+    assert (child[0].abs_row, child[0].col) == (2, 3)
+    assert term.snapshot().viewport_row(child[0].abs_row) == 2
     term.feed(b"\x1b_Ga=d,d=i,i=20,p=3\x1b\\")
     assert not any(
         p.image_id == 20 and p.placement_id in (3, 4) for p in term.placements
@@ -95,7 +98,53 @@ def test_scroll_before_place_sixel_erase_policies_and_event_immutability() -> No
     alt_t = libvt.Terminal(rows=4, cols=8)
     raw_2row = base64.b64encode(b"\xaa" * (16 * 32 * 3))
     alt_t.feed(b"\x1b[?1049h\x1b[4;2H\x1b_Ga=T,f=24,s=16,v=32;" + raw_2row + b"\x1b\\")
-    assert (alt_t.placements[0].row, alt_t.placements[0].rows) == (2, 2)
+    alt_snap = alt_t.snapshot()
+    assert (alt_snap.placements[0].abs_row, alt_snap.placements[0].rows) == (2, 2)
+    assert alt_snap.viewport_row(alt_snap.placements[0].abs_row) == 2
+    assert alt_snap.to_dict()["scrolled_total"] == 0
+    assert alt_snap.to_dict()["placements"][0]["abs_row"] == 2
+    assert alt_snap.to_dict()["placements"][0]["viewport_row"] == 2
+    with pytest.raises(IndexError):
+        alt_snap.at_abs(-1)
+    with pytest.raises(IndexError):
+        alt_snap.at_abs(4)
+
+    # Tall Kitty image on alt screen crops top rows at abs_row == 0, never < 0.
+    tall_raw = base64.b64encode(b"\xff" * (8 * 80 * 3))
+    alt_tall = libvt.Terminal(rows=4, cols=10)
+    alt_tall.feed(
+        b"\x1b[?1049h\x1b[3;1H\x1b_Ga=T,f=24,s=8,v=80;" + tall_raw + b"\x1b\\"
+    )
+    tall_snap = alt_tall.snapshot()
+    assert (tall_snap.placements[0].abs_row, tall_snap.placements[0].rows) == (0, 4)
+    assert tall_snap.viewport_row(tall_snap.placements[0].abs_row) == 0
+    assert tall_snap.at_abs(tall_snap.placements[0].abs_row).text == tall_snap[0].text
+
+    # Alt-screen non-reflow resize dropping top rows crops straddling placement to 0.
+    alt_rz = libvt.Terminal(rows=4, cols=10)
+    alt_rz.feed(
+        b"\x1b[?1049h\x1b[2;1H\x1b_Ga=T,f=24,s=16,v=32;" + raw_2row + b"\x1b\\\x1b[4;1H"
+    )
+    alt_rz.resize(rows=2, cols=10)
+    rz_snap = alt_rz.snapshot()
+    assert (rz_snap.placements[0].abs_row, rz_snap.placements[0].rows) == (0, 1)
+    assert rz_snap.viewport_row(rz_snap.placements[0].abs_row) == 0
+
+    # Tall SIXEL spans scrollback + viewport on primary, and crops at 0 on alt.
+    sixel_8r = b'\x1bP0;1;0q"1;1;16;128#0!16~\x1b\\'
+    prim_sixel = libvt.Terminal(rows=4, cols=10, scrollback=10)
+    prim_sixel.feed(b"\x1b[4;1H" + sixel_8r)
+    ps_snap = prim_sixel.snapshot()
+    assert (ps_snap.placements[0].abs_row, ps_snap.placements[0].rows) == (3, 8)
+    assert ps_snap.viewport_row(ps_snap.placements[0].abs_row) is None
+    assert ps_snap.placements[0].occupies_abs(ps_snap.scrolled_total + 0, 0) is True
+
+    sixel_5r = b'\x1bP0;1;0q"1;1;16;80#0!16~\x1b\\'
+    alt_sixel = libvt.Terminal(rows=4, cols=10)
+    alt_sixel.feed(b"\x1b[?1049h\x1b[3;1H" + sixel_5r)
+    as_snap = alt_sixel.snapshot()
+    assert (as_snap.placements[0].abs_row, as_snap.placements[0].rows) == (0, 3)
+    assert as_snap.viewport_row(as_snap.placements[0].abs_row) == 0
 
     sixel_seq = b'\x1bP0;1;0q"1;1;16;32#0!16~-#0!16~-#0!16~-#0!16~-#0!16~\x1b\\'
     vt_sixel = libvt.Terminal(rows=6, cols=10, profile=Profile.tmux("next-3.9"))
@@ -103,9 +152,13 @@ def test_scroll_before_place_sixel_erase_policies_and_event_immutability() -> No
     assert (vt_sixel.placements[0].rows, vt_sixel.cursor.row) == (2, 2)
     vt_sixel.feed(b"\x1b[1;1HX")
     assert (
-        vt_sixel.placements[0].occupies_cell(0, 0),
-        vt_sixel.placements[0].occupies_cell(0, 1),
+        vt_sixel.placements[0].occupies_abs(0, 0),
+        vt_sixel.placements[0].occupies_abs(0, 1),
     ) == (False, True)
+    with pytest.raises(TypeError):
+        vt_sixel.placements[0].occupies_abs(True, 0)
+    with pytest.raises(TypeError):
+        vt_sixel.placements[0].occupies_abs(0, False)
 
     tm38_sixel = libvt.Terminal(rows=6, cols=10, profile=Profile.tmux("3.8a"))
     tm38_sixel.feed(sixel_seq + b"\x1b[1;1HX")
diff --git a/tests/test_status.py b/tests/test_status.py
index 6b0c80a..253d724 100644
--- a/tests/test_status.py
+++ b/tests/test_status.py
@@ -4,6 +4,8 @@
 
 import base64
 
+import pytest
+
 import libvt
 from libvt.config import Policy, Profile
 from libvt.events import (
@@ -95,6 +97,79 @@ def test_osc_133_osc_7_osc_52_queries_and_tmux_passthrough() -> None:
     zones = term.prompt_zones
     assert [z.abs_row for z in zones] == sorted(z.abs_row for z in zones)
     assert zones[-1].exit_code == 0
+    assert not hasattr(zones[0], "row")
+
+    snap = term.snapshot()
+    assert snap.viewport_row(zones[0].abs_row) is None
+    assert snap.at_abs(zones[0].abs_row).text == "$ c0"
+    last_vr = snap.viewport_row(zones[-1].abs_row)
+    assert last_vr is not None
+    assert snap.at_abs(zones[-1].abs_row).text == snap[last_vr].text
+
+    evict_term = libvt.Terminal(rows=2, cols=12, scrollback=1)
+    evict_term.feed(b"\x1b]133;A\x07p0\r\np1\r\np2\r\np3")
+    evict_snap = evict_term.snapshot()
+    assert (evict_snap.scrolled_total, evict_snap.evicted_total) == (2, 1)
+    evicted_zone = evict_snap.prompt_zones[0]
+    assert evict_snap.viewport_row(evicted_zone.abs_row) is None
+    with pytest.raises(IndexError):
+        evict_snap.at_abs(evicted_zone.abs_row)
+
+    zero_sb = libvt.Terminal(rows=2, cols=12, scrollback=0)
+    zero_tok = zero_sb.sync_token()
+    zero_sb.feed(b"\x1b[3J\x1b]133;A\x07cmd\r\nline1\r\nline2")
+    zero_delta = zero_sb.changes_since(zero_tok)
+    assert zero_delta.full_resync is False
+    zero_snap = zero_sb.snapshot()
+    assert (zero_snap.scrolled_total, zero_snap.evicted_total) == (1, 1)
+    assert zero_snap.viewport_row(zero_snap.prompt_zones[0].abs_row) is None
+    with pytest.raises(IndexError):
+        zero_snap.at_abs(zero_snap.prompt_zones[0].abs_row)
+    assert zero_snap.at_abs(1).text == "line1"
+    assert zero_snap.at_abs(2).text == "line2"
+    zero_sb.resize(rows=2, cols=14, reflow=True)
+    zero_reflow = zero_sb.snapshot()
+    assert (zero_reflow.scrolled_total, zero_reflow.evicted_total) == (1, 1)
+    assert zero_reflow.at_abs(1).text == "line1"
+
+    ed3_term = libvt.Terminal(rows=2, cols=12, scrollback=10)
+    ed3_term.feed(b"\x1b]133;A\x07old\r\nv0\r\nv1\x1b[3J")
+    ed3_snap = ed3_term.snapshot()
+    assert (ed3_snap.scrolled_total, ed3_snap.evicted_total) == (1, 1)
+    assert ed3_snap.viewport_row(ed3_snap.prompt_zones[0].abs_row) is None
+    with pytest.raises(IndexError):
+        ed3_snap.at_abs(ed3_snap.prompt_zones[0].abs_row)
+    assert ed3_snap.at_abs(1).text == "v0"
+    with pytest.raises(TypeError):
+        ed3_snap.at_abs(True)
+    with pytest.raises(TypeError):
+        ed3_snap.viewport_row(False)
+
+    # Alt-screen OSC 133;A pruning ProgramStatusStore bumps _aux_revision for sync.
+    alt_st = libvt.Terminal(rows=3, cols=16)
+    alt_st.feed(b"\x1b[?1049h\x1b]7501;state=working:id=job\x07")
+    st_tok = alt_st.sync_token()
+    alt_st.feed(b"\x1b]133;A\x07")
+    assert alt_st.committed.program_status is None
+    assert alt_st.changes_since(st_tok).metadata_changed is True
+
+    # Multi-row scroll > rows + scrollback preserves scrolled == evicted + len(history).
+    bulk_sb = libvt.Terminal(rows=2, cols=8, scrollback=3)
+    bulk_sb.feed(b'r0\r\nr1\x1bP0;1;0q"1;1;8;160#0!8~\x1b\\')
+    bulk_snap = bulk_sb.snapshot()
+    assert (
+        bulk_snap.scrolled_total,
+        bulk_snap.evicted_total,
+        len(bulk_snap.history),
+    ) == (10, 7, 3)
+
+    # Reflow overflowing scrollback preserves scrolled == evicted + len(history).
+    narrow_sb = libvt.Terminal(rows=2, cols=10, scrollback=2)
+    narrow_sb.feed(b"0123456789\r\nabcdefghij")
+    narrow_sb.resize(rows=2, cols=2, reflow=True)
+    narrow_snap = narrow_sb.snapshot()
+    assert (narrow_snap.scrolled_total, narrow_snap.evicted_total) == (8, 6)
+    assert narrow_snap.at_abs(6).text == "cd"
 
     term.feed(b"\x1b]7;file://localhost/tmp/my%20dir\x07")
     assert (term.cwd, term.cwd_uri) == ("/tmp/my dir", "file://localhost/tmp/my%20dir")
diff --git a/tests/test_tmux.py b/tests/test_tmux.py
index 811a108..099e2c5 100644
--- a/tests/test_tmux.py
+++ b/tests/test_tmux.py
@@ -107,10 +107,17 @@ def test_capture_decoder_acs_tabs_joined_wraps_and_prompt_zones() -> None:
         scrollback=1,
         flagged=True,
     )
-    assert [(z.row, z.kind.value) for z in pz_snap.prompt_zones] == [
-        (-1, "A"),
-        (1, "C"),
+    assert [
+        (z.abs_row, pz_snap.viewport_row(z.abs_row), z.kind.value)
+        for z in pz_snap.prompt_zones
+    ] == [
+        (1, None, "A"),
+        (3, 1, "C"),
     ]
+    assert pz_snap.at_abs(pz_snap.prompt_zones[0].abs_row).text == "H1"
+    assert pz_snap.at_abs(pz_snap.prompt_zones[1].abs_row).text == "V1"
+    with pytest.raises(IndexError):
+        pz_snap.at_abs(0)
 
     meta = TmuxPaneMetadata(
         cols=8,

From d9a07745c0cc44d6bfe482acba9f0001978b99e9 Mon Sep 17 00:00:00 2001
From: Tony Narlock 
Date: Sun, 22 Nov 2026 20:16:08 -0600
Subject: [PATCH 29/29] grid(fix[history]): Add CoW Sequence history (#20)

why:
- _Row.freeze omitted per-column cell tuples whenever combining marks
  and wide SPACER_TAIL empty strings cancelled out to len(text) ==
  text_used, dropping wide glyphs in FrozenRow.char_at and RowView.runs,
  while FrozenRow.used truncated trailing BCE spans when cells existed.
- Materializing tuple(RowView(fr) ...) on every snapshot() and history
  access scaled as O(scrollback).

what:
- Populate FrozenRow.cells whenever "" is in chars[:text_used] or
  len(text) != text_used, include run_end and ext_end in FrozenRow.used,
  cache clean _frozen rows on _Row, binary-search FrozenRow.attr_at and
  ext_at via bisect_right, and coalesce FrozenRow runs in O(R + E).
- Store primary scrollback in 256-row CoW blocks (_HistoryBuffer /
  _FrozenHistory) exposed as Sequence[RowView] via _HistoryView, and add
  value-based RowView.__eq__.
---
 CHANGES                                       |   7 +-
 ...tier-packed-viewport-and-rle-scrollback.md |   7 +-
 src/libvt/_grid.py                            | 241 +++++++++++-
 src/libvt/screen.py                           | 359 ++++++++++++++++--
 src/libvt/terminal.py                         |  43 +--
 src/libvt/tmux.py                             |   1 +
 tests/test_screen.py                          |  96 +++++
 tests/test_terminal.py                        |   2 +-
 8 files changed, 682 insertions(+), 74 deletions(-)

diff --git a/CHANGES b/CHANGES
index b54b628..9a63634 100644
--- a/CHANGES
+++ b/CHANGES
@@ -78,14 +78,15 @@ and `vt_pty` fixtures alongside {func}`~libvt.testing.assert_screen`,
 {class}`~libvt.terminal.FlightRecorder` ring buffers. See
 {doc}`topics/sync-and-asyncio` for details.
 
-#### Incremental sync deltas, `tmux` capture reconstruction, and graphics (#13–#19)
+#### 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
 `"committed"` (`?2026`-held) and `"working"` views, paired with
-{meth}`~libvt.terminal.ScreenDelta.apply_lines` and
-{meth}`~libvt.terminal.ScreenDelta.apply_rows`.
+{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.
 
 {func}`~libvt.tmux.decode_tmux_capture`,
 {class}`~libvt.tmux.TmuxPaneMetadata`, and
diff --git a/docs/project/adr/0003-two-tier-packed-viewport-and-rle-scrollback.md b/docs/project/adr/0003-two-tier-packed-viewport-and-rle-scrollback.md
index 43cbff9..b19f55f 100644
--- a/docs/project/adr/0003-two-tier-packed-viewport-and-rle-scrollback.md
+++ b/docs/project/adr/0003-two-tier-packed-viewport-and-rle-scrollback.md
@@ -81,8 +81,11 @@ cold run-length-encoded (`RLE`) scrollback lines:
    - `RowView` wraps either a live `_Row` or a `FrozenRow`, exposing `.text`,
      `.wrapped`, `row[col] -> Cell` (returning `BLANK_CELL` when default), and
      `.runs -> tuple[RowRun, ...]` for `O(runs)` styled span rendering.
-   - Both `Screen.history` and `Snapshot.history` return `tuple[RowView, ...]`
-     without leaking mutable `deque` or private `_Row` internals.
+   - Primary scrollback stores `FrozenRow` records in `256`-row copy-on-write
+     tuple blocks (`_FrozenHistory` / `_HistoryView`), so `Screen.history`,
+     `Terminal.history`, and `Snapshot.history` satisfy
+     `collections.abc.Sequence[RowView]` with `O(1)` snapshot capture and
+     `O(1)` random row indexing without leaking mutable storage.
 
 ## Alternatives considered
 
diff --git a/src/libvt/_grid.py b/src/libvt/_grid.py
index 2e44053..263f546 100644
--- a/src/libvt/_grid.py
+++ b/src/libvt/_grid.py
@@ -16,6 +16,10 @@
 from __future__ import annotations
 
 import array
+import bisect
+import collections.abc
+import operator
+import typing as t
 from dataclasses import dataclass
 
 from libvt._ucd import WidthRole
@@ -30,6 +34,11 @@
     UnderlineStyle,
 )
 
+_ITEM0 = operator.itemgetter(0)
+_HISTORY_BLOCK_SHIFT = 8
+_HISTORY_BLOCK_SIZE = 1 << _HISTORY_BLOCK_SHIFT
+_HISTORY_BLOCK_MASK = _HISTORY_BLOCK_SIZE - 1
+
 _GLOBAL_ROW_GEN: int = 0
 
 
@@ -38,6 +47,7 @@ def bump_row_gen(row: _Row) -> int:
     global _GLOBAL_ROW_GEN
     _GLOBAL_ROW_GEN += 1
     row.content_gen = _GLOBAL_ROW_GEN
+    row._frozen = None
     return _GLOBAL_ROW_GEN
 
 
@@ -222,11 +232,10 @@ class FrozenRow:
     @property
     def used(self) -> int:
         """Return count of written columns in this sealed row."""
-        if self.cells is not None:
-            return len(self.cells)
+        text_cols = len(self.cells) if self.cells is not None else len(self.text)
         run_end = self.runs[-1][0] if self.runs else 0
         ext_end = (self.exts[-1][0] + 1) if self.exts else 0
-        return max(len(self.text), run_end, ext_end)
+        return max(text_cols, run_end, ext_end)
 
     def rstrip_text(self) -> str:
         """Return right-trimmed row text."""
@@ -234,24 +243,34 @@ def rstrip_text(self) -> str:
 
     def char_at(self, col: int) -> str:
         """Return cell string at *col*."""
+        if col < 0 or col >= self.cols:
+            return " "
         if self.cells is not None:
             return self.cells[col] if col < len(self.cells) else " "
         return self.text[col] if col < len(self.text) else " "
 
     def attr_at(self, col: int) -> int:
         """Return packed 64-bit attribute word at *col*."""
-        for end_col, word in self.runs:
-            if col < end_col:
-                return word
-        return 0
+        runs = self.runs
+        if not runs or col < 0:
+            return 0
+        if len(runs) == 1:
+            end_col, word = runs[0]
+            return word if col < end_col else 0
+        idx = bisect.bisect_right(runs, col, key=_ITEM0)
+        return runs[idx][1] if idx < len(runs) else 0
 
     def ext_at(self, col: int) -> _CellExt | None:
         """Return sparse :class:`_CellExt` at *col*, if any."""
-        for ext_col, ce in self.exts:
-            if ext_col == col:
-                return ce
-            if ext_col > col:
-                break
+        exts = self.exts
+        if not exts or col < 0:
+            return None
+        if len(exts) == 1:
+            ext_col, ce = exts[0]
+            return ce if ext_col == col else None
+        idx = bisect.bisect_right(exts, col, key=_ITEM0) - 1
+        if idx >= 0 and exts[idx][0] == col:
+            return exts[idx][1]
         return None
 
     def thaw(self, target_cols: int | None = None) -> _Row:
@@ -292,6 +311,8 @@ class _Row:
     """Mutable viewport row with lazy 64-bit ``array('Q')`` promotion."""
 
     __slots__ = (
+        "_frozen",
+        "_wrapped",
         "attrs",
         "chars",
         "content_gen",
@@ -300,7 +321,6 @@ class _Row:
         "text_used",
         "uniform_attr",
         "used",
-        "wrapped",
     )
 
     def __init__(self, cols: int) -> None:
@@ -311,8 +331,20 @@ def __init__(self, cols: int) -> None:
         self.ext: dict[int, _CellExt] | None = None
         self.used: int = 0
         self.text_used: int = 0
-        self.wrapped: bool = False
+        self._wrapped: bool = False
         self.content_gen: int = 0
+        self._frozen: FrozenRow | None = None
+
+    @property
+    def wrapped(self) -> bool:
+        """Return ``True`` when this row soft-wrapped onto the next line."""
+        return self._wrapped
+
+    @wrapped.setter
+    def wrapped(self, value: bool) -> None:
+        if self._wrapped != value:
+            self._wrapped = value
+            self._frozen = None
 
     def _ensure_attrs(self) -> array.array[int]:
         if self.attrs is None:
@@ -358,7 +390,7 @@ def reset_blank(
                 self.ext.clear()
             self.used = cols if bce_word != 0 else 0
         self.text_used = 0
-        self.wrapped = False
+        self._wrapped = False
         bump_row_gen(self)
 
     def _set_raw(
@@ -825,20 +857,23 @@ def clone(self) -> _Row:
         dup.ext = self.ext.copy() if self.ext else None
         dup.used = self.used
         dup.text_used = self.text_used
-        dup.wrapped = self.wrapped
+        dup._wrapped = self._wrapped
         dup.content_gen = self.content_gen
+        dup._frozen = self._frozen
         return dup
 
     def freeze(self) -> FrozenRow:
         """Seal this row into a compact run-length-encoded :class:`FrozenRow`."""
+        if self._frozen is not None:
+            return self._frozen
         cols = len(self.chars)
         t_used = self.text_used
         text = "".join(self.chars[:t_used])
         cells: tuple[str, ...] | None = None
-        if len(text) != t_used:
+        if len(text) != t_used or "" in self.chars[:t_used]:
             cells = tuple(self.chars[:t_used])
 
-        u = min(cols, self.used)
+        u = min(cols, max(self.used, t_used))
         runs: tuple[tuple[int, int], ...]
         if u == 0:
             runs = ()
@@ -857,18 +892,184 @@ def freeze(self) -> FrozenRow:
             runs = tuple(run_list)
 
         exts = tuple(sorted(self.ext.items())) if self.ext else ()
-        return FrozenRow(
+        fr = FrozenRow(
             text=text,
             cols=cols,
             runs=runs,
             exts=exts,
             cells=cells,
-            wrapped=self.wrapped,
+            wrapped=self._wrapped,
         )
+        self._frozen = fr
+        return fr
 
     def rstrip_text(self) -> str:
         """Return row text up to ``text_used`` written columns."""
         return "".join(self.chars[: self.text_used])
 
 
+@dataclass(frozen=True, slots=True)
+class _FrozenHistory(collections.abc.Sequence[FrozenRow]):
+    """Immutable 256-row copy-on-write block snapshot of sealed scrollback."""
+
+    blocks: tuple[tuple[FrozenRow, ...], ...] = ()
+    tail: tuple[FrozenRow, ...] = ()
+    head_offset: int = 0
+    length: int = 0
+
+    @classmethod
+    def from_sequence(
+        cls,
+        rows: collections.abc.Sequence[FrozenRow],
+    ) -> _FrozenHistory:
+        """Pack an arbitrary :class:`FrozenRow` sequence into 256-row blocks."""
+        if isinstance(rows, _FrozenHistory):
+            return rows
+        n = len(rows)
+        if n == 0:
+            return _EMPTY_FROZEN_HISTORY
+        full_blocks = n >> _HISTORY_BLOCK_SHIFT
+        blocks = tuple(
+            tuple(rows[i << _HISTORY_BLOCK_SHIFT : (i + 1) << _HISTORY_BLOCK_SHIFT])
+            for i in range(full_blocks)
+        )
+        tail = tuple(rows[full_blocks << _HISTORY_BLOCK_SHIFT :])
+        return cls(blocks=blocks, tail=tail, head_offset=0, length=n)
+
+    def __len__(self) -> int:
+        return self.length
+
+    def at(self, index: int) -> FrozenRow:
+        """Return :class:`FrozenRow` at normalized ``0 <= index < length``."""
+        raw = self.head_offset + index
+        b_idx = raw >> _HISTORY_BLOCK_SHIFT
+        off = raw & _HISTORY_BLOCK_MASK
+        if b_idx < len(self.blocks):
+            return self.blocks[b_idx][off]
+        return self.tail[off]
+
+    @t.overload
+    def __getitem__(self, index: int) -> FrozenRow: ...
+
+    @t.overload
+    def __getitem__(self, index: slice) -> tuple[FrozenRow, ...]: ...
+
+    def __getitem__(
+        self,
+        index: int | slice,
+    ) -> FrozenRow | tuple[FrozenRow, ...]:
+        if isinstance(index, slice):
+            start, stop, step = index.indices(self.length)
+            return tuple(self.at(i) for i in range(start, stop, step))
+        if isinstance(index, bool) or not isinstance(index, int):
+            msg = f"history indices must be int or slice, got {type(index).__name__}"
+            raise TypeError(msg)
+        norm = index + self.length if index < 0 else index
+        if norm < 0 or norm >= self.length:
+            msg = f"history index {index} out of range for size {self.length}"
+            raise IndexError(msg)
+        return self.at(norm)
+
+    def __iter__(self) -> collections.abc.Iterator[FrozenRow]:
+        if self.length == 0:
+            return
+        if not self.blocks:
+            yield from self.tail[self.head_offset : self.head_offset + self.length]
+            return
+        yield from self.blocks[0][self.head_offset :]
+        for blk in self.blocks[1:]:
+            yield from blk
+        yield from self.tail
+
+
+_EMPTY_FROZEN_HISTORY = _FrozenHistory()
+
+
+class _HistoryBuffer:
+    """Bounded 256-row block scrollback buffer with ``O(1)`` CoW snapshots."""
+
+    __slots__ = ("_blocks", "_head_offset", "_len", "_maxlen", "_snapshot", "_tail")
+
+    def __init__(self, *, maxlen: int) -> None:
+        self._maxlen: int = max(0, maxlen)
+        self._blocks: list[tuple[FrozenRow, ...]] = []
+        self._tail: list[FrozenRow] = []
+        self._head_offset: int = 0
+        self._len: int = 0
+        self._snapshot: _FrozenHistory | None = _EMPTY_FROZEN_HISTORY
+
+    @property
+    def maxlen(self) -> int:
+        """Return scrollback line capacity (``0`` when disabled)."""
+        return self._maxlen
+
+    def __len__(self) -> int:
+        return self._len
+
+    def __bool__(self) -> bool:
+        return self._len > 0
+
+    def __getitem__(self, index: int) -> FrozenRow:
+        if isinstance(index, bool) or not isinstance(index, int):
+            msg = f"history index must be int, got {type(index).__name__}"
+            raise TypeError(msg)
+        norm = index + self._len if index < 0 else index
+        if norm < 0 or norm >= self._len:
+            msg = f"history index {index} out of range for size {self._len}"
+            raise IndexError(msg)
+        raw = self._head_offset + norm
+        b_idx = raw >> _HISTORY_BLOCK_SHIFT
+        off = raw & _HISTORY_BLOCK_MASK
+        if b_idx < len(self._blocks):
+            return self._blocks[b_idx][off]
+        return self._tail[off]
+
+    def __iter__(self) -> collections.abc.Iterator[FrozenRow]:
+        return iter(self.freeze())
+
+    def clear(self) -> None:
+        """Discard all stored scrollback blocks."""
+        if self._len == 0:
+            return
+        self._blocks.clear()
+        self._tail = []
+        self._head_offset = 0
+        self._len = 0
+        self._snapshot = _EMPTY_FROZEN_HISTORY
+
+    def append(self, row: FrozenRow) -> bool:
+        """Append *row*, returning ``True`` when the oldest row was evicted."""
+        if self._maxlen <= 0:
+            return False
+        self._snapshot = None
+        self._tail.append(row)
+        if len(self._tail) == _HISTORY_BLOCK_SIZE:
+            self._blocks.append(tuple(self._tail))
+            self._tail = []
+        if self._len == self._maxlen:
+            self._head_offset += 1
+            if self._head_offset == _HISTORY_BLOCK_SIZE:
+                del self._blocks[0]
+                self._head_offset = 0
+            return True
+        self._len += 1
+        return False
+
+    def freeze(self) -> _FrozenHistory:
+        """Capture an ``O(1)`` CoW :class:`_FrozenHistory` snapshot."""
+        if self._snapshot is not None:
+            return self._snapshot
+        if self._len == 0:
+            self._snapshot = _EMPTY_FROZEN_HISTORY
+            return _EMPTY_FROZEN_HISTORY
+        snap = _FrozenHistory(
+            blocks=tuple(self._blocks),
+            tail=tuple(self._tail),
+            head_offset=self._head_offset,
+            length=self._len,
+        )
+        self._snapshot = snap
+        return snap
+
+
 type RowLike = _Row | FrozenRow
diff --git a/src/libvt/screen.py b/src/libvt/screen.py
index a5eecd9..2d2b579 100644
--- a/src/libvt/screen.py
+++ b/src/libvt/screen.py
@@ -2,17 +2,22 @@
 
 from __future__ import annotations
 
-import collections
+import bisect
 import collections.abc
 import enum
+import operator
+import sys
 import typing as t
 from dataclasses import dataclass
 
 from libvt._grid import (
+    _EMPTY_FROZEN_HISTORY,
     _WIDTH_CLEAR_MASK,
     FrozenRow,
     RowLike,
     _CellExt,
+    _FrozenHistory,
+    _HistoryBuffer,
     _Row,
     bump_row_gen,
     raw_width_bits,
@@ -24,6 +29,8 @@
 from libvt.input import KittyKeyboardStack
 from libvt.style import DEFAULT_STYLE, Hyperlink, Style
 
+_ITEM0 = operator.itemgetter(0)
+
 
 class CursorShape(enum.StrEnum):
     """Cursor glyph shape configured via ``DECSCUSR`` (``CSI Ps SP q``)."""
@@ -192,6 +199,146 @@ def _slice_indices(s: slice, length: int) -> range:
     return range(start, stop)
 
 
+def _frozen_row_runs(
+    row: FrozenRow,
+    start_c: int,
+    limit: int,
+) -> tuple[RowRun, ...]:
+    """Coalesce ``(style, hyperlink)`` spans on *row* in ``O(runs + exts)``."""
+    if not row.runs and not row.exts and row.cells is None:
+        t_len = len(row.text)
+        if limit <= t_len:
+            txt = row.text[start_c:limit]
+        elif start_c >= t_len:
+            txt = " " * (limit - start_c)
+        else:
+            txt = row.text[start_c:t_len] + (" " * (limit - t_len))
+        return (
+            RowRun(
+                start_col=start_c,
+                end_col=limit,
+                text=txt,
+                style=DEFAULT_STYLE,
+                hyperlink=None,
+            ),
+        )
+
+    out: list[RowRun] = []
+    runs = row.runs
+    exts = row.exts
+    r_len = len(runs)
+    e_len = len(exts)
+    r_idx = bisect.bisect_right(runs, start_c, key=_ITEM0) if r_len else 0
+    e_idx = bisect.bisect_left(exts, start_c, key=_ITEM0) if e_len else 0
+
+    has_cur = False
+    run_start = start_c
+    cur_style = DEFAULT_STYLE
+    cur_link: Hyperlink | None = None
+    buf: list[str] = []
+    pos = start_c
+
+    while pos < limit:
+        if r_idx < r_len:
+            raw_r_end, word = runs[r_idx]
+            r_end = min(limit, raw_r_end)
+        else:
+            raw_r_end = limit + 1
+            word = 0
+            r_end = limit
+
+        while e_idx < e_len and exts[e_idx][0] < pos:
+            e_idx += 1
+        if e_idx >= e_len:
+            ext: _CellExt | None = None
+            e_end = limit
+        elif exts[e_idx][0] > pos:
+            ext = None
+            e_end = min(limit, exts[e_idx][0])
+        else:
+            ext = exts[e_idx][1]
+            scan_c = pos + 1
+            scan_i = e_idx + 1
+            while (
+                scan_c < r_end
+                and scan_i < e_len
+                and exts[scan_i][0] == scan_c
+                and exts[scan_i][1] == ext
+            ):
+                scan_c += 1
+                scan_i += 1
+            e_end = scan_c
+            e_idx = scan_i
+
+        seg_end = min(r_end, e_end)
+        if seg_end == raw_r_end:
+            r_idx += 1
+
+        role_bits = raw_width_bits(word)
+        if role_bits in (int(WidthRole.SPACER_TAIL), int(WidthRole.SPACER_HEAD)):
+            if not has_cur:
+                cur_style = unpack_style(word, ext)
+                cur_link = ext.hyperlink if ext is not None else None
+                run_start = pos
+                has_cur = True
+            pos = seg_end
+            continue
+
+        if row.cells is not None:
+            c_len = len(row.cells)
+            if seg_end <= c_len:
+                seg_txt = "".join(row.cells[pos:seg_end])
+            elif pos >= c_len:
+                seg_txt = " " * (seg_end - pos)
+            else:
+                seg_txt = "".join(row.cells[pos:c_len]) + (" " * (seg_end - c_len))
+        else:
+            t_len = len(row.text)
+            if seg_end <= t_len:
+                seg_txt = row.text[pos:seg_end]
+            elif pos >= t_len:
+                seg_txt = " " * (seg_end - pos)
+            else:
+                seg_txt = row.text[pos:t_len] + (" " * (seg_end - t_len))
+
+        st = unpack_style(word, ext)
+        lnk = ext.hyperlink if ext is not None else None
+        if not has_cur:
+            run_start = pos
+            cur_style = st
+            cur_link = lnk
+            buf = [seg_txt]
+            has_cur = True
+        elif st != cur_style or lnk != cur_link:
+            out.append(
+                RowRun(
+                    start_col=run_start,
+                    end_col=pos,
+                    text="".join(buf),
+                    style=cur_style,
+                    hyperlink=cur_link,
+                ),
+            )
+            run_start = pos
+            cur_style = st
+            cur_link = lnk
+            buf = [seg_txt]
+        else:
+            buf.append(seg_txt)
+        pos = seg_end
+
+    out.append(
+        RowRun(
+            start_col=run_start,
+            end_col=limit,
+            text="".join(buf),
+            style=cur_style,
+            hyperlink=cur_link,
+        ),
+    )
+    return tuple(out)
+
+
 class RowView(collections.abc.Sequence[Cell]):
     """Read-only sequence view over one live viewport or scrollback row."""
 
@@ -232,7 +379,11 @@ def text(self) -> str:
         total_cols = len(row.chars) if isinstance(row, _Row) else row.cols
         if self._col_range.start == 0 and self._col_range.stop == total_cols:
             return row.rstrip_text()
-        row_t_used = row.text_used if isinstance(row, _Row) else row.used
+        row_t_used = (
+            row.text_used
+            if isinstance(row, _Row)
+            else (len(row.cells) if row.cells is not None else len(row.text))
+        )
         limit = min(self._col_range.stop, row_t_used)
         if limit <= self._col_range.start:
             return ""
@@ -250,6 +401,8 @@ def runs(self) -> tuple[RowRun, ...]:
         start_c = self._col_range.start
         if limit <= start_c:
             return ()
+        if isinstance(row, FrozenRow):
+            return _frozen_row_runs(row, start_c, limit)
         out: list[RowRun] = []
         run_start = start_c
         first_ext = row.ext_at(start_c)
@@ -319,6 +472,164 @@ def __getitem__(self, index: int | slice) -> Cell | RowView:
         norm = _normalize_index(index, len(self._col_range), axis="col")
         return _materialize_cell(row, self._col_range.start + norm)
 
+    def __eq__(self, other: object) -> bool:
+        """Compare two :class:`RowView` instances by wrapped state and cells."""
+        if self is other:
+            return True
+        if not isinstance(other, RowView):
+            return NotImplemented
+        if len(self._col_range) != len(other._col_range):
+            return False
+        r1 = self._current_row()
+        r2 = other._current_row()
+        if r1 is r2 and self._col_range == other._col_range:
+            return True
+        c1 = len(r1.chars) if isinstance(r1, _Row) else r1.cols
+        c2 = len(r2.chars) if isinstance(r2, _Row) else r2.cols
+        if (
+            self._col_range.start == 0
+            and self._col_range.stop == c1
+            and other._col_range.start == 0
+            and other._col_range.stop == c2
+        ):
+            f1 = r1.freeze() if isinstance(r1, _Row) else r1
+            f2 = r2.freeze() if isinstance(r2, _Row) else r2
+            return f1 == f2
+        if r1.wrapped != r2.wrapped:
+            return False
+        return all(a == b for a, b in zip(self, other, strict=True))
+
+
+def _row_view_to_full_frozen(value: object) -> FrozenRow | None:
+    if not isinstance(value, RowView):
+        return None
+    r = value._current_row()
+    cols = len(r.chars) if isinstance(r, _Row) else r.cols
+    if value._col_range.start == 0 and value._col_range.stop == cols:
+        return r.freeze() if isinstance(r, _Row) else r
+    return None
+
+
+class _HistoryView(collections.abc.Sequence[RowView]):
+    """Lazy ``O(1)`` immutable sequence view over scrollback :class:`RowView` lines."""
+
+    __slots__ = ("_data", "_range")
+
+    def __init__(
+        self,
+        data: _FrozenHistory | None = None,
+        index_range: range | None = None,
+    ) -> None:
+        eff = _EMPTY_FROZEN_HISTORY if data is None else data
+        self._data = eff
+        self._range = range(len(eff)) if index_range is None else index_range
+
+    def __len__(self) -> int:
+        """Return number of scrollback rows in this view."""
+        return len(self._range)
+
+    def __bool__(self) -> bool:
+        """Return ``True`` when at least one scrollback row is present."""
+        return bool(self._range)
+
+    @t.overload
+    def __getitem__(self, index: int) -> RowView: ...
+
+    @t.overload
+    def __getitem__(self, index: slice) -> _HistoryView: ...
+
+    def __getitem__(self, index: int | slice) -> RowView | _HistoryView:
+        """Index one :class:`RowView` in ``O(1)`` or slice a sub-view."""
+        if isinstance(index, slice):
+            return _HistoryView(self._data, self._range[index])
+        if isinstance(index, bool) or not isinstance(index, int):
+            msg = f"history indices must be int or slice, got {type(index).__name__}"
+            raise TypeError(msg)
+        return RowView(self._data.at(self._range[index]))
+
+    def __contains__(self, value: object) -> bool:
+        """Return ``True`` when *value* matches a scrollback :class:`RowView`."""
+        if not isinstance(value, RowView):
+            return False
+        target_fr = _row_view_to_full_frozen(value)
+        if target_fr is not None:
+            r = self._range
+            if r.start == 0 and r.stop == len(self._data) and r.step == 1:
+                return any(fr == target_fr for fr in self._data)
+            at = self._data.at
+            return any(at(idx) == target_fr for idx in r)
+        return any(item == value for item in self)
+
+    def count(self, value: object) -> int:
+        """Return count of scrollback rows equal to *value*."""
+        if not isinstance(value, RowView):
+            return 0
+        target_fr = _row_view_to_full_frozen(value)
+        if target_fr is not None:
+            at = self._data.at
+            return sum(1 for idx in self._range if at(idx) == target_fr)
+        return sum(1 for item in self if item == value)
+
+    def index(
+        self,
+        value: object,
+        start: int = 0,
+        stop: int = sys.maxsize,
+    ) -> int:
+        """Return first zero-based index of *value* in ``[start, stop)``."""
+        if isinstance(value, RowView):
+            sub_indices = range(len(self._range))[start:stop]
+            target_fr = _row_view_to_full_frozen(value)
+            at = self._data.at
+            if target_fr is not None:
+                for pos in sub_indices:
+                    if at(self._range[pos]) == target_fr:
+                        return pos
+            else:
+                for pos in sub_indices:
+                    if RowView(at(self._range[pos])) == value:
+                        return pos
+        msg = "RowView is not in history"
+        raise ValueError(msg)
+
+    def __iter__(self) -> collections.abc.Iterator[RowView]:
+        """Yield :class:`RowView` items across this view."""
+        r = self._range
+        if not r:
+            return
+        if r.start == 0 and r.stop == len(self._data) and r.step == 1:
+            for fr in self._data:
+                yield RowView(fr)
+            return
+        at = self._data.at
+        for idx in r:
+            yield RowView(at(idx))
+
+    def __reversed__(self) -> collections.abc.Iterator[RowView]:
+        """Yield :class:`RowView` items in reverse order."""
+        at = self._data.at
+        for idx in reversed(self._range):
+            yield RowView(at(idx))
+
+    def __eq__(self, other: object) -> bool:
+        """Compare two :class:`_HistoryView` instances by underlying frozen rows."""
+        if self is other:
+            return True
+        if not isinstance(other, _HistoryView):
+            return NotImplemented
+        if len(self._range) != len(other._range):
+            return False
+        if self._data is other._data and self._range == other._range:
+            return True
+        return all(
+            self._data.at(i) == other._data.at(j)
+            for i, j in zip(self._range, other._range, strict=True)
+        )
+
+    def __repr__(self) -> str:
+        """Return concise summary representation."""
+        return f"HistoryView(len={len(self._range)})"
+
 
 class RegionView(collections.abc.Sequence[RowView]):
     """Read-only 2D rectangular slice view over ``(rows, cols)``."""
@@ -476,9 +787,7 @@ def __init__(
             raise ValueError(msg)
         self._cols = cols
         self._rows: list[_Row] = [_Row(cols) for _ in range(rows)]
-        self._history: collections.deque[FrozenRow] = collections.deque(
-            maxlen=max(0, scrollback),
-        )
+        self._history: _HistoryBuffer = _HistoryBuffer(maxlen=max(0, scrollback))
         self._scrolled_total: int = 0
         self._evicted_total: int = 0
         self._history_clear_at: int = 0
@@ -542,9 +851,9 @@ def cursor(self, value: Cursor) -> None:
         self._pending_wrap = value.pending_wrap
 
     @property
-    def history(self) -> tuple[RowView, ...]:
-        """Return immutable :class:`RowView` sequence over sealed scrollback rows."""
-        return tuple(RowView(fr) for fr in self._history)
+    def history(self) -> collections.abc.Sequence[RowView]:
+        """Return ``O(1)`` immutable :class:`RowView` sequence over scrollback."""
+        return _HistoryView(self._history.freeze())
 
     @property
     def tabstops(self) -> tuple[int, ...]:
@@ -600,11 +909,8 @@ def placements(self) -> tuple[ImagePlacement, ...]:
         return self._gfx.snapshot_placements()
 
     def _append_history(self, frozen: FrozenRow) -> None:
-        maxlen = self._history.maxlen
-        if maxlen is not None and maxlen > 0:
-            if len(self._history) == maxlen:
-                self._evicted_total += 1
-            self._history.append(frozen)
+        if self._history.append(frozen):
+            self._evicted_total += 1
 
     def _clear_row_spacer_head(self, row_obj: _Row) -> bool:
         if not row_obj.has_wide or row_obj.attrs is None:
@@ -1209,19 +1515,6 @@ def _sync_partial_scroll_bounds(
     r_col: int,
 ) -> None:
     limit = r_col + 1
-    if dst_row.used <= limit:
-        cand_u = (
-            min(src_row.used, limit) if src_row.used > left else min(dst_row.used, left)
-        )
-        floor_u = min(dst_row.used, left)
-        while (
-            cand_u > floor_u
-            and dst_row.chars[cand_u - 1] == " "
-            and dst_row.attr_at(cand_u - 1) == 0
-            and dst_row.ext_at(cand_u - 1) is None
-        ):
-            cand_u -= 1
-        dst_row.used = cand_u
     if dst_row.text_used <= limit:
         cand_t = (
             min(src_row.text_used, limit)
@@ -1233,6 +1526,20 @@ def _sync_partial_scroll_bounds(
             while cand_t > floor_t and dst_row.chars[cand_t - 1] == " ":
                 cand_t -= 1
         dst_row.text_used = cand_t
+    if dst_row.used <= limit:
+        cand_u = (
+            min(src_row.used, limit) if src_row.used > left else min(dst_row.used, left)
+        )
+        floor_u = max(min(dst_row.used, left), dst_row.text_used)
+        if src_row.used > limit:
+            while (
+                cand_u > floor_u
+                and dst_row.chars[cand_u - 1] == " "
+                and dst_row.attr_at(cand_u - 1) == 0
+                and dst_row.ext_at(cand_u - 1) is None
+            ):
+                cand_u -= 1
+        dst_row.used = max(cand_u, dst_row.text_used)
 
 
 class ScreenSet:
diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py
index e4817b1..ab3bbe2 100644
--- a/src/libvt/terminal.py
+++ b/src/libvt/terminal.py
@@ -16,10 +16,12 @@
 from dataclasses import dataclass
 
 from libvt._grid import (
+    _EMPTY_FROZEN_HISTORY,
     _PEN_BASE_MASK,
     _PEN_BG_MASK,
     FrozenRow,
     _CellExt,
+    _FrozenHistory,
     _Row,
     bump_row_gen,
     current_row_gen,
@@ -95,6 +97,7 @@
     Screen,
     ScreenSet,
     ScrollRegion,
+    _HistoryView,
     format_rows_text,
     slice_grid,
 )
@@ -256,7 +259,7 @@ class ScreenDelta:
     dirty_rows : tuple[int, ...]
         Sorted zero-based viewport row indices modified after shifting the
         previous viewport upward by :attr:`viewport_scroll_up`.
-    new_history : tuple[RowView, ...]
+    new_history : collections.abc.Sequence[RowView]
         Newly sealed scrollback rows appended since *from_token*, ordered
         oldest to newest.
     history_evicted : int
@@ -282,7 +285,7 @@ class ScreenDelta:
     resync_reason: ResyncReason
     viewport_scroll_up: int
     dirty_rows: tuple[int, ...]
-    new_history: tuple[RowView, ...]
+    new_history: collections.abc.Sequence[RowView]
     history_evicted: int
     history_cleared: bool
     cursor_changed: bool
@@ -536,7 +539,9 @@ def __init__(
         self,
         *,
         rows: tuple[_Row, ...],
-        history: tuple[FrozenRow, ...],
+        history: _FrozenHistory | collections.abc.Sequence[FrozenRow] = (
+            _EMPTY_FROZEN_HISTORY
+        ),
         cols: int,
         cursor: Cursor,
         title: str,
@@ -555,16 +560,17 @@ def __init__(
     ) -> None:
         object.__setattr__(self, "_frozen", False)
         self._rows = rows
-        self._history = history
+        hist_obj = _FrozenHistory.from_sequence(history)
+        self._history: _FrozenHistory = hist_obj
         self._cols = cols
         eff_scrolled = (
-            (0 if active_is_alt else len(history))
+            (0 if active_is_alt else len(hist_obj))
             if scrolled_total is None
             else scrolled_total
         )
         self._scrolled_total = eff_scrolled
         self._evicted_total = (
-            (0 if active_is_alt else max(0, eff_scrolled - len(history)))
+            (0 if active_is_alt else max(0, eff_scrolled - len(hist_obj)))
             if evicted_total is None
             else evicted_total
         )
@@ -703,7 +709,7 @@ def at_abs(self, abs_row: int) -> RowView:
             msg = f"abs_row {abs_row} was evicted (earliest retained is {first_abs})"
             raise IndexError(msg)
         if abs_row < self._scrolled_total:
-            return RowView(self._history[abs_row - first_abs])
+            return RowView(self._history.at(abs_row - first_abs))
         rel = abs_row - self._scrolled_total
         if rel < len(self._rows):
             return RowView(self._rows[rel])
@@ -711,9 +717,9 @@ def at_abs(self, abs_row: int) -> RowView:
         raise IndexError(msg)
 
     @property
-    def history(self) -> tuple[RowView, ...]:
-        """Return immutable :class:`RowView` sequence over scrollback rows."""
-        return tuple(RowView(fr) for fr in self._history)
+    def history(self) -> collections.abc.Sequence[RowView]:
+        """Return ``O(1)`` immutable :class:`RowView` sequence over scrollback rows."""
+        return _HistoryView(self._history)
 
     @property
     def lines(self) -> tuple[str, ...]:
@@ -1364,7 +1370,7 @@ def screens(self) -> ScreenSet:
         return self._screens
 
     @property
-    def history(self) -> tuple[RowView, ...]:
+    def history(self) -> collections.abc.Sequence[RowView]:
         """Return sealed scrollback :class:`~libvt.screen.RowView` lines."""
         return self._screens.primary.history
 
@@ -1478,7 +1484,7 @@ def _build_snapshot(
         active_alt = self._screens.active_is_alt
         return Snapshot(
             rows=tuple(r.clone() for r in scr._rows),
-            history=tuple(self._screens.primary._history),
+            history=self._screens.primary._history.freeze(),
             cols=scr.cols,
             cursor=scr.cursor,
             title=self._title,
@@ -1627,6 +1633,7 @@ def _full(reason: ResyncReason) -> ScreenDelta:
         hist_cleared = cur_tok.history_clear_seq != token.history_clear_seq
         hist_len = len(cur_snap._history)
         zero_hist_cap = self._screens.primary._history.maxlen == 0 and hist_len == 0
+        new_hist: collections.abc.Sequence[RowView]
         if hist_cleared:
             if zero_hist_cap:
                 new_hist = ()
@@ -1636,11 +1643,7 @@ def _full(reason: ResyncReason) -> ScreenDelta:
                 if post_clear > hist_len:
                     return _full(ResyncReason.HISTORY_EVICTED)
                 new_hist = (
-                    tuple(
-                        RowView(fr) for fr in cur_snap._history[hist_len - post_clear :]
-                    )
-                    if post_clear > 0
-                    else ()
+                    cur_snap.history[hist_len - post_clear :] if post_clear > 0 else ()
                 )
                 evicted_cnt = 0
         else:
@@ -1651,11 +1654,7 @@ def _full(reason: ResyncReason) -> ScreenDelta:
             else:
                 if added > hist_len:
                     return _full(ResyncReason.HISTORY_EVICTED)
-                new_hist = (
-                    tuple(RowView(fr) for fr in cur_snap._history[hist_len - added :])
-                    if added > 0
-                    else ()
-                )
+                new_hist = cur_snap.history[hist_len - added :] if added > 0 else ()
                 evicted_cnt = max(0, cur_tok.evicted_total - token.evicted_total)
 
         v_scroll = (
diff --git a/src/libvt/tmux.py b/src/libvt/tmux.py
index 9c6b270..4caea3d 100644
--- a/src/libvt/tmux.py
+++ b/src/libvt/tmux.py
@@ -576,6 +576,7 @@ def _trim_unwrapped_row(row: _Row) -> None:
         and row.ext_at(row.used - 1) is None
     ):
         row.used -= 1
+    row._frozen = None
 
 
 def _populate_screen_from_lines(
diff --git a/tests/test_screen.py b/tests/test_screen.py
index efd0c76..c63d90a 100644
--- a/tests/test_screen.py
+++ b/tests/test_screen.py
@@ -2,7 +2,9 @@
 
 from __future__ import annotations
 
+import collections.abc
 import random
+import time
 import typing as t
 
 import pytest
@@ -12,6 +14,7 @@
 from libvt.config import DEFAULT_PROFILE, XTERM_PROFILE, Profile
 from libvt.events import InBandResize
 from libvt.modes import Mode
+from libvt.style import AnsiColor
 
 
 def _assert_grid_invariants(term: libvt.Terminal) -> None:
@@ -242,6 +245,99 @@ def test_row_wide_healing_decslrm_scroll_and_rle_history() -> None:
     assert len(fr_t.history[0].runs) >= 1
 
 
+def test_frozen_row_combining_wide_bce_and_256_block_cow_history() -> None:
+    """``_Row.freeze()`` retains wide+combining+BCE cells and ``O(1)`` CoW history."""
+    term = libvt.Terminal(rows=2, cols=8, scrollback=10)
+    term.feed("e\u0301中\x1b[44m\x1b[K\r\n❤\ufe0f🇯🇵👋🏻Z\r\nv0\r\nv1".encode())
+    snap = term.snapshot()
+    assert isinstance(snap.history, collections.abc.Sequence)
+    assert isinstance(term.history, collections.abc.Sequence)
+    assert not isinstance(snap.history, tuple)
+
+    h0 = snap.history[0]
+    assert h0.text == "e\u0301中"
+    assert (h0[0].text, h0[1].text, h0[1].width_role, h0[2].width_role) == (
+        "e\u0301",
+        "中",
+        WidthRole.WIDE,
+        WidthRole.SPACER_TAIL,
+    )
+    assert [r.text for r in h0.runs] == ["e\u0301中", "     "]
+    assert h0.runs[1].style.bg == AnsiColor.BLUE
+    assert (h0.runs[1].start_col, h0.runs[1].end_col) == (3, 8)
+
+    h1 = snap.history[1]
+    assert (h1[0].text, h1[2].text, h1[4].text, h1[6].text) == (
+        "❤\ufe0f",
+        "🇯🇵",
+        "👋🏻",
+        "Z",
+    )
+
+    bce_term = libvt.Terminal(rows=2, cols=8, scrollback=10)
+    bce_term.feed("中\x1b[44m\x1b[K\r\n\n\n".encode())
+    bce_runs = bce_term.snapshot().history[0].runs
+    assert [(r.start_col, r.end_col, r.text, r.style.bg) for r in bce_runs] == [
+        (0, 2, "中", None),
+        (2, 8, "      ", AnsiColor.BLUE),
+    ]
+
+    ech_el = libvt.Terminal(rows=2, cols=10, scrollback=4)
+    ech_el.feed(b"\x1b[41mAB\x1b[K\x1b[0m\x1b[3G\x1b[5X\x1b[8G\x1b[K\r\n\n\n")
+    assert ech_el.snapshot().history[0]._row.used == 2
+    assert [r.text for r in ech_el.snapshot().history[0].runs] == ["AB"]
+
+    declrmm_sp = libvt.Terminal(rows=3, cols=6, scrollback=10)
+    declrmm_sp.feed(
+        b"\r\nA  \x1b[?69h\x1b[1;4s\x1b[1;1H\x1b[S\x1b[?69l\x1b[3;1H\r\n\r\n\r\n"
+    )
+    assert declrmm_sp.history[0].text == "A  "
+    assert [r.text for r in declrmm_sp.history[0].runs] == ["A  "]
+    declrmm_sp.resize(rows=3, cols=8)
+    assert declrmm_sp.history[0].text == "A  "
+
+    deep = libvt.Terminal(rows=2, cols=16, scrollback=50_000)
+    deep.feed(b"".join(f"line-{i:05d}\r\n".encode() for i in range(50_002)))
+    assert len(deep.history) == 50_000
+    assert (deep.history[0].text, deep.history[-1].text) == (
+        "line-00001",
+        "line-50000",
+    )
+    assert deep.history[0] == deep.history[0]
+    assert deep.history[255] in deep.history
+    assert deep.history.index(deep.history[257]) == 257
+    assert deep.history.count(deep.history[257]) == 1
+    assert [r.text for r in deep.history[254:258]] == [
+        "line-00255",
+        "line-00256",
+        "line-00257",
+        "line-00258",
+    ]
+    assert [r.text for r in deep.history[-3:][::-1]] == [
+        "line-50000",
+        "line-49999",
+        "line-49998",
+    ]
+    assert next(reversed(deep.history)).text == "line-50000"
+
+    snap_a = deep.snapshot()
+    tok = deep.sync_token()
+    t0 = time.perf_counter()
+    for step in range(50):
+        deep.feed(f"tail-{step:02d}\r\n".encode())
+        s_deep = deep.snapshot()
+        delta = deep.changes_since(tok)
+        tok = delta.token
+        assert delta.full_resync is False
+        assert len(delta.new_history) == 1
+        assert s_deep.history[-1].text == (
+            "line-50001" if step == 0 else f"tail-{step - 1:02d}"
+        )
+    assert time.perf_counter() - t0 < 0.05
+    snap_b = deep.snapshot()
+    assert snap_a._history.blocks[1] is snap_b._history.blocks[1]
+
+
 def test_seeded_grid_and_reflow_invariants() -> None:
     """Seeded property fuzzing preserves wide-spacer and cursor bounds."""
     rng = random.Random(20261121)
diff --git a/tests/test_terminal.py b/tests/test_terminal.py
index dabab74..9154c25 100644
--- a/tests/test_terminal.py
+++ b/tests/test_terminal.py
@@ -115,7 +115,7 @@ def test_csi_motions_selective_erase_ed3_ed2_and_decstr() -> None:
     ed3_t.feed(b"old\r\nnew\r\nABCD")
     ed3_t.drain_events()
     ed3_t.feed(b"\x1b[3J\x1b[?3J\x1b[99J")
-    assert (ed3_t.history, ed3_t.lines, ed3_t.cursor.pending_wrap) == (
+    assert (tuple(ed3_t.history), ed3_t.lines, ed3_t.cursor.pending_wrap) == (
         (),
         ("new", "ABCD"),
         True,