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
12 changes: 12 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,18 @@
_Notes on the upcoming release will go here._
<!-- END PLACEHOLDER - ADD NEW CHANGELOG ENTRIES BELOW THIS LINE -->

### Fixes

#### Capture a pane with its server's version (#158)

On tmux 3.2 and later, a captured pane answers `XTVERSION` with the
selected server's full release, including suffixes such as `3.6b`.
Earlier releases leave the query unanswered. An explicit `profile=`
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.

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

`libvt` 0.0.1a5 adds rectangular grid blitting, display-column text writes, and
Expand Down
7 changes: 7 additions & 0 deletions MIGRATION
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@ downstream projects (and `>=0.x,<0.y` once `0.1.0` is released).
_Detailed migration steps for the next version will be posted here._
<!-- END PLACEHOLDER - ADD NEW MIGRATION ENTRIES BELOW THIS LINE -->

### tmux capture and attach

On tmux 3.2 and later, `XTVERSION` replies include the release suffix
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.

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

### Curated PEP 562 `libvt` root exports (#43)
Expand Down
9 changes: 9 additions & 0 deletions docs/topics/sync-and-asyncio.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,15 @@ two-phase `refresh-client -A '%N:pause'` barrier and atomic `capture-pane` +
(True, <TmuxAttachPhase.PAUSING: 'pausing'>)
```

Read the selected server's version with `tmux display-message -p '#{version}'`
and pass it as `tmux_version=` to the capture command or pane sync. On
tmux 3.1c, use
{func}`~libvt.contrib.tmux.capture.build_tmux_capture_command` for a one-shot
capture. The pause barrier and the pane's `XTVERSION` reply work on 3.2a.
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.

## Concurrency and thread ownership

Every method call and attribute read on a {class}`~libvt.terminal.Terminal`
Expand Down
13 changes: 9 additions & 4 deletions src/libvt/contrib/tmux/capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
TMUX_CAPTURE_POLICY,
TMUX_PROFILE,
parse_tmux_version,
tmux_profile,
)
from libvt.events import PromptKind, PromptZone
from libvt.modes import DEC_PRIVATE_MASK, Mode
Expand Down Expand Up @@ -1596,6 +1597,8 @@ class TmuxCaptureCommand:
history_lines : int | None
Requested scrollback bound (``None`` for full history, ``0`` for
viewport-only, or ``N`` for ``-S -N``).
tmux_version : tuple[int, int] | str
Server version used to choose capture flags and the default pane profile.
"""

argv: tuple[str, ...]
Expand All @@ -1605,13 +1608,14 @@ class TmuxCaptureCommand:
has_joined: bool
include_saved_primary: bool
history_lines: int | None = None
tmux_version: tuple[int, int] | str = "3.8a"

def parse(
self,
output: CaptureInput,
*,
scrollback: int | None = None,
profile: Profile = TMUX_PROFILE,
profile: Profile | None = None,
policy: Policy = TMUX_CAPTURE_POLICY,
limits: Limits = DEFAULT_LIMITS,
) -> TmuxCaptureResult:
Expand All @@ -1624,8 +1628,8 @@ def parse(
``tmux_cmd.stdout``) produced by executing :attr:`argv`.
scrollback : int | None
Explicit scrollback ceiling override.
profile : Profile
Compatibility profile for the reconstructed terminal.
profile : Profile | None
Override the pane profile. The default uses the command's server version.
policy : Policy
Security policy for the reconstructed terminal.
limits : Limits
Expand Down Expand Up @@ -1749,7 +1753,7 @@ def parse(
saved_primary_flagged=self.flagged,
saved_primary_trim_trailing=self.trim_trailing,
saved_primary_joined_capture=saved_joined_lines,
profile=profile,
profile=tmux_profile(self.tmux_version) if profile is None else profile,
policy=policy,
limits=limits,
)
Expand Down Expand Up @@ -1937,6 +1941,7 @@ def build_tmux_capture_command(
has_joined=has_joined,
include_saved_primary=include_saved_primary,
history_lines=eff_hist,
tmux_version=tmux_version,
)


Expand Down
24 changes: 17 additions & 7 deletions src/libvt/contrib/tmux/control.py
Original file line number Diff line number Diff line change
Expand Up @@ -935,12 +935,27 @@ def begin_attach(self) -> str:
``;``-chained ``refresh-client -A '%N:pause'`` + nonce barrier line
to write (followed by ``\n``) to the control client's stdin.

Raises
------
libvt.exc.ProtocolError
If the selected server version predates the tmux 3.2 pause barrier.

Examples
--------
>>> from libvt.contrib.tmux.control import TmuxPaneSync
>>> TmuxPaneSync("%2").begin_attach().startswith("refresh-client -A '%2:pause'")
True
"""
from libvt.contrib.tmux.profile import parse_tmux_version
from libvt.exc import ProtocolError

if parse_tmux_version(self.tmux_version) < (3, 2):
msg = (
"Pause-based attach requires tmux 3.2 or newer. "
"Use build_tmux_capture_command for a one-shot capture on a server "
"with capture-pane -N, or capture-pane -p for plain text."
)
raise ProtocolError(msg)
marker = f"__LIBVT_PAUSED_{os.urandom(6).hex()}__"
self._pause_marker = marker.encode("ascii")
self._phase = TmuxAttachPhase.PAUSING
Expand Down Expand Up @@ -1074,7 +1089,7 @@ def handle_event(self, event: TmuxControlEvent) -> str | None:
if self._phase == TmuxAttachPhase.CAPTURING:
from libvt.config import DEFAULT_LIMITS
from libvt.contrib.tmux.capture import TmuxCaptureCommand
from libvt.contrib.tmux.profile import TMUX_OBSERVER_POLICY, tmux_profile
from libvt.contrib.tmux.profile import TMUX_OBSERVER_POLICY
from libvt.exc import ProtocolError

cap_cmd = t.cast("TmuxCaptureCommand", self._capture_cmd_obj)
Expand Down Expand Up @@ -1104,17 +1119,12 @@ def handle_event(self, event: TmuxControlEvent) -> str | None:
for blk in cap_blocks
for ln in blk.lines
]
eff_profile = (
tmux_profile(self.tmux_version)
if self._profile is None
else self._profile
)
eff_policy = TMUX_OBSERVER_POLICY if self._policy is None else self._policy
eff_limits = DEFAULT_LIMITS if self._limits is None else self._limits
res = cap_cmd.parse(
combined_lines,
scrollback=self.scrollback,
profile=eff_profile,
profile=self._profile,
policy=eff_policy,
limits=eff_limits,
)
Expand Down
7 changes: 6 additions & 1 deletion src/libvt/contrib/tmux/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,11 @@ def tmux_profile(
(False, True)
"""
major, minor = parse_tmux_version(version)
banner = (
version.strip().removeprefix("tmux").lstrip()
if isinstance(version, str)
else f"{major}.{minor}"
)
at_least_3_6 = (major, minor) >= (3, 6)
at_least_3_9 = (major, minor) >= (3, 9)
da1_attrs = ["1", "2"]
Expand All @@ -142,7 +147,7 @@ def tmux_profile(
name="tmux",
da1=da1,
da2=b"\x1b[>84;0;0c",
xtversion=f"tmux {major}.{minor}",
xtversion=f"tmux {banner}" if (major, minor) >= (3, 2) else "",
osc_7501_capabilities="?" if at_least_3_9 else "",
),
queries=QueryBehavior(
Expand Down
6 changes: 4 additions & 2 deletions src/libvt/contrib/tmux/window.py
Original file line number Diff line number Diff line change
Expand Up @@ -1974,7 +1974,7 @@ def composite_tmux_window(
panes: collections.abc.Mapping[str, TmuxPaneSource],
*,
tmux_version: tuple[int, int] | str = "3.8a",
profile: Profile = TMUX_PROFILE,
profile: Profile | None = None,
) -> Snapshot:
r"""Composite a multi-pane ``tmux`` window into one immutable :class:`Snapshot`.

Expand All @@ -2000,7 +2000,7 @@ def composite_tmux_window(
visibility (``tmux >= 3.7`` hides a ``pending_wrap`` cursor at the
window right margin via ``screen_redraw_get_visible_ranges``, whereas
``tmux <= 3.6`` keeps it visible at ``cols - 1``).
profile : Profile, default TMUX_PROFILE
profile : Profile | None, default None
Terminal compatibility profile for width calculations and the returned
:class:`~libvt.terminal.Snapshot`.

Expand Down Expand Up @@ -2048,6 +2048,8 @@ def composite_tmux_window(
w_cols = min(_TMUX_MAX_DIM, max(1, layout.width))
w_rows = min(_TMUX_MAX_DIM, max(1, layout.height))
ver = parse_tmux_version(tmux_version)
if profile is None:
profile = tmux_profile(tmux_version)
canvas = Screen(rows=w_rows, cols=w_cols, scrollback=0, profile=profile)
theme_ctx = layout._theme_ctx

Expand Down
56 changes: 56 additions & 0 deletions tests/test_tmux.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,14 @@
TMUX_METADATA_FORMAT,
TmuxLineFlags,
TmuxPaneMetadata,
TmuxPaneSync,
build_tmux_capture_command,
decode_tmux_capture,
parse_flagged_line,
tmux_profile,
unescape_tmux_control_output,
)
from libvt.exc import ProtocolError
from libvt.modes import Mode
from libvt.style import AnsiColor, IndexedColor

Expand Down Expand Up @@ -1098,3 +1100,57 @@ def _pump_until(pred: object, timeout: float = 3.0) -> None:
check=False,
capture_output=True,
)


@pytest.mark.parametrize(
("version", "spelling"),
[
(" tmux 3.6b ", "3.6b"),
("tmux 3.8-rc3", "3.8-rc3"),
("next-3.9", "next-3.9"),
("master", "master"),
((3, 6), "3.6"),
],
)
def test_capture_query_uses_selected_version(
version: tuple[int, int] | str, spelling: str
) -> None:
"""The selected native banner survives whole and split version queries."""
command = build_tmux_capture_command(
"%0", tmux_version=version, nonce="TEST_NATIVE", include_saved_primary=False
)
lines = ["TEST_NATIVE:PRE:8\t1\t0\t0", "TEST_NATIVE:CAPTURE"]
if command.flagged:
lines.append("- ok")
else:
lines.extend(["ok", "TEST_NATIVE:JOINED", "ok"])
lines.append("TEST_NATIVE:POST:8\t1\t0\t0")
assert tmux_profile(version).identity.xtversion == f"tmux {spelling}"
for result, banner in (
(command.parse(lines), spelling),
(command.parse(lines, profile=tmux_profile("3.5a")), "3.5a"),
):
assert result.snapshot.lines == ("ok",)
term = result.terminal
for chunk in b"\x1b[>0q":
term.feed(bytes((chunk,)))
reply = b"\x1bP>|tmux " + banner.encode("ascii") + b"\x1b\\"
assert term.drain_replies() == reply
term.feed(b"\x1b[>0q")
assert term.drain_replies() == reply


def test_older_tmux_attach_identifies_one_shot_capture() -> None:
"""An unsupported pause request leaves a compatible one-shot path."""
old = libvt.Terminal(rows=4, cols=32, profile=tmux_profile("3.1c"))
old.feed(b"\x1b[>0q")
assert old.drain_replies() == b""
sync = TmuxPaneSync("%0", tmux_version="tmux 3.1c")
with pytest.raises(ProtocolError, match=r"3\.2.*build_tmux_capture_command"):
sync.begin_attach()
assert sync.phase.value == "unattached"
assert (
TmuxPaneSync("%0", tmux_version="3.2a")
.begin_attach()
.startswith("refresh-client -A ")
)
7 changes: 7 additions & 0 deletions tests/test_tmux_window_capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
decode_tmux_capture,
parse_tmux_version,
parse_tmux_window_layout,
tmux_profile,
)
from libvt.screen import Screen
from libvt.style import (
Expand Down Expand Up @@ -168,6 +169,12 @@ def snapshot(self) -> Snapshot:
assert (snap_34.cursor.col, snap_34.cursor.visible) == (12, True)
assert (snap_38.cursor.col, snap_38.cursor.visible) == (12, False)

assert snap_34._profile == tmux_profile("3.4")
assert snap_38._profile.identity.xtversion == "tmux 3.8a"
override = tmux_profile("3.5a")
explicit = composite_tmux_window(v1, {}, tmux_version="3.6b", profile=override)
assert explicit._profile is override

# V1 layouts omit active-pane flags; WIN_POST active pane ID must flag a
# focus switch between layout discovery and capture as layout_stable=False.
v1_active_0 = parse_tmux_window_layout(
Expand Down
Loading