Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,34 @@
_Notes on the upcoming release will go here._
<!-- END PLACEHOLDER - ADD NEW CHANGELOG ENTRIES BELOW THIS LINE -->

### 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 <libvt.config.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 <libvt.config.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 <libvt.terminal.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
Expand Down
4 changes: 2 additions & 2 deletions docs/api/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions src/libvt/codec.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
27 changes: 25 additions & 2 deletions src/libvt/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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``)."""

Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -508,6 +530,7 @@ class Limits:
"Charset",
"ClipboardReadPolicy",
"ColorScheme",
"DeccolmBehavior",
"Identity",
"InputBehavior",
"Limits",
Expand Down
2 changes: 2 additions & 0 deletions src/libvt/contrib/tmux/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import re

from libvt.config import (
DeccolmBehavior,
Identity,
InputBehavior,
Policy,
Expand Down Expand Up @@ -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",
),
Expand Down
3 changes: 3 additions & 0 deletions src/libvt/modes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 27 additions & 2 deletions src/libvt/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -620,6 +620,7 @@ class Parser:

__slots__ = (
"_abort_dispatch_osc",
"_allow_encoding_switch",
"_csi_colon_mask",
"_csi_cur",
"_csi_has_digit",
Expand All @@ -632,6 +633,7 @@ class Parser:
"_dcs_final",
"_dcs_params",
"_encoding",
"_initial_encoding",
"_intermediates",
"_latin1",
"_limits",
Expand All @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -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`."""
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
3 changes: 3 additions & 0 deletions src/libvt/profiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
from __future__ import annotations

from libvt.config import (
DeccolmBehavior,
Identity,
InputBehavior,
Profile,
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading