diff --git a/AGENTS.md b/AGENTS.md index 01785e5..d006f94 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,15 @@ 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/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/` | 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 | | `CHANGES` | The changelog, rendered as a docs page | | `MIGRATION` | Deprecation and migration notes | @@ -51,14 +55,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..9a63634 100644 --- a/CHANGES +++ b/CHANGES @@ -5,3 +5,110 @@ _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`), `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) + +{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, 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` +(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. + +#### 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 +52,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_box +>>> t = libvt.Terminal(rows=2, cols=8) +>>> t.feed("日本ok\r\ndone".encode()) +>>> assert_screen_box( +... t, +... """ +... ┌────────┐ +... │日本ok │ +... │done │ +... └────────┘ +... """, +... cursor=(1, 4), +... ) ``` ## License diff --git a/conftest.py b/conftest.py index 4f91501..dd0026d 100644 --- a/conftest.py +++ b/conftest.py @@ -7,9 +7,14 @@ import pytest import libvt +from libvt.testing import assert_screen, assert_screen_box @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 + doctest_namespace["assert_screen_box"] = assert_screen_box 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/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/docs/api/index.md b/docs/api/index.md index 1de76f2..7bc9310 100644 --- a/docs/api/index.md +++ b/docs/api/index.md @@ -12,13 +12,61 @@ 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. +::: + +:::{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. ::: :::: @@ -53,5 +101,20 @@ Active deprecations and migration guidance. :maxdepth: 1 libvt +terminal +screen +parser +style +modes +config +events +status +input +codec +graphics +tmux +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/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/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/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..33eab7b --- /dev/null +++ b/docs/project/adr/0002-sans-io-layers-profiles-and-closed-events.md @@ -0,0 +1,125 @@ +(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`, + `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=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=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=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 + `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 | 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 + 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..b19f55f --- /dev/null +++ b/docs/project/adr/0003-two-tier-packed-viewport-and-rle-scrollback.md @@ -0,0 +1,124 @@ +(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. + - 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 + +| 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..8bc6745 --- /dev/null +++ b/docs/project/adr/0005-utf8-c1-isolation-and-unicode-17-grapheme-width.md @@ -0,0 +1,108 @@ +(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. **`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`). +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. **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 + 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..63abe45 --- /dev/null +++ b/docs/project/adr/0007-rex-osc-7501-program-status-and-semantic-prompts.md @@ -0,0 +1,115 @@ +(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` (`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]`. + - **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`, 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 + 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, abs_row: int, col: int, + exit_code: int | None)` in a `collections.deque` bounded by + `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 + `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 envelopes (emitting `Passthrough` and re-feeding inner + bytes only when `Policy.allow_passthrough=True`). + +## Alternatives considered + +- **Simplified `OSC 7501;value;progress` string split**: Rejected because it is + wire-incompatible with `tmux`, `Ghostty`, and Rex CLI emitters. +- **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 + +### 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 = 256`. 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..abe5f95 --- /dev/null +++ b/docs/project/adr/0010-transport-only-asyncio-and-diagnostic-pytest-plugin.md @@ -0,0 +1,107 @@ +(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, 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`, + 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` + `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. **Literal `assert_screen`, column-exact `assert_screen_box`, and `FlightRecorder` + (`libvt.testing`)**: + - `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`). + +## 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 +``` diff --git a/docs/quickstart.md b/docs/quickstart.md index 3ed1f7d..da82826 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -17,15 +17,70 @@ $ 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 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, 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/docs/topics/architecture.md b/docs/topics/architecture.md new file mode 100644 index 0000000..9ffc258 --- /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`): 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 + 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..948d1f7 --- /dev/null +++ b/docs/topics/protocols-and-input.md @@ -0,0 +1,59 @@ +(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 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 + +`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..5454653 --- /dev/null +++ b/docs/topics/sync-and-asyncio.md @@ -0,0 +1,59 @@ +(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 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. 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 new file mode 100644 index 0000000..c62fcc0 --- /dev/null +++ b/scripts/generate_ucd.py @@ -0,0 +1,710 @@ +"""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 urllib.request +import zlib + +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( + { + 0x061C, + *range(0x202A, 0x202F), + *range(0x2066, 0x206A), + }, +) + + +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 _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 + 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 + 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 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) + 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 _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.""" + 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)] + 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. + +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 + +import array +import base64 +import enum +import re +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.""" + + NARROW = 0 + WIDE = 1 + SPACER_TAIL = 2 + SPACER_HEAD = 3 + + +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}" +EXPANDED_UCD_SHA256 = "{expanded_sha256}" + +SAFE_NARROW_BMP_RE: t.Final[re.Pattern[str]] = re.compile( +{bmp_pat_literal} +) + +_PACKED_B85 = ( +{b85_literal} +) + + +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() + s2.byteswap() + return s1, s2 + + +_STAGE1, _STAGE2 = _unpack_tables() + + +def ucd_lookup(cp: int) -> int: + """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 GCB_CONTROL << 2 + + +def _pack_state( + gcb: int, + ri_odd: int, + ep_state: int, + incb_state: int, + vs_base: int, + has_spacing: int, + multi_scalar: int, +) -> int: + return ( + _ACTIVE_BIT + | (gcb << 1) + | (ri_odd << 5) + | (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 + 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: + """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: int, + 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*. + + Returns + ------- + 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 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 + 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 + 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, has_spacing, 1), + -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 or (vs16_always_wide and has_spacing)): + w_override = 2 + elif cp == 0xFE0E and vs_base and vs15_narrows and not multi_scalar: + w_override = 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) + ): + 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 (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, + next_sp, + next_multi, + ), + w_override, + ) + + 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 + + +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, + 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 + for ch in text: + cp = ord(ch) + if 0x20 <= cp <= 0x7E and state == CLUSTER_NONE: + 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, + vs15_narrows=vs15_narrows, + vs16_always_wide=vs16_wide, + ) + 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", + "CLUSTER_NONE", + "EXPANDED_UCD_SHA256", + "SAFE_NARROW_BMP_RE", + "UNICODE_VERSION", + "WidthRole", + "char_width", + "display_width", + "init_cluster_state", + "sanitize_terminal_text", + "segment_graphemes", + "step_cluster", + "ucd_lookup", +] +''' + + +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 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/libvt/__init__.py b/src/libvt/__init__.py index 63cbae6..c4e28e2 100644 --- a/src/libvt/__init__.py +++ b/src/libvt/__init__.py @@ -18,10 +18,239 @@ __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_OSC7_HOSTS, + DEFAULT_POLICY, + DEFAULT_PROFILE, + LINUX_CONSOLE_PROFILE, + TMUX_CAPTURE_POLICY, + TMUX_PROFILE, + XTERM_PROFILE, + Charset, + ColorScheme, + Limits, + Policy, + Profile, + SixelErasePolicy, +) +from libvt.events import ( + Bell, + ClipboardWrite, + ColorSchemeQueried, + EraseCause, + Event, + InBandResize, + KittyCommand, + KittyGraphic, + Passthrough, + ProgramStatusChanged, + PromptKind, + PromptMark, + PromptZone, + Rect, + RenderHoldChanged, + ScreenErased, + SixelData, + SixelGraphic, + TitleChanged, + UnhandledSequence, + WindowRenamed, + WorkingDirectoryChanged, +) +from libvt.exc import ( + LibVtError, + ProtocolError, + ScreenAssertionError, + TerminalTimeoutError, + UnsafePasteError, +) +from libvt.graphics import ( + GraphicsProtocol, + ImageMeta, + ImagePlacement, + ZLayer, +) +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, + 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()) __all__ = [ + "BLANK_CELL", + "DEFAULT_LIMITS", + "DEFAULT_OSC7_HOSTS", + "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", + "Color", + "ColorScheme", + "ColorSchemeQueried", + "CsiParams", + "Cursor", + "CursorShape", + "DecrpmValue", + "EraseCause", + "Event", + "ExplainedSpan", + "FlightRecorder", + "FocusEvent", + "Formatter", + "GraphicsProtocol", + "Hyperlink", + "ImageMeta", + "ImagePlacement", + "InBandResize", + "IndexedColor", + "InputEvent", + "KeyAction", + "KeyEvent", + "KeyMod", + "KittyCommand", + "KittyGraphic", + "KittyKeyboardFlags", + "LibVtError", + "Limits", + "Mode", + "ModeState", + "MouseAction", + "MouseButton", + "MouseEvent", + "OutputFormat", + "Parser", + "ParserState", + "Passthrough", + "PasteEvent", + "Policy", + "Profile", + "ProgramStatus", + "ProgramStatusChanged", + "ProgramStatusStore", + "PromptKind", + "PromptMark", + "PromptZone", + "ProtocolError", + "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__", @@ -34,4 +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/__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..263f546 --- /dev/null +++ b/src/libvt/_grid.py @@ -0,0 +1,1075 @@ +"""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 +import bisect +import collections.abc +import operator +import typing as t +from dataclasses import dataclass + +from libvt._ucd import WidthRole +from libvt.style import ( + DEFAULT_STYLE, + AnsiColor, + Color, + Hyperlink, + IndexedColor, + RgbColor, + Style, + 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 + + +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 + row._frozen = None + 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 + +_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 +_PEN_BASE_MASK = _WIDTH_CLEAR_MASK & ~_HAS_EXT_BIT +_PEN_BG_MASK = _COLOR_MASK << _BG_SHIFT + + +@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.""" + 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(text_cols, run_end, ext_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 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*.""" + 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.""" + 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: + """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 + row.text_used = min( + len(self.cells) if self.cells is not None else len(self.text), width + ) + return row + + +class _Row: + """Mutable viewport row with lazy 64-bit ``array('Q')`` promotion.""" + + __slots__ = ( + "_frozen", + "_wrapped", + "attrs", + "chars", + "content_gen", + "ext", + "has_wide", + "text_used", + "uniform_attr", + "used", + ) + + 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.text_used: int = 0 + 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: + 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.text_used = 0 + self._wrapped = False + bump_row_gen(self) + + 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]) + 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: + 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, + 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) + self.text_used = max(self.text_used, col + 1) + bump_row_gen(self) + + 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) + self.text_used = max(self.text_used, col + 1) + bump_row_gen(self) + + 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) + self.text_used = max(self.text_used, end) + bump_row_gen(self) + + 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) + self.text_used = max(self.text_used, col + 2) + bump_row_gen(self) + + def append_grapheme( + self, + col: int, + ch: str, + *, + width_override: int, + bce_word: int = 0, + ) -> 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 + ): + base_pen = self.attr_at(target) & _PEN_BASE_MASK + base_ext = self.ext_at(target) + self._heal_wide_boundary(target + 1) + self._set_raw( + target, self.chars[target], base_pen, WidthRole.WIDE, base_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 ( + 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, " ", bce_word, WidthRole.NARROW, None) + if self.text_used == target + 2: + self.text_used = target + 1 + if self.used == target + 2 and bce_word == 0: + self.used = target + 1 + bump_row_gen(self) + + 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 >= self.used: + 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 + 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: + 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 >= self.used: + # 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, + 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) + + # Clear right when shifting pushes a WIDE head onto right without its tail. + 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 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 <= 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, + 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 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) + bump_row_gen(self) + + 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) + 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] + 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 + bump_row_gen(self) + + 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.text_used = self.text_used + 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 or "" in self.chars[:t_used]: + cells = tuple(self.chars[:t_used]) + + u = min(cols, max(self.used, t_used)) + runs: tuple[tuple[int, int], ...] + 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] + for c in range(1, u): + w = self.attrs[c] + if w != cur_word: + run_list.append((c, cur_word)) + cur_word = w + if cur_word != 0: + run_list.append((u, cur_word)) + runs = tuple(run_list) + + exts = tuple(sorted(self.ext.items())) if self.ext else () + fr = FrozenRow( + text=text, + cols=cols, + runs=runs, + exts=exts, + cells=cells, + 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/_ucd.py b/src/libvt/_ucd.py new file mode 100644 index 0000000..75b8618 --- /dev/null +++ b/src/libvt/_ucd.py @@ -0,0 +1,460 @@ +"""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 + +import array +import base64 +import enum +import re +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.""" + + NARROW = 0 + WIDE = 1 + SPACER_TAIL = 2 + SPACER_HEAD = 3 + + +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" +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" + 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" + "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(" +) + + +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() + s2.byteswap() + return s1, s2 + + +_STAGE1, _STAGE2 = _unpack_tables() + + +def ucd_lookup(cp: int) -> int: + """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 GCB_CONTROL << 2 + + +def _pack_state( + gcb: int, + ri_odd: int, + ep_state: int, + incb_state: int, + vs_base: int, + has_spacing: int, + multi_scalar: int, +) -> int: + return ( + _ACTIVE_BIT + | (gcb << 1) + | (ri_odd << 5) + | (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 + 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: + """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: int, + 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*. + + Returns + ------- + 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 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 + 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 + 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, has_spacing, 1), + -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 or (vs16_always_wide and has_spacing)): + w_override = 2 + elif cp == 0xFE0E and vs_base and vs15_narrows and not multi_scalar: + w_override = 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) + ): + 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 (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, + next_sp, + next_multi, + ), + w_override, + ) + + 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 + + +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, + 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 + for ch in text: + cp = ord(ch) + if 0x20 <= cp <= 0x7E and state == CLUSTER_NONE: + 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, + vs15_narrows=vs15_narrows, + vs16_always_wide=vs16_wide, + ) + 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", + "CLUSTER_NONE", + "EXPANDED_UCD_SHA256", + "SAFE_NARROW_BMP_RE", + "UNICODE_VERSION", + "WidthRole", + "char_width", + "display_width", + "init_cluster_state", + "sanitize_terminal_text", + "segment_graphemes", + "step_cluster", + "ucd_lookup", +] diff --git a/src/libvt/aio.py b/src/libvt/aio.py new file mode 100644 index 0000000..997a2f7 --- /dev/null +++ b/src/libvt/aio.py @@ -0,0 +1,787 @@ +"""Transport-only ``asyncio`` stream and POSIX PTY adapters over :class:`Terminal`.""" + +from __future__ import annotations + +import asyncio +import collections.abc +import contextlib +import dataclasses +import errno +import os +import signal +import socket +import struct +import sys +import time +import typing as t + +from libvt.config import ( + DEFAULT_LIMITS, + DEFAULT_OSC7_HOSTS, + 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 + +type TtyMode = t.Literal["cooked", "cbreak", "raw"] + +_PTY_TRAMPOLINE = ( + "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" + " 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" + " 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: + 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 + 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: + """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, InterruptedError): + 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) + + +def _make_timeout_error( + terminal: Terminal, + snap: Snapshot, + header: str, + *, + eof: bool, + attach_note: bool = True, +) -> 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) + return TerminalTimeoutError( + header, + parser_state=terminal.parser_state, + screen_text=snap.text, + recent_bytes=recent, + eof=eof, + diagnostics=f"{box}\n{diag}", + attach_note=attach_note, + ) + + +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, recorder=FlightRecorder()) + ) + 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: + 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.""" + 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, + attach_note: bool = True, + ) -> 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) + else predicate + ) + deadline = time.monotonic() + timeout + while True: + 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) + snap = self.terminal.snapshot() if self._eof else self.terminal.committed + if check(snap): + return snap + if self._eof: + raise _make_timeout_error( + self.terminal, + snap, + "stream reached EOF before predicate matched", + eof=True, + attach_note=attach_note, + ) + remaining = deadline - now + if remaining <= 0: + live = self.terminal.snapshot() + if check(live): + return live + raise _make_timeout_error( + self.terminal, + live, + f"timed out after {timeout:.2f}s waiting for terminal state", + eof=False, + attach_note=attach_note, + ) + self._frame_event.clear() + 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) + if self.terminal.synchronized: + self._update_sync_timer(time.monotonic()) + 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 _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 (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: + 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 | None = None, + ) -> 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, + attach_note: bool = True, + ) -> 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) + 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: + raise _make_timeout_error( + self.terminal, + snap, + "PTY reached EOF before predicate matched", + eof=True, + attach_note=attach_note, + ) + remaining = deadline - now + if remaining <= 0: + live = self.terminal.snapshot() + if check(live): + return live + raise _make_timeout_error( + self.terminal, + live, + f"timed out after {timeout:.2f}s waiting for PTY state", + eof=False, + attach_note=attach_note, + ) + self._frame_event.clear() + 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) + + async def aclose(self) -> int: + """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) + + 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, + 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, +) -> collections.abc.AsyncGenerator[PtySession]: + """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) + 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) + + 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 + 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( + py_bin, + "-I", + "-S", + "-c", + _PTY_TRAMPOLINE, + str(err_w), + *argv, + stdin=slave_fd, + stdout=slave_fd, + stderr=slave_fd, + 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 != 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() + with contextlib.suppress(OSError): + os.close(master_fd) + raise + finally: + 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.osc7_hosts is None: + fqdn = socket.gethostname().lower() + short = fqdn.partition(".")[0] + eff_policy = dataclasses.replace( + policy, + osc7_hosts=DEFAULT_OSC7_HOSTS | frozenset({fqdn, short}), + ) + + recorder = FlightRecorder(max_bytes=limits.max_recorder_bytes) + terminal = Terminal( + rows=rows, + cols=cols, + scrollback=scrollback, + profile=profile, + policy=eff_policy, + limits=limits, + recorder=recorder, + ) + session = PtySession( + master_fd=master_fd, + process=proc, + terminal=terminal, + sync_timeout=sync_timeout, + ) + session._loop = loop + loop.add_reader(master_fd, session._on_readable) + try: + yield session + finally: + await session.aclose() + + +__all__ = [ + "AsyncTerminalStream", + "PtySession", + "ReplyWriter", + "TtyMode", + "open_pty", +] diff --git a/src/libvt/codec.py b/src/libvt/codec.py new file mode 100644 index 0000000..237abf3 --- /dev/null +++ b/src/libvt/codec.py @@ -0,0 +1,234 @@ +"""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", + "a": "HPR", + "b": "REP", + "c": "DA1", + "d": "VPA", + "e": "VPR", + "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..de514d5 --- /dev/null +++ b/src/libvt/config.py @@ -0,0 +1,352 @@ +"""Terminal identity profiles, security policies, and resource ceilings.""" + +from __future__ import annotations + +import enum +import re +import typing as t +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*(?:tmux\s+)?(?:next-)?(\d+)\.(\d+)(?:[a-z]|-rc\d*)?\s*$", +) + + +class ColorScheme(enum.IntEnum): + """``CSI ? 997 ; Ps n`` color-scheme values (``DEC ?2031`` / ``DSR ?996n``).""" + + DARK = 1 + LIGHT = 2 + + +@dataclass(frozen=True, slots=True, kw_only=True) +class Profile: + r"""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 + (``""`` 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] + 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`` 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 + 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. + 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``). + 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. + 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. + 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). + 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" + 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 + vs15_narrows_wide_emoji: bool = True + vs16_always_wide: bool = False + tmux_window_rename: bool = False + 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" + 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`. + + 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', 'next-3.9', 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, + 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", + ) + + +DEFAULT_OSC7_HOSTS: frozenset[str] = frozenset({"", "localhost"}) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class Policy: + r"""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 + 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 + 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``). + 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`. ``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 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 + 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 = True + allow_unsafe_uris: bool = False + allow_passthrough: bool = False + 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) +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 (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 + 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 + (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 + 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 + max_csi_params: int = 32 + max_osc_bytes: int = 131_072 + 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 = 256 + max_events: int = 4_096 + 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() +XTERM_PROFILE = Profile( + name="xterm", + osc_7501_capabilities="", + reflow_on_resize=False, + 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=False) +DEFAULT_LIMITS = Limits() + +__all__ = [ + "DEFAULT_LIMITS", + "DEFAULT_OSC7_HOSTS", + "DEFAULT_POLICY", + "DEFAULT_PROFILE", + "LINUX_CONSOLE_PROFILE", + "TMUX_CAPTURE_POLICY", + "TMUX_PROFILE", + "XTERM_PROFILE", + "Charset", + "ColorScheme", + "Limits", + "Policy", + "Profile", + "SixelErasePolicy", +] diff --git a/src/libvt/events.py b/src/libvt/events.py new file mode 100644 index 0000000..bf5a9d3 --- /dev/null +++ b/src/libvt/events.py @@ -0,0 +1,388 @@ +"""Closed algebraic Event union and structured terminal notification records.""" + +from __future__ import annotations + +import collections.abc +import enum +import types +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``). + 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``. + """ + + kind: PromptKind + abs_row: int + col: int + exit_code: int | None = None + + +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 : collections.abc.Mapping[str, str] + Immutable key-value control header pairs before ``;``. + payload : bytes + Encoded payload bytes following ``;``. + """ + + row: int + col: int + 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: + """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 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. + + 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 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``. + + 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 + | WindowRenamed + | WorkingDirectoryChanged + | ClipboardWrite + | PromptMark + | ProgramStatusChanged + | RenderHoldChanged + | ColorSchemeQueried + | InBandResize + | SixelGraphic + | KittyGraphic + | ScreenErased + | Passthrough + | UnhandledSequence +) + +__all__ = [ + "Bell", + "ClipboardWrite", + "ColorSchemeQueried", + "EraseCause", + "Event", + "InBandResize", + "KittyCommand", + "KittyGraphic", + "Passthrough", + "ProgramStatusChanged", + "PromptKind", + "PromptZone", + "Rect", + "RenderHoldChanged", + "ScreenErased", + "SixelData", + "SixelGraphic", + "TitleChanged", + "UnhandledSequence", + "WindowRenamed", + "WorkingDirectoryChanged", +] diff --git a/src/libvt/exc.py b/src/libvt/exc.py new file mode 100644 index 0000000..6d83109 --- /dev/null +++ b/src/libvt/exc.py @@ -0,0 +1,213 @@ +"""Exceptions raised by libvt.""" + +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.""" + + +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.""" + + +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 + 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) + OSError.__init__(obj, *os_args) + if raw_args is not None and obj.args != raw_args: + obj.args = raw_args + return obj + + +class TerminalTimeoutError(LibVtError, TimeoutError): + """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 | None = None, + *, + parser_state: ParserState | None = None, + screen_text: str = "", + recent_bytes: collections.abc.Buffer = b"", + eof: bool = False, + diagnostics: str = "", + attach_note: bool = True, + ) -> None: + if message is None: + super().__init__() + else: + super().__init__(message) + self.parser_state = parser_state + self.screen_text = screen_text + self.recent_bytes = bytes(recent_bytes) + self.eof = 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__``.""" + 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, self.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 + 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) + + +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/graphics.py b/src/libvt/graphics.py new file mode 100644 index 0000000..681f5fe --- /dev/null +++ b/src/libvt/graphics.py @@ -0,0 +1,1695 @@ +"""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). + 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. + 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 + 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 + + @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_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.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 = (abs_row - self.abs_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) -> ImagePlacement: + return ImagePlacement( + protocol=self.protocol, + image_id=self.image_id, + placement_id=self.placement_id, + abs_row=self.abs_row, + col=self.col, + rows=self.rows, + cols=self.cols, + 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) -> tuple[ImagePlacement, ...]: + """Freeze stored placements into immutable :class:`ImagePlacement` records.""" + if not self._placements: + return () + 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*.""" + 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: + 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 + 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, + min_abs: int = 0, + ) -> None: + """Record a scanned ``SIXEL`` image and placement at post-scroll *row*.""" + abs_r = scrolled_total + row + eff_rows = rows + 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 + abs_r = min_abs + 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=max(0, abs_r), + col=col, + rows=eff_rows, + cols=cols, + source_y=eff_src_y, + source_width=width_px, + source_height=eff_h_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, + 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. + + 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. + 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 + 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, + min_row=min_row, + 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, + min_row=min_row, + 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, + min_row=min_row, + 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, + min_row: int = 0, + 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, + min_row=min_row, + 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, + min_row: int = 0, + 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 + ) + + 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: + 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 + 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=max(0, 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, + ), + ) + 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", +] diff --git a/src/libvt/input.py b/src/libvt/input.py new file mode 100644 index 0000000..51d6f96 --- /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"`` through ``"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..6b214a6 --- /dev/null +++ b/src/libvt/modes.py @@ -0,0 +1,145 @@ +"""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 + 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 + 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..d1a48b7 --- /dev/null +++ b/src/libvt/parser.py @@ -0,0 +1,1208 @@ +"""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 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 + +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]") +_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"] + + +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 + STRING_ESC = 14 + + +@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"``, ``b"\x1b\\"``, or + ``b"\x9c"`` in Latin-1 8-bit mode). + """ + + 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): + 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: + 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 VT500 / ANSI escape-sequence byte parser.""" + + __slots__ = ( + "_abort_dispatch_osc", + "_csi_colon_mask", + "_csi_cur", + "_csi_has_digit", + "_csi_is_colon", + "_csi_memo", + "_csi_omitted_mask", + "_csi_prefix", + "_csi_vals", + "_dcs_final", + "_dcs_params", + "_encoding", + "_intermediates", + "_latin1", + "_limits", + "_state", + "_str_buf", + "_str_esc_origin", + "_str_kind", + "_str_overflow", + "_tmux_dcs_state", + "_tmux_passthrough", + "_tmux_window_rename", + "_utf8", + "_utf8_pending", + ) + + def __init__( + self, + *, + 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"): + 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._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") + 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_final: int = 0 + self._str_buf = bytearray() + self._str_overflow: bool = False + self._str_kind: int = 0 + 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`.""" + 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._abort_string() + + 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 _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: + 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: + cleaned = _C1_CHAR_RE.sub("", decoded) + 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() + return + raw = bytes(self._str_buf) + self._abort_string() + 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, + bytes(self._intermediates), + self._dcs_final, + bytes(self._str_buf), + ) + self._abort_string() + + def _dispatch_apc(self, sink: ActionSink) -> None: + 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: + self._dcs_params = self._finalize_params() + self._dcs_final = final_byte + self._str_buf.clear() + self._str_overflow = False + 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: + 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 + latin1 = self._latin1 + 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 latin1: + 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: + break + 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) + 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._state = ParserState.ESCAPE + elif b == 0x7F: + pass + else: + self._flush_incomplete_utf8(sink) + sink.on_execute(b) + continue + + if state == ParserState.OSC_STRING: + 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[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] + pos += 1 + if b == 0x07: + self._dispatch_osc(sink, b"\x07") + self._state = ParserState.GROUND + 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._str_esc_origin = ParserState.OSC_STRING + self._state = ParserState.STRING_ESC + else: + self._abort_string() + self._state = ParserState.GROUND + continue + + if state == ParserState.DCS_PASSTHROUGH: + 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[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 + ) + else: + self._str_buf.clear() + self._str_overflow = True + self._notify_overflow(sink, "dcs", max_dcs) + pos = end + if pos >= n: + break + b = mv[pos] + pos += 1 + if b == 0x7F: + continue + 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._str_esc_origin = ParserState.DCS_PASSTHROUGH + self._state = ParserState.STRING_ESC + else: + self._abort_string() + self._state = ParserState.GROUND + continue + + if state == ParserState.SOS_PM_APC_STRING: + 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 ( + end > pos + and self._str_kind in (0x5F, 0x6B) + and not self._str_overflow + ): + 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[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] + pos += 1 + 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._str_esc_origin = ParserState.SOS_PM_APC_STRING + self._state = ParserState.STRING_ESC + else: + self._abort_string() + self._state = ParserState.GROUND + continue + + 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 ( + 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: + self._str_buf.append(0x1B) + 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 + # 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 + + 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._abort_string() + self._state = ParserState.GROUND + continue + + if state == ParserState.DCS_IGNORE: + continue + + if b < 0x20: + sink.on_execute(b) + continue + if b == 0x7F: + continue + + if state == ParserState.ESCAPE: + 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) 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 + 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._enter_dcs_passthrough(b) + 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._enter_dcs_passthrough(b) + else: + self._state = ParserState.DCS_IGNORE + + +__all__ = [ + "EMPTY_PARAMS", + "Action", + "ActionSink", + "ApcDispatch", + "CsiDispatch", + "CsiParams", + "DcsDispatch", + "EscDispatch", + "Execute", + "OscDispatch", + "Parser", + "ParserEncoding", + "ParserState", + "Print", + "parse_sgr", +] diff --git a/src/libvt/pytest_plugin.py b/src/libvt/pytest_plugin.py index 1936d84..525943e 100644 --- a/src/libvt/pytest_plugin.py +++ b/src/libvt/pytest_plugin.py @@ -1,5 +1,173 @@ -"""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, TtyMode + 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, + 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.""" + + +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 + 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 + + +__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..2d2b579 --- /dev/null +++ b/src/libvt/screen.py @@ -0,0 +1,1607 @@ +"""Zero-based screen buffer, lazy cell/row/region views, reflow, and dual screens.""" + +from __future__ import annotations + +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, + 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 + +_ITEM0 = operator.itemgetter(0) + + +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) + + +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.""" + + __slots__ = ("_col_range", "_row", "_row_idx", "_screen") + + def __init__( + self, + row: RowLike, + col_range: range | None = None, + *, + screen: Screen | None = None, + row_idx: int = -1, + ) -> None: + self._row = row + 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._current_row().wrapped + + @property + def text(self) -> str: + """Return right-trimmed rendered text for this row slice.""" + 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 row.rstrip_text() + 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 "" + if isinstance(row, _Row): + raw = "".join(row.chars[self._col_range.start : limit]) + else: + 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.""" + row = self._current_row() + limit = min(self._col_range.stop, row.used) + 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) + 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 = row.attr_at(c) + role_bits = raw_width_bits(word) + if role_bits in (int(WidthRole.SPACER_TAIL), int(WidthRole.SPACER_HEAD)): + continue + ext = row.ext_at(c) + st = unpack_style(word, ext) + lnk = ext.hyperlink if ext is not None else None + ch = row.chars[c] if isinstance(row, _Row) else 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`.""" + row = self._current_row() + if isinstance(index, slice): + sub = _slice_indices(index, len(self._col_range)) + base = self._col_range.start + 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(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)``.""" + + __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], + *, + 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], 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)) + + 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__ = ( + "_cell_height_px", + "_cols", + "_cur_blinking", + "_cur_col", + "_cur_row", + "_cur_shape", + "_cur_visible", + "_evicted_total", + "_gfx", + "_history", + "_history_clear_at", + "_history_clear_seq", + "_is_alt", + "_max_image_dimension", + "_max_images", + "_max_placements", + "_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, + cell_height_px: int = 16, + 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})" + raise ValueError(msg) + self._cols = cols + self._rows: list[_Row] = [_Row(cols) for _ in range(rows)] + self._history: _HistoryBuffer = _HistoryBuffer(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._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 + 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 + 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) -> collections.abc.Sequence[RowView]: + """Return ``O(1)`` immutable :class:`RowView` sequence over scrollback.""" + return _HistoryView(self._history.freeze()) + + @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._evicted_total += len(self._history) + 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() + + def _append_history(self, frozen: FrozenRow) -> None: + 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: + 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] == " " + 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 + bump_row_gen(row_obj) + 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 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: + 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 + ) and self._clear_row_spacer_head(prev): + prev.wrapped = False + + @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[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], + ) -> RowView | Cell | RegionView: + """Index a row, single ``(row, col)`` cell, or 2D region view.""" + return slice_grid(self._rows, self._cols, key, screen=self) + + 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, + 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 + 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 + full_screen = full_width and t_row == 0 and b_row == len(self._rows) - 1 + + if full_width: + if t_row > 0: + 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: + 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]) + 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, + 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 (advances_abs and not full_screen) else 0 + ), + ) + evicted = self._rows[t_row : t_row + shift] + 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( + 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 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]) + 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] + 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) + 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)) + _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 + 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( + 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, + 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 + 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 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: + 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] + 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: + 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): + 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) + 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)) + _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 + 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( + 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.""" + last_used = -1 + for idx in range(len(self._rows) - 1, -1, -1): + 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 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( + 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) + + 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 + 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 + total = len(combined) + while idx < total: + group_start = idx + while idx + 1 < total and combined[idx].wrapped: + idx += 1 + group_end = idx + idx += 1 + + 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 + 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 == eff_cur_col + if rb == int(WidthRole.SPACER_HEAD): + if is_cur: + carry_cur = True + continue + if rb == int(WidthRole.SPACER_TAIL): + if is_cur and cells: + 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), + 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: + 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 + continue + + cur_out = _Row(cols) + new_all.append(cur_out) + out_col = 0 + for ch, base_w, cw, ce, cur_off 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 cur_off >= 0 and not cursor_placed: + new_cur_abs = len(new_all) - 1 + new_cur_col = min(cols - 1, out_col + cur_off) + new_pending_wrap = False + 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 + + 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)) + + 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()) + 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: + 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)) + 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.""" + 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 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) + 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. + top_excess = max(0, self._cur_row - (rows - 1)) + top_drop = min(drop_needed, top_excess) + if top_drop > 0: + 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( + 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: + del self._rows[rows:] + 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 + + 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() + if self._gfx is not None: + self._gfx.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.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 + 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: + """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, + 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, + is_alt=True, + ) + 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..83559b8 --- /dev/null +++ b/src/libvt/style.py @@ -0,0 +1,207 @@ +"""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() + +_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", + "Color", + "Hyperlink", + "IndexedColor", + "RgbColor", + "Style", + "UnderlineStyle", +] diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py new file mode 100644 index 0000000..ab3bbe2 --- /dev/null +++ b/src/libvt/terminal.py @@ -0,0 +1,4264 @@ +"""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 re +import types +import typing as t +import urllib.parse +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, + make_cell_ext, + pack_pen_base, + raw_width_bits, + unpack_style, +) +from libvt._ucd import ( + CLUSTER_NONE, + GCB_PREPEND, + SAFE_NARROW_BMP_RE, + 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, + TMUX_CAPTURE_POLICY, + TMUX_PROFILE, + Charset, + Limits, + Policy, + Profile, +) +from libvt.events import ( + Bell, + ClipboardWrite, + ColorSchemeQueried, + EraseCause, + Event, + InBandResize, + KittyCommand, + KittyGraphic, + Passthrough, + ProgramStatusChanged, + PromptKind, + PromptMark, + PromptZone, + Rect, + RenderHoldChanged, + ScreenErased, + SixelData, + SixelGraphic, + TitleChanged, + UnhandledSequence, + WindowRenamed, + 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, + DEC_PRIVATE_MASK, + TRANSIENT_SNAPSHOT_MODES, + Mode, + ModeState, +) +from libvt.parser import CsiParams, Parser, ParserEncoding, ParserState, parse_sgr +from libvt.screen import ( + Cell, + Cursor, + CursorShape, + RegionView, + RowView, + Screen, + ScreenSet, + ScrollRegion, + _HistoryView, + format_rows_text, + slice_grid, +) +from libvt.status import ProgramStatus, ProgramStatusStore +from libvt.style import ( + DEFAULT_STYLE, + AnsiColor, + Color, + Hyperlink, + IndexedColor, + Style, + UnderlineStyle, + _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( + { + "_": " ", + "`": "◆", + "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:") +_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]+") + +_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 : collections.abc.Sequence[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: collections.abc.Sequence[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): + """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[Charset, Charset, Charset, Charset] + 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[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. + + 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 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] + 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", + "_evicted_total", + "_frozen", + "_history", + "_rows", + "_scrolled_total", + "active_is_alt", + "cursor", + "cwd", + "cwd_uri", + "generation", + "images", + "modes", + "placements", + "program_status", + "program_statuses", + "prompt_zones", + "title", + ) + + def __init__( + self, + *, + rows: tuple[_Row, ...], + history: _FrozenHistory | collections.abc.Sequence[FrozenRow] = ( + _EMPTY_FROZEN_HISTORY + ), + cols: int, + cursor: Cursor, + title: str, + cwd: str, + cwd_uri: str = "", + modes: frozenset[Mode], + active_is_alt: bool, + prompt_zones: tuple[PromptZone, ...], + program_status: ProgramStatus | None, + program_statuses: collections.abc.Mapping[str, ProgramStatus], + 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 + hist_obj = _FrozenHistory.from_sequence(history) + self._history: _FrozenHistory = hist_obj + self._cols = cols + eff_scrolled = ( + (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(hist_obj))) + if evicted_total is None + else evicted_total + ) + 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 + self.program_status = program_status + 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: + """Return snapshot height in rows.""" + return len(self._rows) + + @property + 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.at(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) -> collections.abc.Sequence[RowView]: + """Return ``O(1)`` immutable :class:`RowView` sequence over scrollback rows.""" + return _HistoryView(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[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], + ) -> 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, + profile: Profile = DEFAULT_PROFILE, + ) -> str: + """Render this snapshot using :class:`Formatter`.""" + 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.""" + 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": { + "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, + "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": ( + { + "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, + } + if self.program_status is not None + else None + ), + "placements": [ + { + "protocol": p.protocol.value, + "image_id": p.image_id, + "placement_id": p.placement_id, + "abs_row": p.abs_row, + "viewport_row": self.viewport_row(p.abs_row), + "col": p.col, + "rows": p.rows, + "cols": p.cols, + "z_index": p.z_index, + "virtual": p.virtual, + } + for p in self.placements + ], + } + + +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", "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`.""" + 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 "") + 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)): + 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 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: + 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
+        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] = []
+            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.dim:
+                    css.append("opacity:0.65")
+                if style.italic:
+                    css.append("font-style:italic")
+                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
+                    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 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() + + +_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, + 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() + self._event_bytes: int = 0 + self._screens = ScreenSet( + rows=rows, + 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: + 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 + self._protected: bool = False + self._pen_word: int = 0 + self._hyperlink: Hyperlink | None = None + self._cell_ext: _CellExt | None = None + 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) + 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 + 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 = "" + 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._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 + + @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, + ) + + @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.""" + 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) -> collections.abc.Sequence[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 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``.""" + 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`.""" + 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 primary-screen ``OSC 133`` semantic prompt zones.""" + return tuple(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 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.""" + 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 _invalidate_cache(self) -> None: + if self._cached_snapshot is not None: + self._cached_snapshot = None + self._generation += 1 + + def _build_snapshot( + self, + *, + exclude_modes: frozenset[Mode] = frozenset(), + ) -> Snapshot: + scr = self._screens.active + 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=self._screens.primary._history.freeze(), + cols=scr.cols, + cursor=scr.cursor, + title=self._title, + cwd=self._cwd, + cwd_uri=self._cwd_uri, + modes=modes, + 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( + 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: + if self._sync_hold_pending and self._held_snapshot is 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) + 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 = () + 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 = ( + 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 zero_hist_cap: + new_hist = () + evicted_cnt = 0 + else: + if added > hist_len: + return _full(ResyncReason.HISTORY_EVICTED) + 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 = ( + 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 ( + 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 + + @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[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], + ) -> 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: + 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) + + 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() + self._event_bytes = 0 + 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._held_sync_token = None + self._cached_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.""" + 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), + ) + + 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 = CLUSTER_NONE + self._cluster_len = 0 + self._pending_prepend = "" + + 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 | 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=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 + 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)) + + 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() + 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 + 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 + self._held_sync_token = None + 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._epoch += 1 + 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(g_sets=def_g) + self._saved_alt = _SavedCursor(g_sets=def_g) + 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 = "" + self._prompt_zones.clear() + self._status_store.reset() + self._aux_revision += 1 + self._notify_erase( + 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.""" + 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) + ): + 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) + 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, + ): + 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) + 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: + 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 + 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, + abs_row=z.abs_row + count, + col=z.col, + exit_code=z.exit_code, + ), + ) + 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) + 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: + 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=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, + ) + 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=keep_wrap) + 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] + 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 _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": + text = self._map_charset(text) + + scr = self._screens.active + autowrap = self._modes.is_set(Mode.DECAWM) + insert_mode = self._modes.is_set(Mode.IRM) + _, bottom, left, right = self._effective_margins(scr) + + mode_2027 = self._modes.is_set(Mode.GRAPHEME_CLUSTERING) + 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() + ): + 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 + + ch = text[t_idx] + t_idx += 1 + cp = ord(ch) + 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 + 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 + 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 + ): + prev_cluster_len = self._cluster_len + combined = row_obj.chars[pc] + ch + 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 + 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, + base_pen, + base_ext, + ) + 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: + 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 + + 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) + 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, + ) + vacated_bce = ( + (self._pen_word & _PEN_BG_MASK) if w_override == 1 else 0 + ) + row_obj.append_grapheme( + pc, + ch, + width_override=w_override, + bce_word=vacated_bce, + ) + 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 ( + 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 + 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 + else: + self._clear_cluster_anchor() + 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 + just_wrapped_wide = False + + if scr._pending_wrap and autowrap: + can_advance = c_row < scr.rows - 1 or ( + c_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 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 + + if width == 2 and c_col == max_col: + 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() + 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 + else: + 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() + 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_full, + self._pen_word, + self._cell_ext, + ) + written_cols = 2 + 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_full, + self._pen_word, + self._cell_ext, + ) + written_cols = 1 + 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, + ) + + 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 + self._cluster_len = len(ch_full) + + 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: + self._before_mutate() + 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: + self._last_printed = "" + 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: + 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 + 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) + restored_wrap = ( + False if self._profile.pending_wrap_phantom_col else saved.pending_wrap + ) + self._set_cursor( + scr, + saved.row, + saved.col, + pending_wrap=restored_wrap, + ) + + 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 + 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) + 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( + 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=keep_wrap, + ) + 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() + fill = "E" * scr.cols + for r in scr._rows: + 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") + 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 == 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._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( + active=enabled, + sync_generation=self._sync_generation, + ), + ) + return + + 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._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() + elif not enabled: + self._modes.sync_alt_screen(active_is_alt=False) + return + + self._before_mutate() + 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() + + def _erase_display( + self, + scr: Screen, + mode: int, + *, + 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 + 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) + scr._rows[c_row].clear_range( + c_col, + scr.cols, + bce_w, + bce_e, + 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, + ) + 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, end_c) + scr._rows[c_row].clear_range( + 0, + end_c, + bce_w, + 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: + 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) + 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) + + def _erase_line( + self, + scr: Screen, + mode: int, + *, + selective: bool, + ) -> 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 + 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( + c_col, + scr.cols, + bce_w, + bce_e, + 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 + scr.heal_before_edit(c_row, 0, end_c) + scr._rows[c_row].clear_range( + 0, + end_c, + bce_w, + bce_e, + selective=selective, + ) + 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) + scr._rows[c_row].clear_range( + 0, + scr.cols, + bce_w, + 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) + + def _handle_csi( + self, + prefix: int, + params: CsiParams, + 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) + + # 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"): + if self._profile.decstr_enabled: + self.reset(soft=True) + return + + # 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 + 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: + 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 + phantom_extra) + if self._modes.is_set(Mode.DECOM) + 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: + 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 == "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): + target_r = min(bottom, top + row_1 - 1) + else: + target_r = min(scr.rows - 1, row_1 - 1) + 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 + 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) + 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 + 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() + 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 + 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 + 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() + scr.heal_before_edit(c_row, c_col, right + 1) + scr._rows[c_row].insert_blanks( + c_col, + n, + left=left, + right=right, + 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: + return + 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 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, + left=left, + right=right, + bce_word=bce_w, + bce_ext=bce_e, + ) + 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: + 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, + bottom=bottom, + left=left, + 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), + EraseCause.SCROLL, + ) + 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, + bottom=bottom, + left=left, + right=right, + save_history=False, + bce_word=bce_w, + bce_ext=bce_e, + is_line_op=True, + ) + self._notify_erase( + Rect( + max(c_row, bottom - n + 1), + left, + min(n, bottom - c_row + 1), + right - left + 1, + ), + EraseCause.SCROLL, + ) + 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) + 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 prev_printed: + count = min(self._limits.max_rep_count, params.get(0, 1)) + 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 + 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: + 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 + phantom_extra) + if self._modes.is_set(Mode.DECOM) + else (c_col + 1 + phantom_extra) + ) + 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 + 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[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( + 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._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}") + + def _handle_window_rename(self, raw: bytes) -> None: + self._last_printed = "" + try: + 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: + self._before_mutate() + cleaned = raw_uri.strip() + if not cleaned or "\x00" in cleaned: + self._cwd = "" + self._cwd_uri = "" + self._emit_event(WorkingDirectoryChanged(uri="", path="")) + return + 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 + 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: + self._last_printed = "" + scr = self._screens.active + 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)) + elif code == 1: + return + elif code == 7: + 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(";") + 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(): + 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) + 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) + 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: + 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"): + self._before_mutate() + 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]) + 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), + ) + elif code == 7501: + if data == b"?": + 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 + 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: + 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: + self._last_printed = "" + # 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 ( + prefix == 0 + and not intermediates + and not params.values + and final == ord("t") + and data.startswith(b"mux;") + ): + 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: + 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) + finally: + self._passthrough_depth -= 1 + return + + # 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 + 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, + height_px=h_px, + row=post_r, + col=anchor_c, + 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( + SixelGraphic( + data=SixelData( + row=orig_row, + col=orig_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: + self._last_printed = "" + if data.startswith(b"G"): + 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] + 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 + 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 + 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, + min_row=(top if in_margins else 0), + 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)}") + + +def render( + data: collections.abc.Buffer | str, + /, + *, + 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, + newline_mode=newline_mode, + ) + 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", + "ResyncReason", + "ScreenDelta", + "Snapshot", + "StepResult", + "StopOn", + "SyncToken", + "SyncView", + "Terminal", + "render", + "strip", +] diff --git a/src/libvt/testing.py b/src/libvt/testing.py new file mode 100644 index 0000000..58656f3 --- /dev/null +++ b/src/libvt/testing.py @@ -0,0 +1,282 @@ +"""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 _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 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 + ---------- + 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 right-trimmed 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") + exp_lines = cleaned.split("\n") if cleaned else [] + 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}┘") + _raise_mismatch(target, snap, "\n".join(exp_box_lines), actual_box, cursor) + + +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/src/libvt/tmux.py b/src/libvt/tmux.py new file mode 100644 index 0000000..4caea3d --- /dev/null +++ b/src/libvt/tmux.py @@ -0,0 +1,1011 @@ +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" + "#{synchronized_output_flag}\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 + (``#{synchronized_output_flag}``). + 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 + 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, nxt_mod - mod_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 _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_lines: list[str], + cols: int, +) -> tuple[list[bool], list[bool]] | None: + n = len(plain_rows) + if len(joined_lines) == 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]): + 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] + 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, spacer_heads) 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 + row._frozen = None + + +def _populate_screen_from_lines( + target: Screen, + raw_lines: list[str], + *, + rows: int, + cols: int, + tabstops: tuple[int, ...], + flagged: bool, + joined_capture: CaptureInput | None, + stripped_trailing: int = 0, + 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] + inferred_spacers: list[bool] | None = None + 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] + 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, decoded_joined, cols + ) + if inferred is not None: + exact_wraps = True + row_wraps, inferred_spacers = 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 ( + 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) + 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] + if fl & TmuxLineFlags.START_PROMPT: + zones.append( + PromptZone( + kind=PromptKind.PROMPT_START, + abs_row=idx, + col=0, + ), + ) + if fl & TmuxLineFlags.START_OUTPUT: + zones.append( + PromptZone( + kind=PromptKind.COMMAND_EXECUTED, + abs_row=idx, + col=0, + ), + ) + + 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 - -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) + 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) + 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, + stripped_trailing=stripped_trailing, + 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/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_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_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.py b/tests/test_codec.py new file mode 100644 index 0000000..5a5f7d2 --- /dev/null +++ b/tests/test_codec.py @@ -0,0 +1,59 @@ +"""Tests for ``libvt.codec`` sequence disassembly and ``python -m libvt`` CLI.""" + +from __future__ import annotations + +import io +import pathlib +import sys + +import pytest + +from libvt.__main__ import main +from libvt.codec import explain, format_explain + + +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\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] + 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_subcommands_file_and_stdin( + tmp_path: pathlib.Path, + capsys: pytest.CaptureFixture[str], + monkeypatch: pytest.MonkeyPatch, +) -> None: + """``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") + + 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 + assert "SGR" in capsys.readouterr().out + + monkeypatch.setattr( + sys, + "stdin", + io.TextIOWrapper(io.BytesIO(b"\x1b[1;34mpiped\x1b[0m\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..ceafb5d --- /dev/null +++ b/tests/test_exc.py @@ -0,0 +1,388 @@ +"""Tests for ``libvt.exc`` exception hierarchy, notes, and pickling.""" + +from __future__ import annotations + +import copy +import errno +import pickle +import sys +import traceback + +import pytest + +from libvt.exc import TerminalTimeoutError, _reconstruct_timeout_error +from libvt.parser import ParserState + + +class _SlottedTimeoutError(TerminalTimeoutError): + """Subclass with ``__slots__`` and custom keyword-only ``__init__``.""" + + __slots__ = ("attempt",) + + def __init__( + self, + message: str | None = None, + *, + 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 _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", + screen_text="secret-viewport", + attach_note=False, + ) + assert not hasattr(quiet, "__notes__") + assert "secret-viewport" in quiet.format_diagnostics() + 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, args, descriptors, and 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 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__ + 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", + 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" + + 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" + 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__ + + +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__ diff --git a/tests/test_graphics.py b/tests/test_graphics.py new file mode 100644 index 0000000..a5b252f --- /dev/null +++ b/tests/test_graphics.py @@ -0,0 +1,181 @@ +"""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 not hasattr(kp, "row") + assert (kp.protocol, kp.abs_row, kp.col, kp.rows, kp.cols, kp.layer) == ( + GraphicsProtocol.KITTY, + 1, + 2, + 2, + 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. + 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].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 + ) + + +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\\") + 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")) + 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_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") + 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_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_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..2cbf15a --- /dev/null +++ b/tests/test_parser.py @@ -0,0 +1,173 @@ +"""Tests for ``libvt.parser`` VT500 state transitions, SGR, and wire encodings.""" + +from __future__ import annotations + +import typing as t + +import pytest + +import libvt +from libvt.config import Limits, Policy +from libvt.parser import ( + Action, + ApcDispatch, + CsiDispatch, + DcsDispatch, + EscDispatch, + OscDispatch, + Parser, + ParserState, + 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 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 + + +@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() + + 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) + + 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, 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) + 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, 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 + assert term[0, 2].style == libvt.Style() + + +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, term.text) == (title, "ok") + + smuggled = Parser(encoding="utf-8").feed(b"\xc2\x9b31mSAFE") + assert _coalesce_prints(smuggled) == [Print("31mSAFE")] + assert libvt.strip(b"\xc2\x9b31mSAFE") == "31mSAFE" + + 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 isinstance(actions[1], ApcDispatch) + + 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"), + EscDispatch(b"", ord("M")), + 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")) + + # 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_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 + assert p.feed(b"c") == [EscDispatch(b"", ord("c"))] + assert p.state == ParserState.GROUND + + # 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, + limits=Limits(max_osc_bytes=16), + record_events=True, + ) + term.feed(b"\x1b]2;cut\x1b[32mok") + assert (term.title, term.text) == ("", "ok") + assert term[0, 0].style.fg == AnsiColor.GREEN + + 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, opt_term.text) == ("committed", "RX") + + term.reset() + term.feed(b"\x1b]2;short\x1b\x1b\\after") + assert (term.title, term.text) == ("", "after") + + 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.drain_events() + term.feed(b"\x1b]2;" + (b"x" * 64) + b"\x07clean") + assert (term.title, term.text) == ("", "clean") + assert any(isinstance(ev, libvt.UnhandledSequence) for ev in term.drain_events()) diff --git a/tests/test_screen.py b/tests/test_screen.py new file mode 100644 index 0000000..c63d90a --- /dev/null +++ b/tests/test_screen.py @@ -0,0 +1,390 @@ +"""Tests for ``libvt._grid`` and ``libvt.screen`` rows, healing, reflow, and fuzz.""" + +from __future__ import annotations + +import collections.abc +import random +import time +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 +from libvt.style import AnsiColor + + +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_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) + 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..253d724 --- /dev/null +++ b/tests/test_status.py @@ -0,0 +1,230 @@ +"""Tests for ``libvt.status`` (``OSC 7501`` / ``9;4``) and ``OSC 133/7/52``.""" + +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.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 + 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") + 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 new file mode 100644 index 0000000..9154c25 --- /dev/null +++ b/tests/test_terminal.py @@ -0,0 +1,405 @@ +"""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 ( + DEFAULT_PROFILE, + TMUX_PROFILE, + XTERM_PROFILE, + Policy, + Profile, + SixelErasePolicy, +) +from libvt.events import RenderHoldChanged, ScreenErased +from libvt.exc import ProtocolError +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" + + 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_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) + term.feed(b"\x1b[2Ia\x1b[2Zb") + assert (term[0, 16].text, term[0, 8].text) == ("a", "b") + + term.reset() + term.feed(b'\x1b[1"qSAFE\x1b[0"qWIPE\x1b[?2K\x1b[?2J') + assert term[0].text == "SAFE" + term.feed(b"\x1b[2J") + assert term[0].text == "" + + term.reset() + 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 (tuple(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") + + # 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" + + 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" + tm.reset() + tm.feed(b"abcdef\x08\x08Z") + assert tm[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" + + 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" + + 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) + 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, part2.offset, utf8_term[0, 0].text) == ( + StopOn.GROUND, + 1, + "日", + ) + + +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[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\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 + + 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..099e2c5 --- /dev/null +++ b/tests/test_tmux.py @@ -0,0 +1,309 @@ +"""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 + 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" + "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=6, history_size=2) + cjk_term = libvt.Terminal.from_tmux_capture( + [ + "\x0elqqk\x0f", + "\x1b[5:3mH1\x1b[0m", + "ABCD", + "EFGH", + "ab ", + "中文", + "abc ", + "中文", + ], + metadata=cjk_meta, + 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.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=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=TmuxPaneMetadata(cols=4, rows=5, history_size=2), + scrollback=1, + flagged=True, + ) + 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, + 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`` reconstructs ACS, wraps, tabs, 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[?1000h\\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", + "-", + "-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", + "-L", + sock, + "capture-pane", + "-S", + "-", + "-E", + "-", + "-F", + "-e", + "-p", + "-N", + ], + check=False, + capture_output=True, + text=True, + ) + if flagged_proc.returncode == 0: + candidates.append( + decode_tmux_capture( + flagged_proc.stdout, + metadata=meta_raw, + flagged=True, + ), + ) + 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[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..360d60e --- /dev/null +++ b/tests/test_ucd.py @@ -0,0 +1,366 @@ +"""Tests for ``libvt._ucd`` Unicode 17 width, UAX #29 clustering, and BMP regex.""" + +from __future__ import annotations + +import array +import collections.abc +import hashlib +import pathlib +import sys +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, + 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): + """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") + + +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"