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
8 changes: 8 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ still takes precedence.
{meth}`~libvt.contrib.tmux.control.TmuxPaneSync.begin_attach` reports the
pause requirement before sending a command to a server older than 3.2.

#### Identify uncertain emoji columns in tmux captures (#174)

When an emoji presentation selector widens captured text on an
unknown tmux release or one before 3.5,
{attr}`~libvt.contrib.tmux.capture.CaptureCompleteness.exact_cells`
is false and `unexposed_fields` lists `grapheme_widths`. Pass
`tmux_version=` when decoding raw output to identify the server.

## libvt 0.0.1a5 (2026-11-30)

`libvt` 0.0.1a5 adds rectangular grid blitting, display-column text writes, and
Expand Down
6 changes: 6 additions & 0 deletions MIGRATION
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ supplied to the capture command. Earlier versions emit no reply. To
select a different identity, pass `profile=` to the command's `parse()`
method. For tmux 3.1c, use a one-shot pane capture.

For raw {func}`~libvt.contrib.tmux.capture.decode_tmux_capture` input,
pass the version of the server that emitted the bytes. A widening emoji
presentation selector from an unknown or pre-3.5 release now leaves
`exact_cells` false. Read an attached client's screen when the column of
the next character matters.

## libvt 0.0.1a2 (2026-11-28)

### Curated PEP 562 `libvt` root exports (#43)
Expand Down
7 changes: 7 additions & 0 deletions docs/topics/sync-and-asyncio.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,13 @@ A server without `capture-pane -N` can still supply plain text through
`capture-pane -p`. Pane metadata also varies by release. For example,
tmux 3.7 exposes the bracketed-paste state.

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

## Concurrency and thread ownership

Every method call and attribute read on a {class}`~libvt.terminal.Terminal`
Expand Down
35 changes: 31 additions & 4 deletions src/libvt/contrib/tmux/capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from dataclasses import dataclass, field

from libvt._grid import WidthRole, _Row, raw_width_bits
from libvt._ucd import display_width
from libvt.config import (
DEFAULT_LIMITS,
Limits,
Expand All @@ -27,7 +28,7 @@
from libvt.parser import CsiParams, Parser, _parse_ascii_int, _parse_ascii_uint
from libvt.screen import CursorShape, Screen, ScrollRegion
from libvt.style import DEFAULT_STYLE
from libvt.terminal import Snapshot, Terminal
from libvt.terminal import Snapshot, Terminal, strip

#: Accepted input payload shapes for ``tmux capture-pane`` decoders.
type CaptureInput = str | bytes | bytearray | collections.abc.Sequence[str]
Expand Down Expand Up @@ -449,8 +450,9 @@ class CaptureCompleteness:
Attributes
----------
exact_cells : bool
``True`` when cell glyphs, styles, and tab expansions were decoded from
``-e -p -N`` (or ``-e -p -N -T``) output.
Whether the capture can certify cell positions and styles. A widening
emoji presentation selector from a server older than 3.5 leaves its
native columns unverified.
exact_wraps : bool
``True`` when soft-wrap flags came from ``-F`` or an exact ``-J``
companion capture.
Expand Down Expand Up @@ -730,6 +732,19 @@ def _row_trimmed_text_and_cols(row: _Row) -> tuple[str, int]:
return row.slice_text(0, t_end), t_end


def _has_widening_selector(lines: list[str]) -> bool:
"""Test captured text using the producer's tmux width rules."""
for line in lines:
if "\ufe0f" in line:
text = strip(line.encode("utf-8", errors="surrogateescape"))
without_selector = text.replace("\ufe0f", "")
if display_width(text, profile=TMUX_PROFILE) > display_width(
without_selector, profile=TMUX_PROFILE
):
return True
return False


def _infer_wraps_from_joined(
plain_rows: list[str],
joined_raw: CaptureInput,
Expand Down Expand Up @@ -1149,6 +1164,7 @@ def decode_tmux_capture(
saved_primary_trim_trailing: bool | None = None,
saved_primary_joined_capture: CaptureInput | None = None,
post_metadata: TmuxPaneMetadata | str | None = None,
tmux_version: tuple[int, int] | str | None = None,
profile: Profile = TMUX_PROFILE,
policy: Policy = TMUX_CAPTURE_POLICY,
limits: Limits = DEFAULT_LIMITS,
Expand Down Expand Up @@ -1210,6 +1226,10 @@ def decode_tmux_capture(
post_metadata : TmuxPaneMetadata | str | None
Optional second metadata sample taken immediately after ``capture-pane``
to verify ``pane_output_generation`` stability.
tmux_version : tuple[int, int] | str | None
Release that produced the capture. Before tmux 3.5, a widening
emoji selector can shift the next captured cell. An unknown release
receives the same qualification in the completeness report.
profile : Profile
Compatibility profile for the reconstructed terminal.
policy : Policy
Expand Down Expand Up @@ -1245,6 +1265,7 @@ def decode_tmux_capture(
r0[0..5]: fg=green
"""
eff_hist_req = _validate_history_lines(history_lines)
legacy_width = tmux_version is None or parse_tmux_version(tmux_version) < (3, 5)
fallback_sb = 2_000 if scrollback is None else scrollback
if isinstance(metadata, str):
meta = TmuxPaneMetadata.from_format_line(metadata)
Expand Down Expand Up @@ -1286,6 +1307,7 @@ def decode_tmux_capture(
term._tabstops_from_list(term.screens.alternate, tabstops)

raw_lines = _split_capture_lines(captured)
unverified_width = legacy_width and _has_widening_selector(raw_lines)
stripped_trailing = 0
expected_hist = (
meta.history_size
Expand Down Expand Up @@ -1323,6 +1345,8 @@ def decode_tmux_capture(

if saved_primary_capture is not None:
prim_lines = _split_capture_lines(saved_primary_capture)
if legacy_width and not unverified_width:
unverified_width = _has_widening_selector(prim_lines)
prim_flagged = (
flagged if saved_primary_flagged is None else saved_primary_flagged
)
Expand Down Expand Up @@ -1539,6 +1563,8 @@ def decode_tmux_capture(
unexposed.discard("cursor_shape")
if uncalibrated_tabs:
unexposed.add("pane_tabs")
if unverified_width:
unexposed.add("grapheme_widths")
if not exact_wraps:
unexposed.add("soft_wraps")
if meta.alternate_on and saved_primary_capture is None:
Expand All @@ -1557,7 +1583,7 @@ def decode_tmux_capture(
== (meta.cols, meta.rows, meta.alternate_on, meta.history_size)
)
completeness = CaptureCompleteness(
exact_cells=not uncalibrated_tabs,
exact_cells=not (uncalibrated_tabs or unverified_width),
exact_wraps=exact_wraps,
exact_generation_bracket=exact_gen,
unexposed_fields=frozenset(unexposed),
Expand Down Expand Up @@ -1753,6 +1779,7 @@ def parse(
saved_primary_flagged=self.flagged,
saved_primary_trim_trailing=self.trim_trailing,
saved_primary_joined_capture=saved_joined_lines,
tmux_version=self.tmux_version,
profile=tmux_profile(self.tmux_version) if profile is None else profile,
policy=policy,
limits=limits,
Expand Down
58 changes: 58 additions & 0 deletions tests/test_tmux.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import pytest

import libvt
from libvt.config import Profile, UnicodeBehavior
from libvt.contrib.tmux import (
TMUX_METADATA_FORMAT,
TmuxLineFlags,
Expand Down Expand Up @@ -1154,3 +1155,60 @@ def test_older_tmux_attach_identifies_one_shot_capture() -> None:
.begin_attach()
.startswith("refresh-client -A ")
)


@pytest.mark.parametrize(
("version", "text", "z_col", "exact"),
[
("3.1c", "✈️Z", 2, False),
("3.4", "✈️ Z", 3, False),
("3.4", "界Z", 2, True),
("3.4", "界️Z", 2, True),
("3.5", "✈️Z", 2, True),
("3.8", "✈️ Z", 3, True),
],
)
def test_capture_reports_unverified_presentation_widths(
version: str, text: str, z_col: int, exact: bool
) -> None:
"""Preserve captured cells and qualify columns the older server can lose."""
cmd = build_tmux_capture_command(
"%0", tmux_version=version, nonce="WIDTH_120", include_saved_primary=False
)
meta = f"WIDTH_120:PRE:8\t1\t{z_col + 1}\t0"
body = "\x1b[32m" + text
raw = [meta, "WIDTH_120:CAPTURE", ("- " if cmd.flagged else "") + body]
if cmd.has_joined:
raw.extend(["WIDTH_120:JOINED", body])
result = cmd.parse([*raw, meta.replace(":PRE:", ":POST:")])
assert result.completeness.exact_cells is exact
assert ("grapheme_widths" in result.completeness.unexposed_fields) is not exact
snap = result.snapshot
assert snap[0, z_col].text == "Z"
assert snap[0, z_col].style.fg == AnsiColor.GREEN
assert (snap.cursor.row, snap.cursor.col, snap[0].wrapped) == (0, z_col + 1, False)
result.terminal.feed(b"\rX")
assert snap[0, 0].text != "X"


def test_capture_width_checks_only_printed_text_in_both_screens() -> None:
"""Inspect the saved primary, skip OSC payloads and retain one-column evidence."""
meta = TmuxPaneMetadata(cols=4, rows=1, alternate_on=True)
link = "\x1b]8;;https://example.org/✈️\x1b\\Z\x1b]8;;\x1b\\"
exact = decode_tmux_capture([link], metadata=meta, tmux_version="3.4")
assert exact.completeness.exact_cells
for version, trusted in [(None, False), ("3.4", False), ("3.5", True)]:
result = decode_tmux_capture(
[link], metadata=meta, saved_primary_capture=["✈️Z"], tmux_version=version
)
assert result.completeness.exact_cells is trusted
assert result.snapshot.lines == ("Z",)
narrow = decode_tmux_capture(["✈️"], rows=1, cols=1, tmux_version="3.4")
assert not narrow.completeness.exact_cells
cjk = Profile(unicode=UnicodeBehavior(ambiguous_width=2))
phone = decode_tmux_capture(
["☎️ Z"], rows=1, cols=5, tmux_version="3.4", profile=cjk
)
assert phone.snapshot[0, 3].text == "Z"
assert "grapheme_widths" in phone.completeness.unexposed_fields
assert phone.terminal.profile is cjk
Loading