From 683571144435302f59d6c42d623267251d929372 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 28 Nov 2026 20:03:24 -0600 Subject: [PATCH] terminal(feat[compat]): Add DECCOLM, CP437, DOCS (#58) why: Legacy VT streams and pyte callers rely on 80/132-column switching, IBM PC CP437 graphic designations, and ISO-2022 wire-encoding switches without weakening modern UTF-8 or tmux geometry defaults. what: - Add Mode.DECCOLM (?3), Mode.ALLOW_80_132 (?40), Mode.DECNCSM (?95), and DeccolmBehavior (default GATED_BY_MODE_40; CLEAR_ONLY on tmux) - Add 'U' (IBM PC / CP437 0xA0..0xFF) G0..G3 charset mapping in latin-1 mode while keeping 'V' as a documented US-ASCII fallback - Add opt-in Parser.allow_encoding_switch for ESC % G / ESC % @ DOCS transitions, codec.explain disassembly, and feed_str() latin-1 guard --- CHANGES | 28 +++ docs/api/config.md | 4 +- src/libvt/codec.py | 3 + src/libvt/config.py | 27 ++- src/libvt/contrib/tmux/profile.py | 2 + src/libvt/modes.py | 3 + src/libvt/parser.py | 29 ++- src/libvt/profiles.py | 3 + src/libvt/terminal.py | 228 ++++++++++++++++++++++-- tests/test_pyte_compat.py | 284 ++++++++++++++++++++++++++++++ 10 files changed, 592 insertions(+), 19 deletions(-) create mode 100644 tests/test_pyte_compat.py diff --git a/CHANGES b/CHANGES index 77faa99..e63eab5 100644 --- a/CHANGES +++ b/CHANGES @@ -6,6 +6,34 @@ _Notes on the upcoming release will go here._ +### What's new + +#### Mode-gated 80/132-column switching, `CP437` charset, and wire-encoding transitions (#58) + +{class}`~libvt.modes.Mode` adds {attr}`~libvt.modes.Mode.DECCOLM` (`?3`), +{attr}`~libvt.modes.Mode.ALLOW_80_132` (`?40`), and +{attr}`~libvt.modes.Mode.DECNCSM` (`?95`), governed by +{attr}`ScreenBehavior.deccolm ` +({class}`~libvt.config.DeccolmBehavior`). +{data}`~libvt.config.DEFAULT_PROFILE` uses +{attr}`~libvt.config.DeccolmBehavior.GATED_BY_MODE_40` with `?40` initially +reset (`?3h` selects `132` columns and `?3l` selects `80` columns once `?40h` +is enabled), {func}`~libvt.contrib.tmux.profile.tmux_profile` uses +{attr}`~libvt.config.DeccolmBehavior.CLEAR_ONLY` so `tmux` retains +authoritative pane geometry, and {data}`~libvt.profiles.LINUX_CONSOLE_PROFILE` +uses {attr}`~libvt.config.DeccolmBehavior.IGNORE`. + +`G0`–`G3` character-set designations ({type}`~libvt.config.Charset`) add `'U'` +(`IBM PC` / `CP437` `0xA0`–`0xFF` graphic mapping in `"latin-1"` parser mode). +{class}`~libvt.parser.Parser` adds {meth}`~libvt.parser.Parser.set_encoding` +and `allow_encoding_switch`, wired to +{attr}`ScreenBehavior.allow_encoding_switch ` +(`False` by default; `True` on {data}`~libvt.profiles.LINUX_CONSOLE_PROFILE`) +for ISO-2022 `DOCS` (`ESC % G` / `ESC % @`) transitions, +{func}`~libvt.codec.explain` disassembles `ESC % G` and `ESC % @`, and +{meth}`Terminal.feed_str ` raises +{exc}`ValueError` when the wire encoding is `"latin-1"`. + ## libvt 0.0.1a2 (2026-11-28) `libvt` 0.0.1a2 splits {class}`~libvt.config.Profile` into capability groups diff --git a/docs/api/config.md b/docs/api/config.md index ed9ed33..503462d 100644 --- a/docs/api/config.md +++ b/docs/api/config.md @@ -14,10 +14,10 @@ .. py:type:: Charset :module: libvt.config - :canonical: typing.Literal['B', '0', 'A'] + :canonical: typing.Literal['B', '0', 'A', 'U'] Supported ``G0``–``G3`` character-set designators (US-ASCII, DEC Special, - UK). + UK, IBM PC / CP437). .. py:type:: SixelErasePolicy :module: libvt.config diff --git a/src/libvt/codec.py b/src/libvt/codec.py index 83ae4da..9391b02 100644 --- a/src/libvt/codec.py +++ b/src/libvt/codec.py @@ -196,6 +196,9 @@ def explain(data: collections.abc.Buffer | str) -> tuple[ExplainedSpan, ...]: if inter in ("(", ")", "*", "+"): slot = {"(": "G0", ")": "G1", "*": "G2", "+": "G3"}[inter] spans.append(ExplainedSpan("ESC", "SCS", f"{slot} -> {fin!r}")) + elif inter == "%" and fin in ("@", "G"): + target = "UTF-8" if fin == "G" else "legacy" + spans.append(ExplainedSpan("ESC", "DOCS", f"encoding -> {target}")) else: spans.append(ExplainedSpan("ESC", f"ESC {inter}{fin}", f"{inter}{fin}")) elif isinstance(act, CsiDispatch): diff --git a/src/libvt/config.py b/src/libvt/config.py index 2fc3a1e..50c5603 100644 --- a/src/libvt/config.py +++ b/src/libvt/config.py @@ -9,13 +9,22 @@ #: East Asian Ambiguous (``EA=A``) cell width setting (``1`` Western, ``2`` CJK). type AmbiguousWidth = t.Literal[1, 2] -#: Supported ``G0``..``G3`` character-set designators (US-ASCII, DEC Special, UK). -type Charset = t.Literal["B", "0", "A"] +#: Supported ``G0``..``G3`` charsets (US-ASCII, DEC Special, UK, CP437). +type Charset = t.Literal["B", "0", "A", "U"] #: ``SIXEL`` cell-overwrite and rectangular-erase clipping policy. type SixelErasePolicy = t.Literal["cell_mask", "whole_image"] +class DeccolmBehavior(enum.StrEnum): + """How ``DECCOLM`` (``CSI ? 3 h`` / ``CSI ? 3 l``) handles column switching.""" + + IGNORE = "ignore" + CLEAR_ONLY = "clear_only" + GATED_BY_MODE_40 = "gated_by_mode_40" + ALWAYS = "always" + + class ColorScheme(enum.IntEnum): """``CSI ? 997 ; Ps n`` color-scheme values (``DEC ?2031`` / ``DSR ?996n``).""" @@ -231,6 +240,17 @@ class ScreenBehavior: sixel_erase_policy : SixelErasePolicy How text overwrites and cell erases affect ``SIXEL`` placements (``"cell_mask"`` or ``"whole_image"``). + deccolm : DeccolmBehavior + How ``DECCOLM`` (``CSI ? 3 h`` / ``CSI ? 3 l``) switches between 80 and + 132 columns (default ``DeccolmBehavior.GATED_BY_MODE_40``, requiring + ``CSI ? 40 h`` first; ``DeccolmBehavior.ALWAYS`` honors ``?3`` + unconditionally; ``DeccolmBehavior.CLEAR_ONLY`` clears and homes + without resizing; ``DeccolmBehavior.IGNORE`` ignores ``?3`` and + ``?40``). Resetting ``?3l`` when enabled selects 80 columns rather than + restoring a prior arbitrary width. + allow_encoding_switch : bool + When ``True``, ``ESC % G`` selects UTF-8 wire decoding and ``ESC % @`` + selects legacy Latin-1 wire decoding (default ``False``). """ pending_wrap_phantom_col: bool = False @@ -251,6 +271,8 @@ class ScreenBehavior: cell_width_px: int = 8 cell_height_px: int = 16 sixel_erase_policy: SixelErasePolicy = "cell_mask" + deccolm: DeccolmBehavior = DeccolmBehavior.GATED_BY_MODE_40 + allow_encoding_switch: bool = False @dataclass(frozen=True, slots=True, kw_only=True) @@ -508,6 +530,7 @@ class Limits: "Charset", "ClipboardReadPolicy", "ColorScheme", + "DeccolmBehavior", "Identity", "InputBehavior", "Limits", diff --git a/src/libvt/contrib/tmux/profile.py b/src/libvt/contrib/tmux/profile.py index 9ce5149..fad72a9 100644 --- a/src/libvt/contrib/tmux/profile.py +++ b/src/libvt/contrib/tmux/profile.py @@ -5,6 +5,7 @@ import re from libvt.config import ( + DeccolmBehavior, Identity, InputBehavior, Policy, @@ -163,6 +164,7 @@ def tmux_profile( xtsave_enabled=False, separate_alt_save_cursor=True, ris_alt_screen=RisAltScreenBehavior.KEEP_ACTIVE_SCREEN, + deccolm=DeccolmBehavior.CLEAR_ONLY, allow_esc_k_title=True, sixel_erase_policy="cell_mask" if at_least_3_9 else "whole_image", ), diff --git a/src/libvt/modes.py b/src/libvt/modes.py index cdf2cb2..5308ab9 100644 --- a/src/libvt/modes.py +++ b/src/libvt/modes.py @@ -15,18 +15,21 @@ class Mode(enum.IntEnum): LNM = 20 DECCKM = DEC_PRIVATE_MASK | 1 + DECCOLM = DEC_PRIVATE_MASK | 3 DECSCNM = DEC_PRIVATE_MASK | 5 DECOM = DEC_PRIVATE_MASK | 6 DECAWM = DEC_PRIVATE_MASK | 7 AUTO_REPEAT = DEC_PRIVATE_MASK | 8 MOUSE_X10 = DEC_PRIVATE_MASK | 9 DECTCEM = DEC_PRIVATE_MASK | 25 + ALLOW_80_132 = DEC_PRIVATE_MASK | 40 REVERSE_WRAP = DEC_PRIVATE_MASK | 45 ALT_SCREEN_47 = DEC_PRIVATE_MASK | 47 APPLICATION_KEYPAD = DEC_PRIVATE_MASK | 66 BACKARROW_IS_BS = DEC_PRIVATE_MASK | 67 DECLRMM = DEC_PRIVATE_MASK | 69 DECSDM = DEC_PRIVATE_MASK | 80 + DECNCSM = DEC_PRIVATE_MASK | 95 MOUSE_VT200 = DEC_PRIVATE_MASK | 1000 MOUSE_BUTTON_EVENT = DEC_PRIVATE_MASK | 1002 MOUSE_ANY_EVENT = DEC_PRIVATE_MASK | 1003 diff --git a/src/libvt/parser.py b/src/libvt/parser.py index 812ded1..0a20fda 100644 --- a/src/libvt/parser.py +++ b/src/libvt/parser.py @@ -620,6 +620,7 @@ class Parser: __slots__ = ( "_abort_dispatch_osc", + "_allow_encoding_switch", "_csi_colon_mask", "_csi_cur", "_csi_has_digit", @@ -632,6 +633,7 @@ class Parser: "_dcs_final", "_dcs_params", "_encoding", + "_initial_encoding", "_intermediates", "_latin1", "_limits", @@ -651,6 +653,7 @@ def __init__( self, *, encoding: ParserEncoding = "utf-8", + allow_encoding_switch: bool = False, tmux_passthrough: bool = True, tmux_window_rename: bool = False, abort_dispatch_osc: bool = False, @@ -659,8 +662,10 @@ def __init__( if encoding not in ("utf-8", "latin-1"): msg = f"unsupported parser encoding: {encoding!r}" raise ValueError(msg) + self._initial_encoding: ParserEncoding = encoding self._encoding: ParserEncoding = encoding self._latin1: bool = encoding == "latin-1" + self._allow_encoding_switch: bool = allow_encoding_switch self._tmux_passthrough: bool = tmux_passthrough self._tmux_window_rename: bool = tmux_window_rename self._abort_dispatch_osc: bool = abort_dispatch_osc @@ -691,6 +696,17 @@ def encoding(self) -> ParserEncoding: """Return wire character encoding (``"utf-8"`` or ``"latin-1"``).""" return self._encoding + def set_encoding(self, encoding: ParserEncoding) -> None: + """Switch wire character encoding between ``"utf-8"`` and ``"latin-1"``.""" + if encoding not in ("utf-8", "latin-1"): + msg = f"unsupported parser encoding: {encoding!r}" + raise ValueError(msg) + self._encoding = encoding + self._latin1 = encoding == "latin-1" + if self._latin1: + self._utf8.reset() + self._utf8_pending = False + @property def state(self) -> ParserState: """Return the current :class:`ParserState`.""" @@ -728,6 +744,8 @@ def at_ground_state(self) -> bool: def reset(self) -> None: """Reset parser state and clear buffered partial sequences.""" self._state = ParserState.GROUND + self._encoding = self._initial_encoding + self._latin1 = self._initial_encoding == "latin-1" self._utf8.reset() self._utf8_pending = False self._intermediates.clear() @@ -898,13 +916,13 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None: 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 + latin1 = self._latin1 if state == ParserState.GROUND: if latin1: @@ -1175,7 +1193,14 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None: if len(self._intermediates) < MAX_INTERMEDIATES: self._intermediates.append(b) elif 0x30 <= b <= 0x7E: - sink.on_esc(bytes(self._intermediates), b) + inter_b = bytes(self._intermediates) + if ( + self._allow_encoding_switch + and inter_b == b"%" + and b in (0x40, 0x47) + ): + self.set_encoding("latin-1" if b == 0x40 else "utf-8") + sink.on_esc(inter_b, b) self._intermediates.clear() self._state = ParserState.GROUND else: diff --git a/src/libvt/profiles.py b/src/libvt/profiles.py index 50382e9..8e01572 100644 --- a/src/libvt/profiles.py +++ b/src/libvt/profiles.py @@ -36,6 +36,7 @@ from __future__ import annotations from libvt.config import ( + DeccolmBehavior, Identity, InputBehavior, Profile, @@ -117,6 +118,8 @@ default_g1_charset="0", decstr_enabled=False, declrmm_enabled=False, + deccolm=DeccolmBehavior.IGNORE, + allow_encoding_switch=True, ), input=InputBehavior( kitty_keyboard_enabled=False, diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py index 2046fe2..f1c1c51 100644 --- a/src/libvt/terminal.py +++ b/src/libvt/terminal.py @@ -7,6 +7,7 @@ import collections import collections.abc import dataclasses +import encodings.cp437 import enum import html import itertools @@ -50,6 +51,7 @@ Charset, ClipboardReadPolicy, ColorScheme, + DeccolmBehavior, Limits, Policy, Profile, @@ -173,6 +175,10 @@ ) _UK_CHARSET = str.maketrans({"#": "£"}) +# IBM PC / CP437 ('U') graphic glyphs in GR 0xA0..0xFF (console_codes(4) / CP437). +_CP437_HIGH_CHARSET = str.maketrans( + {chr(i): encodings.cp437.decoding_table[i] for i in range(0xA0, 0x100)}, +) _SAFE_URI_PREFIXES = ("https://", "http://", "mailto:") _PRINT_ASCII_RE = re.compile(rb"[\x20-\x7e]+") @@ -997,6 +1003,11 @@ def format_snapshot(self, snapshot: Snapshot) -> str: def _render_vt(self, snapshot: Snapshot) -> str: out: list[str] = [] export_modes = snapshot.modes - TRANSIENT_SNAPSHOT_MODES + if Mode.DECCOLM in export_modes: + if Mode.ALLOW_80_132 in export_modes: + out.append("\x1b[?40h\x1b[?3h") + else: + out.append("\x1b[?40h\x1b[?3h\x1b[?40l") if not snapshot.active_is_alt: export_modes = export_modes - ALT_SCREEN_MODES else: @@ -1109,12 +1120,13 @@ def _render_vt(self, snapshot: Snapshot) -> str: if raw & DEC_PRIVATE_MASK: code = raw & ~DEC_PRIVATE_MASK if mode not in ( + Mode.DECCOLM, Mode.DECAWM, Mode.AUTO_REPEAT, Mode.DECTCEM, Mode.ALTERNATE_SCROLL, Mode.GRAPHEME_CLUSTERING, - ): + ) and not (mode == Mode.ALLOW_80_132 and Mode.DECCOLM in export_modes): out.append(f"\x1b[?{code}h") else: out.append(f"\x1b[{raw}h") @@ -1779,10 +1791,15 @@ def __init__( self._modes._enabled.add(Mode.LNM) self._parser = Parser( encoding=encoding, + allow_encoding_switch=profile.screen.allow_encoding_switch, tmux_window_rename=profile.screen.allow_esc_k_title, abort_dispatch_osc=policy.abort_dispatch_osc, limits=limits, ) + self._docs_utf8_active: bool = encoding == "utf-8" + self._saved_docs_charset: ( + tuple[tuple[Charset, Charset, Charset, Charset], int, int | None] | None + ) = None self._passthrough_parser: Parser | None = None self._sink = _TerminalSink(self) self._sgr_memo: dict[tuple[Style, CsiParams], Style] = {} @@ -1895,6 +1912,11 @@ def parser_state(self) -> ParserState: """Return current :class:`~libvt.parser.ParserState`.""" return self._parser.state + @property + def encoding(self) -> ParserEncoding: + """Return active wire character encoding (``"utf-8"`` or ``"latin-1"``).""" + return self._parser.encoding + @property def at_ground_state(self) -> bool: r"""Return ``True`` when the parser is in ``GROUND`` with no pending UTF-8. @@ -2883,6 +2905,7 @@ def reset(self, *, soft: bool = False) -> None: self._single_shift = None was_sync = self.synchronized if soft: + self._saved_docs_charset = None for mode_off in ( Mode.IRM, Mode.DECOM, @@ -2921,6 +2944,7 @@ def reset(self, *, soft: bool = False) -> None: else: self._saved_primary = _SavedCursor(g_sets=def_g) else: + was_deccolm = self._modes.is_set(Mode.DECCOLM) keep_alt = ( self._screens.active_is_alt and self._profile.screen.ris_alt_screen @@ -2941,6 +2965,8 @@ def reset(self, *, soft: bool = False) -> None: self._held_sync_token = None self._epoch += 1 self._parser.reset() + self._docs_utf8_active = self._encoding == "utf-8" + self._saved_docs_charset = None self._passthrough_parser = None if keep_alt: self._screens.alternate.reset() @@ -2961,6 +2987,17 @@ def reset(self, *, soft: bool = False) -> None: self._prompt_zones.clear() self._last_prompt_osc_code = 0 self._last_prompt_zone = None + if ( + was_deccolm + and self._profile.screen.deccolm + in (DeccolmBehavior.GATED_BY_MODE_40, DeccolmBehavior.ALWAYS) + and self.cols != 80 + ): + self._screens._resize_with_pins( + rows=self.rows, + cols=80, + reflow=False, + ) self._title = "" self._icon_title = "" self._window_name = "" @@ -3050,6 +3087,12 @@ def _intercept_mode_set(self, mode: Mode, enabled: bool) -> bool: return True if mode == Mode.DECSC_1048 and self._profile.screen.separate_alt_save_cursor: return True + if ( + mode in (Mode.DECCOLM, Mode.ALLOW_80_132, Mode.DECNCSM) + and enabled + and not self._is_private_mode_supported(mode) + ): + return True if ( mode == Mode.MOUSE_SGR_PIXELS and enabled @@ -3072,7 +3115,39 @@ def _before_mutate(self) -> None: self._invalidate_cache() def feed_str(self, text: str, /) -> None: - """Encode *text* as UTF-8 and feed into the terminal.""" + """Encode *text* as UTF-8 and feed into the terminal. + + Raises + ------ + ValueError + When the parser wire encoding is ``"latin-1"`` (either on entry or + after an in-stream ``ESC % @`` switch with trailing characters). + """ + if self._parser.encoding != "utf-8": + msg = ( + "feed_str() requires 'utf-8' parser encoding; " + "encode bytes explicitly and call feed() in 'latin-1' mode" + ) + raise ValueError(msg) + if not text: + return + if self._profile.screen.allow_encoding_switch and "@" in text: + pos = 0 + n = len(text) + while pos < n: + if self._parser.encoding != "utf-8": + msg = ( + "feed_str() cannot feed text after switching parser " + "encoding to 'latin-1'; call feed() with encoded bytes" + ) + raise ValueError(msg) + at_idx = text.find("@", pos) + if at_idx == -1: + self.feed(text[pos:].encode("utf-8")) + break + self.feed(text[pos : at_idx + 1].encode("utf-8")) + pos = at_idx + 1 + return self.feed(text.encode("utf-8")) def feed(self, data: collections.abc.Buffer, /) -> None: @@ -3128,7 +3203,7 @@ def feed_until( ): body_re = ( _STR_BODY_LATIN1_RE - if self._encoding == "latin-1" + if self._parser.encoding == "latin-1" else _STR_BODY_UTF8_RE ) body_m = body_re.match(mv, idx) @@ -3331,15 +3406,20 @@ def _advance_rows( return orig_row return orig_row - scroll_cnt + def _translate_charset_char(self, ch: str, cs: Charset) -> str: + if cs == "0": + return ch.translate(_DEC_SPECIAL_GRAPHICS) + if cs == "A": + return ch.translate(_UK_CHARSET) + if cs == "U" and self._parser.encoding == "latin-1": + return ch.translate(_CP437_HIGH_CHARSET) + return ch + 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]) - ) + first = self._translate_charset_char(text[0], ch0_cs) if len(text) == 1: return first return first + self._map_charset(text[1:]) @@ -3351,6 +3431,8 @@ def _map_charset(self, text: str) -> str: return text.translate(_DEC_SPECIAL_GRAPHICS) if active_cs == "A": return text.translate(_UK_CHARSET) + if active_cs == "U" and self._parser.encoding == "latin-1": + return text.translate(_CP437_HIGH_CHARSET) return text def _write_slice_run( @@ -4060,10 +4142,43 @@ def _handle_esc(self, intermediates: bytes, final: int) -> None: 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"): + if desig in ("0", "A", "B", "U"): self._g_sets[slot] = desig else: self._g_sets[slot] = "B" + elif intermediates == b"%" and final in (0x40, 0x47): # ISO-2022 DOCS + if self._profile.screen.allow_encoding_switch: + if final == 0x47: # ESC % G -> UTF-8 + if not self._docs_utf8_active: + self._before_mutate() + self._saved_docs_charset = ( + ( + self._g_sets[0], + self._g_sets[1], + self._g_sets[2], + self._g_sets[3], + ), + self._gl, + self._single_shift, + ) + self._g_sets = [ + "B", + self._profile.screen.default_g1_charset, + "B", + "B", + ] + self._gl = 0 + self._single_shift = None + self._docs_utf8_active = True + elif self._docs_utf8_active: # ESC % @ -> legacy 8-bit + self._before_mutate() + if self._saved_docs_charset is not None: + saved_g, saved_gl, saved_ss = self._saved_docs_charset + self._g_sets = list(saved_g) + self._gl = saved_gl + self._single_shift = saved_ss + self._saved_docs_charset = None + self._docs_utf8_active = False elif intermediates == b"#" and final == 0x38: # DECALN self._before_mutate() fill = "E" * scr.cols @@ -4113,6 +4228,12 @@ def _is_private_mode_supported(self, mode: Mode) -> bool: >>> Terminal(profile=tmux_profile())._is_private_mode_supported(Mode.DECLRMM) False """ + deccolm_cfg = self._profile.screen.deccolm + if mode in (Mode.DECCOLM, Mode.ALLOW_80_132, Mode.DECNCSM) and deccolm_cfg in ( + DeccolmBehavior.IGNORE, + DeccolmBehavior.CLEAR_ONLY, + ): + return False if mode == Mode.DECLRMM and not self._profile.screen.declrmm_enabled: return False if mode == Mode.DECSC_1048 and self._profile.screen.separate_alt_save_cursor: @@ -4381,6 +4502,20 @@ def _xtrestore_modes(self, params: CsiParams) -> None: items.append((m, saved_alt)) elif m in self._saved_private_modes: items.append((m, self._saved_private_modes[m])) + items.sort( + key=lambda item: ( + 0 + if item[0] == Mode.DECNCSM + else ( + 1 + if ( + item[0] != Mode.DECCOLM + and not (item[0] == Mode.ALLOW_80_132 and not item[1]) + ) + else (2 if item[0] == Mode.DECCOLM else 3) + ) + ), + ) for m, saved_enabled in items: cur_enabled = ( self._screens.active_is_alt @@ -4395,6 +4530,50 @@ def _xtrestore_modes(self, params: CsiParams) -> None: enabled=saved_enabled, ) + def _apply_deccolm(self, *, enabled: bool) -> None: + deccolm_cfg = self._profile.screen.deccolm + if deccolm_cfg == DeccolmBehavior.IGNORE: + return + if deccolm_cfg == DeccolmBehavior.CLEAR_ONLY: + scr = self._screens.active + top, _, left, _ = self._effective_margins(scr) + decom = self._modes.is_set(Mode.DECOM) + self._set_cursor( + scr, + top if decom else 0, + left if decom else 0, + pending_wrap=False, + ) + self._erase_display(scr, 2, selective=False) + return + if deccolm_cfg == DeccolmBehavior.GATED_BY_MODE_40 and not self._modes.is_set( + Mode.ALLOW_80_132 + ): + return + + self._before_mutate() + self._clear_cluster_anchor() + self._modes.set_mode(Mode.DECCOLM, enabled=enabled) + target_cols = 132 if enabled else 80 + if self.cols != target_cols: + self.resize(rows=self.rows, cols=target_cols, reflow=False) + scr = self._screens.active + scr.scroll_region = ScrollRegion( + top=0, + bottom=scr.rows - 1, + left=0, + right=scr.cols - 1, + ) + if not self._modes.is_set(Mode.DECNCSM): + bce_w, bce_e = self._bce_pair() + for r in range(scr.rows): + scr._rows[r].clear_range(0, scr.cols, bce_w, bce_e) + scr._rows[r].wrapped = False + 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), EraseCause.ED) + self._set_cursor(scr, 0, 0, pending_wrap=False) + def _apply_mode(self, code: int, *, private: bool, enabled: bool) -> None: if not (0 <= code < DEC_PRIVATE_MASK): return @@ -4408,6 +4587,16 @@ def _apply_mode(self, code: int, *, private: bool, enabled: bool) -> None: self._set_synchronized_output(enabled) return + if mode == Mode.DECCOLM: + self._apply_deccolm(enabled=enabled) + return + + if mode in ( + Mode.ALLOW_80_132, + Mode.DECNCSM, + ) and not self._is_private_mode_supported(mode): + return + if mode == Mode.DECLRMM and not self._profile.screen.declrmm_enabled: return @@ -4778,8 +4967,19 @@ def _handle_csi( return private = prefix == ord("?") code = params.raw_or_default(0, 0) - if private and ( - (code == 69 and not self._profile.screen.declrmm_enabled) + if ( + private + and code == 3 + and self._profile.screen.deccolm == DeccolmBehavior.CLEAR_ONLY + ): + pm = int(DecrpmValue.PERMANENTLY_RESET) + elif private and ( + ( + code in (3, 40, 95) + and self._profile.screen.deccolm + in (DeccolmBehavior.IGNORE, DeccolmBehavior.CLEAR_ONLY) + ) + or (code == 69 and not self._profile.screen.declrmm_enabled) or (code == 1048 and self._profile.screen.separate_alt_save_cursor) or ( code == 1016 @@ -6269,7 +6469,8 @@ def _handle_dcs( if self._passthrough_depth == 0: if self._passthrough_parser is None: self._passthrough_parser = Parser( - encoding=self._encoding, + encoding=self._parser.encoding, + allow_encoding_switch=self._profile.screen.allow_encoding_switch, tmux_window_rename=self._profile.screen.allow_esc_k_title, abort_dispatch_osc=self._policy.abort_dispatch_osc, limits=self._limits, @@ -6277,7 +6478,8 @@ def _handle_dcs( inner_parser = self._passthrough_parser else: inner_parser = Parser( - encoding=self._encoding, + encoding=self._parser.encoding, + allow_encoding_switch=self._profile.screen.allow_encoding_switch, tmux_window_rename=self._profile.screen.allow_esc_k_title, abort_dispatch_osc=self._policy.abort_dispatch_osc, limits=self._limits, diff --git a/tests/test_pyte_compat.py b/tests/test_pyte_compat.py new file mode 100644 index 0000000..6c03450 --- /dev/null +++ b/tests/test_pyte_compat.py @@ -0,0 +1,284 @@ +"""Clean-room compatibility tests for terminal modes, charsets, and DOCS.""" + +from __future__ import annotations + +import dataclasses + +import pytest + +from libvt.codec import explain +from libvt.config import DEFAULT_PROFILE, DeccolmBehavior, Profile +from libvt.contrib.tmux import tmux_profile +from libvt.modes import Mode +from libvt.profiles import ( + GHOSTTY_PROFILE, + KITTY_PROFILE, + LINUX_CONSOLE_PROFILE, + XTERM_PROFILE, +) +from libvt.style import AnsiColor +from libvt.terminal import OutputFormat, Terminal + + +def _switchable_profile() -> Profile: + return dataclasses.replace( + XTERM_PROFILE, + screen=dataclasses.replace( + XTERM_PROFILE.screen, + allow_encoding_switch=True, + ), + ) + + +def _always_deccolm_profile() -> Profile: + return dataclasses.replace( + DEFAULT_PROFILE, + screen=dataclasses.replace( + DEFAULT_PROFILE.screen, + deccolm=DeccolmBehavior.ALWAYS, + ), + ) + + +def test_deccolm_gated_by_mode_40_default_matrix() -> None: + """``DEFAULT_PROFILE`` gates ``DECCOLM`` (``?3``) behind mode ``?40``.""" + for prof in (DEFAULT_PROFILE, XTERM_PROFILE, GHOSTTY_PROFILE, KITTY_PROFILE): + assert prof.screen.deccolm == DeccolmBehavior.GATED_BY_MODE_40 + + term = Terminal(rows=5, cols=90) + assert not term.modes.is_set(Mode.ALLOW_80_132) + assert not term.modes.is_set(Mode.DECCOLM) + + term.feed(b"\x1b[2;4r\x1b[3;10HKEEP") + term.feed(b"\x1b[?3h") + assert (term.rows, term.cols) == (5, 90) + assert term[2].text == " KEEP" + assert (term.cursor.row, term.cursor.col) == (2, 13) + assert (term.screen.scroll_region.top, term.screen.scroll_region.bottom) == (1, 3) + assert not term.modes.is_set(Mode.DECCOLM) + + term.feed(b"\x1b[?3l") + assert (term.rows, term.cols) == (5, 90) + assert term[2].text == " KEEP" + assert (term.cursor.row, term.cursor.col) == (2, 13) + + term.feed(b"\x1b[?40h") + assert term.modes.is_set(Mode.ALLOW_80_132) + assert (term.rows, term.cols) == (5, 90) + assert term[2].text == " KEEP" + assert (term.cursor.row, term.cursor.col) == (2, 13) + + term.feed(b"\x1b[?3h") + assert term.modes.is_set(Mode.DECCOLM) + assert (term.rows, term.cols) == (5, 132) + assert term.text == "" + assert (term.cursor.row, term.cursor.col, term.cursor.pending_wrap) == (0, 0, False) + assert ( + term.screen.scroll_region.top, + term.screen.scroll_region.bottom, + term.screen.scroll_region.left, + term.screen.scroll_region.right, + ) == (0, 4, 0, 131) + + term.feed(b"\x1b[2;4r\x1b[4;132HX\x1b[?3l") + assert not term.modes.is_set(Mode.DECCOLM) + assert (term.rows, term.cols) == (5, 80) + assert term.text == "" + assert (term.cursor.row, term.cursor.col, term.cursor.pending_wrap) == (0, 0, False) + assert (term.screen.scroll_region.top, term.screen.scroll_region.bottom) == (0, 4) + + term.feed(b"\x1b[?3hWIDE\x1b[?40l") + assert (term.rows, term.cols) == (5, 132) + assert term[0].text == "WIDE" + term.feed(b"\x1b[?3l") + assert (term.rows, term.cols) == (5, 132) + assert term[0].text == "WIDE" + assert (term.cursor.row, term.cursor.col) == (0, 4) + + +def test_deccolm_always_decncsm_ris_xtsave_and_vt_roundtrip() -> None: + """``ALWAYS``, ``DECNCSM``, ``RIS``, ``XTSAVE``, and VT round-trip.""" + legacy = Terminal(rows=4, cols=100, profile=_always_deccolm_profile()) + legacy.feed(b"HELLO\x1b[?3h") + assert (legacy.cols, legacy.text, legacy.modes.is_set(Mode.DECCOLM)) == ( + 132, + "", + True, + ) + legacy.feed(b"WIDE\x1b[?3l") + assert (legacy.cols, legacy.text, legacy.modes.is_set(Mode.DECCOLM)) == ( + 80, + "", + False, + ) + + ncsm = Terminal(rows=4, cols=80) + ncsm.feed(b"\x1b[?40h\x1b[?95h\x1b[2;3r\x1b[2;5HKEEP\x1b[?3h") + assert ncsm.cols == 132 + assert ncsm[1].text == " KEEP" + assert (ncsm.cursor.row, ncsm.cursor.col) == (0, 0) + assert (ncsm.screen.scroll_region.top, ncsm.screen.scroll_region.bottom) == (0, 3) + + ncsm.feed(b"\x1bc") + assert ncsm.cols == 80 + assert not ncsm.modes.is_set(Mode.DECCOLM) + assert not ncsm.modes.is_set(Mode.ALLOW_80_132) + + custom_w = Terminal(rows=4, cols=94) + custom_w.feed(b"abc\x1bc") + assert custom_w.cols == 94 + + xts = Terminal(rows=3, cols=80) + xts.feed(b"\x1b[?40h\x1b[?95h\x1b[?3hSAVED\x1b[?s\x1b[?3;40l") + assert xts.cols == 80 + assert not xts.modes.is_set(Mode.ALLOW_80_132) + xts.feed(b"NARROW\x1b[?r") + assert xts.cols == 132 + assert xts.modes.is_set(Mode.DECCOLM) + assert xts.modes.is_set(Mode.ALLOW_80_132) + assert xts[0].text == "NARROW" + + for keep_40 in (True, False): + src = Terminal(rows=3, cols=80) + src.feed(b"\x1b[?40h\x1b[?3h\x1b[1;125HEDGE132!") + if not keep_40: + src.feed(b"\x1b[?40l") + vt_payload = src.snapshot().format(OutputFormat.VT) + dst = Terminal(rows=3, cols=80) + dst.feed_str(vt_payload) + assert dst.cols == 132 + assert dst[0].text.endswith("EDGE132!") + assert dst.modes.is_set(Mode.DECCOLM) is True + assert dst.modes.is_set(Mode.ALLOW_80_132) is keep_40 + + +def test_deccolm_tmux_observer_and_linux_console_profiles() -> None: + """``tmux_profile`` keeps size fixed; ``LINUX_CONSOLE_PROFILE`` ignores ``?3``.""" + tm = Terminal(rows=4, cols=96, profile=tmux_profile("3.8a")) + assert tm.profile.screen.deccolm == DeccolmBehavior.CLEAR_ONLY + tm.feed(b"\x1b[2;4r\x1b[?6h\x1b[2;3HPANE\x1b[?40h\x1b[?3h") + assert (tm.rows, tm.cols) == (4, 96) + assert tm.text == "" + assert (tm.cursor.row, tm.cursor.col) == (1, 0) + assert not tm.modes.is_set(Mode.DECCOLM) + assert not tm.modes.is_set(Mode.ALLOW_80_132) + tm.feed(b"\x1b[?3$p\x1b[?40$p") + assert tm.drain_replies() == b"\x1b[?3;4$y\x1b[?40;0$y" + + lc = Terminal(rows=4, cols=88, profile=LINUX_CONSOLE_PROFILE) + assert lc.profile.screen.deccolm == DeccolmBehavior.IGNORE + lc.feed(b"\x1b[2;5HSTAY\x1b[?40h\x1b[?3h\x1b[?3$p") + assert (lc.rows, lc.cols) == (4, 88) + assert lc[1].text == " STAY" + assert (lc.cursor.row, lc.cursor.col) == (1, 8) + assert lc.drain_replies() == b"\x1b[?3;0$y" + + +def test_legacy_charsets_cp437_u_shifts_save_restore_and_vax42_omission() -> None: + """``U`` maps CP437 GR bytes in Latin-1; ``V`` (pyte VAX42) falls back to ``B``.""" + term = Terminal(rows=4, cols=20, encoding="latin-1") + term.feed(b"\x1b(UASCII:\xda\xc4\xbf\xdb\xe0\xfb") + assert term[0].text == "ASCII:┌─┐█\u03b1√" + + term.feed(b"\r\n\x9b31m\xb3\x9b0m") + assert term[1].text == "│" + assert term[1, 0].style.fg == AnsiColor.RED + + shifts = Terminal(rows=3, cols=20, encoding="latin-1") + shifts.feed(b"\x1b)0\x1b*A\x1b+U\x0elq\x1b7\x1bn#\x1bO\xfb\x0f#\x1b8\x1b[6Gk\x0f") + assert shifts[0].text == "┌─£√#┐" + + utf8_term = Terminal(rows=2, cols=20) + utf8_term.feed("café £10".encode() + b"\x1b(U " + "café".encode()) + assert utf8_term[0].text == "café £10 café" + + vax_fallback = Terminal(rows=2, cols=20) + vax_fallback.feed(b"\x1b(0lqk\x1b(Vlqk#") + assert vax_fallback[0].text == "┌─┐lqk#" + + +def test_encoding_switches_docs_utf8_c1_isolation_and_chunking() -> None: + """``ESC % G`` / ``ESC % @`` respect profile opt-in, ADR 0005, and chunking.""" + assert DEFAULT_PROFILE.screen.allow_encoding_switch is False + assert XTERM_PROFILE.screen.allow_encoding_switch is False + assert GHOSTTY_PROFILE.screen.allow_encoding_switch is False + assert KITTY_PROFILE.screen.allow_encoding_switch is False + assert tmux_profile("3.8a").screen.allow_encoding_switch is False + assert LINUX_CONSOLE_PROFILE.screen.allow_encoding_switch is True + + dis = explain(b"\x1b%@\x1b%G") + assert [op.summary for op in dis] == [ + "encoding -> legacy", + "encoding -> UTF-8", + ] + + for locked_prof in (DEFAULT_PROFILE, XTERM_PROFILE, tmux_profile("3.8a")): + locked = Terminal(rows=2, cols=20, profile=locked_prof, record_events=True) + locked.feed(b"\x1b%@caf\xc3\xa9") + assert locked.encoding == "utf-8" + assert locked[0].text == "café" + assert locked.drain_events() == () + + stream = ( + b"\xe2\x80\x9cHi\xe2\x80\x9d" + b"\xc2\x9b31m!" + b"\r\n\xc3\x1b%@\xa9" + b"\x1b(U\xda\x1b%Gcaf\xc3\xa9\x1b%@\xbf\x1b%G" + ) + whole = Terminal(rows=4, cols=30, profile=_switchable_profile()) + whole.feed(stream) + assert whole.encoding == "utf-8" + assert whole[0].text == "“Hi”31m!" + assert whole[0, 4].style.fg is None + assert whole[1].text == "\ufffd©┌café┐" + + for step in (1, 2, 3, 5, 7): + chunked = Terminal(rows=4, cols=30, profile=_switchable_profile()) + for off in range(0, len(stream), step): + chunked.feed(stream[off : off + step]) + assert chunked.encoding == whole.encoding + assert chunked.lines == whole.lines + assert chunked.cursor == whole.cursor + + sw = Terminal(rows=2, cols=16, profile=LINUX_CONSOLE_PROFILE) + sw.feed(b"\x1b%@\x1b[!p") + assert sw.encoding == "latin-1" + sw.feed(b"\x1bc") + assert sw.encoding == "utf-8" + + +def test_feed_str_explicit_in_legacy_encoding_state() -> None: + """``feed_str()`` rejects ``latin-1`` wire state before text can corrupt.""" + lat = Terminal(rows=2, cols=16, encoding="latin-1") + with pytest.raises(ValueError, match="feed_str"): + lat.feed_str("café") + assert lat.text == "" + + sw = Terminal(rows=2, cols=20, profile=LINUX_CONSOLE_PROFILE) + sw.feed(b"\x1b%@") + assert sw.encoding == "latin-1" + with pytest.raises(ValueError, match="feed_str"): + sw.feed_str("café") + assert sw.text == "" + + sw.feed(b"\xe9\x1b%G") + assert sw.encoding == "utf-8" + sw.feed_str("ok") + assert sw[0].text == "éok" + + mid = Terminal(rows=2, cols=20, profile=LINUX_CONSOLE_PROFILE) + with pytest.raises(ValueError, match="latin-1"): + mid.feed_str("AB\x1b%@café") + assert mid.encoding == "latin-1" + assert mid[0].text == "AB" + + clean_end = Terminal(rows=2, cols=20, profile=LINUX_CONSOLE_PROFILE) + clean_end.feed_str("user@host\x1b%@") + assert clean_end.encoding == "latin-1" + assert clean_end[0].text == "user@host" + + split_sw = Terminal(rows=2, cols=20, profile=LINUX_CONSOLE_PROFILE) + split_sw.feed_str("HI\x1b%") + with pytest.raises(ValueError, match="latin-1"): + split_sw.feed_str("@café") + assert split_sw[0].text == "HI"