Skip to content

Commit 0eff690

Browse files
authored
terminal(feat[compat]): Add DECCOLM, CP437, DOCS (#61)
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
2 parents b47f4e9 + 6835711 commit 0eff690

10 files changed

Lines changed: 592 additions & 19 deletions

File tree

‎CHANGES‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,34 @@
66
_Notes on the upcoming release will go here._
77
<!-- END PLACEHOLDER - ADD NEW CHANGELOG ENTRIES BELOW THIS LINE -->
88

9+
### What's new
10+
11+
#### Mode-gated 80/132-column switching, `CP437` charset, and wire-encoding transitions (#58)
12+
13+
{class}`~libvt.modes.Mode` adds {attr}`~libvt.modes.Mode.DECCOLM` (`?3`),
14+
{attr}`~libvt.modes.Mode.ALLOW_80_132` (`?40`), and
15+
{attr}`~libvt.modes.Mode.DECNCSM` (`?95`), governed by
16+
{attr}`ScreenBehavior.deccolm <libvt.config.ScreenBehavior.deccolm>`
17+
({class}`~libvt.config.DeccolmBehavior`).
18+
{data}`~libvt.config.DEFAULT_PROFILE` uses
19+
{attr}`~libvt.config.DeccolmBehavior.GATED_BY_MODE_40` with `?40` initially
20+
reset (`?3h` selects `132` columns and `?3l` selects `80` columns once `?40h`
21+
is enabled), {func}`~libvt.contrib.tmux.profile.tmux_profile` uses
22+
{attr}`~libvt.config.DeccolmBehavior.CLEAR_ONLY` so `tmux` retains
23+
authoritative pane geometry, and {data}`~libvt.profiles.LINUX_CONSOLE_PROFILE`
24+
uses {attr}`~libvt.config.DeccolmBehavior.IGNORE`.
25+
26+
`G0`–`G3` character-set designations ({type}`~libvt.config.Charset`) add `'U'`
27+
(`IBM PC` / `CP437` `0xA0`–`0xFF` graphic mapping in `"latin-1"` parser mode).
28+
{class}`~libvt.parser.Parser` adds {meth}`~libvt.parser.Parser.set_encoding`
29+
and `allow_encoding_switch`, wired to
30+
{attr}`ScreenBehavior.allow_encoding_switch <libvt.config.ScreenBehavior.allow_encoding_switch>`
31+
(`False` by default; `True` on {data}`~libvt.profiles.LINUX_CONSOLE_PROFILE`)
32+
for ISO-2022 `DOCS` (`ESC % G` / `ESC % @`) transitions,
33+
{func}`~libvt.codec.explain` disassembles `ESC % G` and `ESC % @`, and
34+
{meth}`Terminal.feed_str <libvt.terminal.Terminal.feed_str>` raises
35+
{exc}`ValueError` when the wire encoding is `"latin-1"`.
36+
937
## libvt 0.0.1a2 (2026-11-28)
1038

1139
`libvt` 0.0.1a2 splits {class}`~libvt.config.Profile` into capability groups

‎docs/api/config.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,10 @@
1414
1515
.. py:type:: Charset
1616
:module: libvt.config
17-
:canonical: typing.Literal['B', '0', 'A']
17+
:canonical: typing.Literal['B', '0', 'A', 'U']
1818
1919
Supported ``G0``–``G3`` character-set designators (US-ASCII, DEC Special,
20-
UK).
20+
UK, IBM PC / CP437).
2121
2222
.. py:type:: SixelErasePolicy
2323
:module: libvt.config

‎src/libvt/codec.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,9 @@ def explain(data: collections.abc.Buffer | str) -> tuple[ExplainedSpan, ...]:
196196
if inter in ("(", ")", "*", "+"):
197197
slot = {"(": "G0", ")": "G1", "*": "G2", "+": "G3"}[inter]
198198
spans.append(ExplainedSpan("ESC", "SCS", f"{slot} -> {fin!r}"))
199+
elif inter == "%" and fin in ("@", "G"):
200+
target = "UTF-8" if fin == "G" else "legacy"
201+
spans.append(ExplainedSpan("ESC", "DOCS", f"encoding -> {target}"))
199202
else:
200203
spans.append(ExplainedSpan("ESC", f"ESC {inter}{fin}", f"{inter}{fin}"))
201204
elif isinstance(act, CsiDispatch):

‎src/libvt/config.py‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,22 @@
99
#: East Asian Ambiguous (``EA=A``) cell width setting (``1`` Western, ``2`` CJK).
1010
type AmbiguousWidth = t.Literal[1, 2]
1111

12-
#: Supported ``G0``..``G3`` character-set designators (US-ASCII, DEC Special, UK).
13-
type Charset = t.Literal["B", "0", "A"]
12+
#: Supported ``G0``..``G3`` charsets (US-ASCII, DEC Special, UK, CP437).
13+
type Charset = t.Literal["B", "0", "A", "U"]
1414

1515
#: ``SIXEL`` cell-overwrite and rectangular-erase clipping policy.
1616
type SixelErasePolicy = t.Literal["cell_mask", "whole_image"]
1717

1818

19+
class DeccolmBehavior(enum.StrEnum):
20+
"""How ``DECCOLM`` (``CSI ? 3 h`` / ``CSI ? 3 l``) handles column switching."""
21+
22+
IGNORE = "ignore"
23+
CLEAR_ONLY = "clear_only"
24+
GATED_BY_MODE_40 = "gated_by_mode_40"
25+
ALWAYS = "always"
26+
27+
1928
class ColorScheme(enum.IntEnum):
2029
"""``CSI ? 997 ; Ps n`` color-scheme values (``DEC ?2031`` / ``DSR ?996n``)."""
2130

@@ -231,6 +240,17 @@ class ScreenBehavior:
231240
sixel_erase_policy : SixelErasePolicy
232241
How text overwrites and cell erases affect ``SIXEL`` placements
233242
(``"cell_mask"`` or ``"whole_image"``).
243+
deccolm : DeccolmBehavior
244+
How ``DECCOLM`` (``CSI ? 3 h`` / ``CSI ? 3 l``) switches between 80 and
245+
132 columns (default ``DeccolmBehavior.GATED_BY_MODE_40``, requiring
246+
``CSI ? 40 h`` first; ``DeccolmBehavior.ALWAYS`` honors ``?3``
247+
unconditionally; ``DeccolmBehavior.CLEAR_ONLY`` clears and homes
248+
without resizing; ``DeccolmBehavior.IGNORE`` ignores ``?3`` and
249+
``?40``). Resetting ``?3l`` when enabled selects 80 columns rather than
250+
restoring a prior arbitrary width.
251+
allow_encoding_switch : bool
252+
When ``True``, ``ESC % G`` selects UTF-8 wire decoding and ``ESC % @``
253+
selects legacy Latin-1 wire decoding (default ``False``).
234254
"""
235255

236256
pending_wrap_phantom_col: bool = False
@@ -251,6 +271,8 @@ class ScreenBehavior:
251271
cell_width_px: int = 8
252272
cell_height_px: int = 16
253273
sixel_erase_policy: SixelErasePolicy = "cell_mask"
274+
deccolm: DeccolmBehavior = DeccolmBehavior.GATED_BY_MODE_40
275+
allow_encoding_switch: bool = False
254276

255277

256278
@dataclass(frozen=True, slots=True, kw_only=True)
@@ -508,6 +530,7 @@ class Limits:
508530
"Charset",
509531
"ClipboardReadPolicy",
510532
"ColorScheme",
533+
"DeccolmBehavior",
511534
"Identity",
512535
"InputBehavior",
513536
"Limits",

‎src/libvt/contrib/tmux/profile.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import re
66

77
from libvt.config import (
8+
DeccolmBehavior,
89
Identity,
910
InputBehavior,
1011
Policy,
@@ -163,6 +164,7 @@ def tmux_profile(
163164
xtsave_enabled=False,
164165
separate_alt_save_cursor=True,
165166
ris_alt_screen=RisAltScreenBehavior.KEEP_ACTIVE_SCREEN,
167+
deccolm=DeccolmBehavior.CLEAR_ONLY,
166168
allow_esc_k_title=True,
167169
sixel_erase_policy="cell_mask" if at_least_3_9 else "whole_image",
168170
),

‎src/libvt/modes.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,18 +15,21 @@ class Mode(enum.IntEnum):
1515
LNM = 20
1616

1717
DECCKM = DEC_PRIVATE_MASK | 1
18+
DECCOLM = DEC_PRIVATE_MASK | 3
1819
DECSCNM = DEC_PRIVATE_MASK | 5
1920
DECOM = DEC_PRIVATE_MASK | 6
2021
DECAWM = DEC_PRIVATE_MASK | 7
2122
AUTO_REPEAT = DEC_PRIVATE_MASK | 8
2223
MOUSE_X10 = DEC_PRIVATE_MASK | 9
2324
DECTCEM = DEC_PRIVATE_MASK | 25
25+
ALLOW_80_132 = DEC_PRIVATE_MASK | 40
2426
REVERSE_WRAP = DEC_PRIVATE_MASK | 45
2527
ALT_SCREEN_47 = DEC_PRIVATE_MASK | 47
2628
APPLICATION_KEYPAD = DEC_PRIVATE_MASK | 66
2729
BACKARROW_IS_BS = DEC_PRIVATE_MASK | 67
2830
DECLRMM = DEC_PRIVATE_MASK | 69
2931
DECSDM = DEC_PRIVATE_MASK | 80
32+
DECNCSM = DEC_PRIVATE_MASK | 95
3033
MOUSE_VT200 = DEC_PRIVATE_MASK | 1000
3134
MOUSE_BUTTON_EVENT = DEC_PRIVATE_MASK | 1002
3235
MOUSE_ANY_EVENT = DEC_PRIVATE_MASK | 1003

‎src/libvt/parser.py‎

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -620,6 +620,7 @@ class Parser:
620620

621621
__slots__ = (
622622
"_abort_dispatch_osc",
623+
"_allow_encoding_switch",
623624
"_csi_colon_mask",
624625
"_csi_cur",
625626
"_csi_has_digit",
@@ -632,6 +633,7 @@ class Parser:
632633
"_dcs_final",
633634
"_dcs_params",
634635
"_encoding",
636+
"_initial_encoding",
635637
"_intermediates",
636638
"_latin1",
637639
"_limits",
@@ -651,6 +653,7 @@ def __init__(
651653
self,
652654
*,
653655
encoding: ParserEncoding = "utf-8",
656+
allow_encoding_switch: bool = False,
654657
tmux_passthrough: bool = True,
655658
tmux_window_rename: bool = False,
656659
abort_dispatch_osc: bool = False,
@@ -659,8 +662,10 @@ def __init__(
659662
if encoding not in ("utf-8", "latin-1"):
660663
msg = f"unsupported parser encoding: {encoding!r}"
661664
raise ValueError(msg)
665+
self._initial_encoding: ParserEncoding = encoding
662666
self._encoding: ParserEncoding = encoding
663667
self._latin1: bool = encoding == "latin-1"
668+
self._allow_encoding_switch: bool = allow_encoding_switch
664669
self._tmux_passthrough: bool = tmux_passthrough
665670
self._tmux_window_rename: bool = tmux_window_rename
666671
self._abort_dispatch_osc: bool = abort_dispatch_osc
@@ -691,6 +696,17 @@ def encoding(self) -> ParserEncoding:
691696
"""Return wire character encoding (``"utf-8"`` or ``"latin-1"``)."""
692697
return self._encoding
693698

699+
def set_encoding(self, encoding: ParserEncoding) -> None:
700+
"""Switch wire character encoding between ``"utf-8"`` and ``"latin-1"``."""
701+
if encoding not in ("utf-8", "latin-1"):
702+
msg = f"unsupported parser encoding: {encoding!r}"
703+
raise ValueError(msg)
704+
self._encoding = encoding
705+
self._latin1 = encoding == "latin-1"
706+
if self._latin1:
707+
self._utf8.reset()
708+
self._utf8_pending = False
709+
694710
@property
695711
def state(self) -> ParserState:
696712
"""Return the current :class:`ParserState`."""
@@ -728,6 +744,8 @@ def at_ground_state(self) -> bool:
728744
def reset(self) -> None:
729745
"""Reset parser state and clear buffered partial sequences."""
730746
self._state = ParserState.GROUND
747+
self._encoding = self._initial_encoding
748+
self._latin1 = self._initial_encoding == "latin-1"
731749
self._utf8.reset()
732750
self._utf8_pending = False
733751
self._intermediates.clear()
@@ -898,13 +916,13 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None:
898916
mv = memoryview(data).cast("B")
899917
n = len(mv)
900918
pos = 0
901-
latin1 = self._latin1
902919
max_osc = self._limits.max_osc_bytes
903920
max_dcs = self._limits.max_dcs_bytes
904921
max_apc = self._limits.max_apc_bytes
905922

906923
while pos < n:
907924
state = self._state
925+
latin1 = self._latin1
908926

909927
if state == ParserState.GROUND:
910928
if latin1:
@@ -1175,7 +1193,14 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None:
11751193
if len(self._intermediates) < MAX_INTERMEDIATES:
11761194
self._intermediates.append(b)
11771195
elif 0x30 <= b <= 0x7E:
1178-
sink.on_esc(bytes(self._intermediates), b)
1196+
inter_b = bytes(self._intermediates)
1197+
if (
1198+
self._allow_encoding_switch
1199+
and inter_b == b"%"
1200+
and b in (0x40, 0x47)
1201+
):
1202+
self.set_encoding("latin-1" if b == 0x40 else "utf-8")
1203+
sink.on_esc(inter_b, b)
11791204
self._intermediates.clear()
11801205
self._state = ParserState.GROUND
11811206
else:

‎src/libvt/profiles.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
from __future__ import annotations
3737

3838
from libvt.config import (
39+
DeccolmBehavior,
3940
Identity,
4041
InputBehavior,
4142
Profile,
@@ -117,6 +118,8 @@
117118
default_g1_charset="0",
118119
decstr_enabled=False,
119120
declrmm_enabled=False,
121+
deccolm=DeccolmBehavior.IGNORE,
122+
allow_encoding_switch=True,
120123
),
121124
input=InputBehavior(
122125
kitty_keyboard_enabled=False,

0 commit comments

Comments
 (0)