Skip to content

Commit 3910dbe

Browse files
authored
tmux(fix[capture]): Flag uncertain emoji widths (#174)
why: Older tmux can shift a cell next to an emoji selector. what: - Use the selected server version when assessing capture fidelity. - Preserve raw capture cells and report uncertain grapheme widths. - Exercise pre-3.5 emoji and ordinary-width controls. Fixes #120
2 parents 81c4f7a + a973711 commit 3910dbe

5 files changed

Lines changed: 110 additions & 4 deletions

File tree

‎CHANGES‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,14 @@ still takes precedence.
8484
{meth}`~libvt.contrib.tmux.control.TmuxPaneSync.begin_attach` reports the
8585
pause requirement before sending a command to a server older than 3.2.
8686

87+
#### Identify uncertain emoji columns in tmux captures (#174)
88+
89+
When an emoji presentation selector widens captured text on an
90+
unknown tmux release or one before 3.5,
91+
{attr}`~libvt.contrib.tmux.capture.CaptureCompleteness.exact_cells`
92+
is false and `unexposed_fields` lists `grapheme_widths`. Pass
93+
`tmux_version=` when decoding raw output to identify the server.
94+
8795
### Documentation
8896

8997
#### Assert effective colors alongside screen goldens (#190)

‎MIGRATION‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,12 @@ supplied to the capture command. Earlier versions emit no reply. To
3939
select a different identity, pass `profile=` to the command's `parse()`
4040
method. For tmux 3.1c, use a one-shot pane capture.
4141

42+
For raw {func}`~libvt.contrib.tmux.capture.decode_tmux_capture` input,
43+
pass the version of the server that emitted the bytes. A widening emoji
44+
presentation selector from an unknown or pre-3.5 release now leaves
45+
`exact_cells` false. Read an attached client's screen when the column of
46+
the next character matters.
47+
4248
## libvt 0.0.1a2 (2026-11-28)
4349

4450
### Curated PEP 562 `libvt` root exports (#43)

‎docs/topics/sync-and-asyncio.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,13 @@ A server without `capture-pane -N` can still supply plain text through
146146
`capture-pane -p`. Pane metadata also varies by release. For example,
147147
tmux 3.7 exposes the bracketed-paste state.
148148

149+
On tmux 3.4, a pane that prints `✈️Z` places `Z` in column 2
150+
(zero-based). Its capture can insert a space and place `Z` in column 3.
151+
For this input `result.completeness.unexposed_fields` includes
152+
`grapheme_widths`. A plain two-cell glyph such as `界` keeps its columns.
153+
Use an attached-client screen to assert positions in a pane with
154+
uncertain widths.
155+
149156
## Concurrency and thread ownership
150157

151158
Every method call and attribute read on a {class}`~libvt.terminal.Terminal`

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

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from dataclasses import dataclass, field
1111

1212
from libvt._grid import WidthRole, _Row, raw_width_bits
13+
from libvt._ucd import display_width
1314
from libvt.config import (
1415
DEFAULT_LIMITS,
1516
Limits,
@@ -27,7 +28,7 @@
2728
from libvt.parser import CsiParams, Parser, _parse_ascii_int, _parse_ascii_uint
2829
from libvt.screen import CursorShape, Screen, ScrollRegion
2930
from libvt.style import DEFAULT_STYLE
30-
from libvt.terminal import Snapshot, Terminal
31+
from libvt.terminal import Snapshot, Terminal, strip
3132

3233
#: Accepted input payload shapes for ``tmux capture-pane`` decoders.
3334
type CaptureInput = str | bytes | bytearray | collections.abc.Sequence[str]
@@ -456,8 +457,9 @@ class CaptureCompleteness:
456457
Attributes
457458
----------
458459
exact_cells : bool
459-
``True`` when cell glyphs, styles, and tab expansions were decoded from
460-
``-e -p -N`` (or ``-e -p -N -T``) output.
460+
Whether the capture can certify cell positions and styles. A widening
461+
emoji presentation selector from a server older than 3.5 leaves its
462+
native columns unverified.
461463
exact_wraps : bool
462464
``True`` when soft-wrap flags came from ``-F`` or an exact ``-J``
463465
companion capture.
@@ -737,6 +739,19 @@ def _row_trimmed_text_and_cols(row: _Row) -> tuple[str, int]:
737739
return row.slice_text(0, t_end), t_end
738740

739741

742+
def _has_widening_selector(lines: list[str]) -> bool:
743+
"""Test captured text using the producer's tmux width rules."""
744+
for line in lines:
745+
if "\ufe0f" in line:
746+
text = strip(line.encode("utf-8", errors="surrogateescape"))
747+
without_selector = text.replace("\ufe0f", "")
748+
if display_width(text, profile=TMUX_PROFILE) > display_width(
749+
without_selector, profile=TMUX_PROFILE
750+
):
751+
return True
752+
return False
753+
754+
740755
def _infer_wraps_from_joined(
741756
plain_rows: list[str],
742757
joined_raw: CaptureInput,
@@ -1156,6 +1171,7 @@ def decode_tmux_capture(
11561171
saved_primary_trim_trailing: bool | None = None,
11571172
saved_primary_joined_capture: CaptureInput | None = None,
11581173
post_metadata: TmuxPaneMetadata | str | None = None,
1174+
tmux_version: tuple[int, int] | str | None = None,
11591175
profile: Profile = TMUX_PROFILE,
11601176
policy: Policy = TMUX_CAPTURE_POLICY,
11611177
limits: Limits = DEFAULT_LIMITS,
@@ -1217,6 +1233,10 @@ def decode_tmux_capture(
12171233
post_metadata : TmuxPaneMetadata | str | None
12181234
Optional second metadata sample taken immediately after ``capture-pane``
12191235
to verify ``pane_output_generation`` stability.
1236+
tmux_version : tuple[int, int] | str | None
1237+
Release that produced the capture. Before tmux 3.5, a widening
1238+
emoji selector can shift the next captured cell. An unknown release
1239+
receives the same qualification in the completeness report.
12201240
profile : Profile
12211241
Compatibility profile for the reconstructed terminal.
12221242
policy : Policy
@@ -1252,6 +1272,7 @@ def decode_tmux_capture(
12521272
r0[0..5]: fg=green
12531273
"""
12541274
eff_hist_req = _validate_history_lines(history_lines)
1275+
legacy_width = tmux_version is None or parse_tmux_version(tmux_version) < (3, 5)
12551276
fallback_sb = 2_000 if scrollback is None else scrollback
12561277
if isinstance(metadata, str):
12571278
meta = TmuxPaneMetadata.from_format_line(metadata)
@@ -1293,6 +1314,7 @@ def decode_tmux_capture(
12931314
term._tabstops_from_list(term.screens.alternate, tabstops)
12941315

12951316
raw_lines = _split_capture_lines(captured)
1317+
unverified_width = legacy_width and _has_widening_selector(raw_lines)
12961318
stripped_trailing = 0
12971319
expected_hist = (
12981320
meta.history_size
@@ -1330,6 +1352,8 @@ def decode_tmux_capture(
13301352

13311353
if saved_primary_capture is not None:
13321354
prim_lines = _split_capture_lines(saved_primary_capture)
1355+
if legacy_width and not unverified_width:
1356+
unverified_width = _has_widening_selector(prim_lines)
13331357
prim_flagged = (
13341358
flagged if saved_primary_flagged is None else saved_primary_flagged
13351359
)
@@ -1546,6 +1570,8 @@ def decode_tmux_capture(
15461570
unexposed.discard("cursor_shape")
15471571
if uncalibrated_tabs:
15481572
unexposed.add("pane_tabs")
1573+
if unverified_width:
1574+
unexposed.add("grapheme_widths")
15491575
if not exact_wraps:
15501576
unexposed.add("soft_wraps")
15511577
if meta.alternate_on and saved_primary_capture is None:
@@ -1564,7 +1590,7 @@ def decode_tmux_capture(
15641590
== (meta.cols, meta.rows, meta.alternate_on, meta.history_size)
15651591
)
15661592
completeness = CaptureCompleteness(
1567-
exact_cells=not uncalibrated_tabs,
1593+
exact_cells=not (uncalibrated_tabs or unverified_width),
15681594
exact_wraps=exact_wraps,
15691595
exact_generation_bracket=exact_gen,
15701596
unexposed_fields=frozenset(unexposed),
@@ -1760,6 +1786,7 @@ def parse(
17601786
saved_primary_flagged=self.flagged,
17611787
saved_primary_trim_trailing=self.trim_trailing,
17621788
saved_primary_joined_capture=saved_joined_lines,
1789+
tmux_version=self.tmux_version,
17631790
profile=tmux_profile(self.tmux_version) if profile is None else profile,
17641791
policy=policy,
17651792
limits=limits,

‎tests/test_tmux.py‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import pytest
1010

1111
import libvt
12+
from libvt.config import Profile, UnicodeBehavior
1213
from libvt.contrib.tmux import (
1314
TMUX_METADATA_FORMAT,
1415
TmuxLineFlags,
@@ -1186,3 +1187,60 @@ def test_older_tmux_attach_identifies_one_shot_capture() -> None:
11861187
.begin_attach()
11871188
.startswith("refresh-client -A ")
11881189
)
1190+
1191+
1192+
@pytest.mark.parametrize(
1193+
("version", "text", "z_col", "exact"),
1194+
[
1195+
("3.1c", "✈️Z", 2, False),
1196+
("3.4", "✈️ Z", 3, False),
1197+
("3.4", "界Z", 2, True),
1198+
("3.4", "界️Z", 2, True),
1199+
("3.5", "✈️Z", 2, True),
1200+
("3.8", "✈️ Z", 3, True),
1201+
],
1202+
)
1203+
def test_capture_reports_unverified_presentation_widths(
1204+
version: str, text: str, z_col: int, exact: bool
1205+
) -> None:
1206+
"""Preserve captured cells and qualify columns the older server can lose."""
1207+
cmd = build_tmux_capture_command(
1208+
"%0", tmux_version=version, nonce="WIDTH_120", include_saved_primary=False
1209+
)
1210+
meta = f"WIDTH_120:PRE:8\t1\t{z_col + 1}\t0"
1211+
body = "\x1b[32m" + text
1212+
raw = [meta, "WIDTH_120:CAPTURE", ("- " if cmd.flagged else "") + body]
1213+
if cmd.has_joined:
1214+
raw.extend(["WIDTH_120:JOINED", body])
1215+
result = cmd.parse([*raw, meta.replace(":PRE:", ":POST:")])
1216+
assert result.completeness.exact_cells is exact
1217+
assert ("grapheme_widths" in result.completeness.unexposed_fields) is not exact
1218+
snap = result.snapshot
1219+
assert snap[0, z_col].text == "Z"
1220+
assert snap[0, z_col].style.fg == AnsiColor.GREEN
1221+
assert (snap.cursor.row, snap.cursor.col, snap[0].wrapped) == (0, z_col + 1, False)
1222+
result.terminal.feed(b"\rX")
1223+
assert snap[0, 0].text != "X"
1224+
1225+
1226+
def test_capture_width_checks_only_printed_text_in_both_screens() -> None:
1227+
"""Inspect the saved primary, skip OSC payloads and retain one-column evidence."""
1228+
meta = TmuxPaneMetadata(cols=4, rows=1, alternate_on=True)
1229+
link = "\x1b]8;;https://example.org/✈️\x1b\\Z\x1b]8;;\x1b\\"
1230+
exact = decode_tmux_capture([link], metadata=meta, tmux_version="3.4")
1231+
assert exact.completeness.exact_cells
1232+
for version, trusted in [(None, False), ("3.4", False), ("3.5", True)]:
1233+
result = decode_tmux_capture(
1234+
[link], metadata=meta, saved_primary_capture=["✈️Z"], tmux_version=version
1235+
)
1236+
assert result.completeness.exact_cells is trusted
1237+
assert result.snapshot.lines == ("Z",)
1238+
narrow = decode_tmux_capture(["✈️"], rows=1, cols=1, tmux_version="3.4")
1239+
assert not narrow.completeness.exact_cells
1240+
cjk = Profile(unicode=UnicodeBehavior(ambiguous_width=2))
1241+
phone = decode_tmux_capture(
1242+
["☎️ Z"], rows=1, cols=5, tmux_version="3.4", profile=cjk
1243+
)
1244+
assert phone.snapshot[0, 3].text == "Z"
1245+
assert "grapheme_widths" in phone.completeness.unexposed_fields
1246+
assert phone.terminal.profile is cjk

0 commit comments

Comments
 (0)