Debian Codegraph @

src/libtmux/pane.py

raw symbols SCIP
1 """Pythonization of the :ref:`tmux(1)` pane.
2
3 libtmux.pane
4 ~~~~~~~~~~~~
5
6 """
7
8 from __future__ import annotations
9
10 import dataclasses
11 import logging
12 import pathlib
13 import typing as t
14 import warnings
15
16 from libtmux import exc
17 from libtmux.common import get_version_str, has_gte_version, raise_if_stderr, tmux_cmd
18 from libtmux.constants import (
19 PANE_DIRECTION_FLAG_MAP,
20 RESIZE_ADJUSTMENT_DIRECTION_FLAG_MAP,
21 OptionScope,
22 PaneDirection,
23 ResizeAdjustmentDirection,
24 )
25 from libtmux.formats import FORMAT_SEPARATOR
26 from libtmux.hooks import HooksMixin
27 from libtmux.neo import Obj, fetch_obj
28 from libtmux.options import OptionsMixin
29
30 if t.TYPE_CHECKING:
31 import sys
32 import types
33
34 from libtmux._internal.types import StrPath
35
36 from .server import Server
37 from .session import Session
38 from .window import Window
39
40 if sys.version_info >= (3, 11):
41 from typing import Self
42 else:
43 from typing_extensions import Self
44
45 logger = logging.getLogger(__name__)
46
47
48 @dataclasses.dataclass()
49 class Pane(
50 Obj,
51 OptionsMixin,
52 HooksMixin,
53 ):
54 """:term:`tmux(1)` :term:`Pane` [pane_manual]_.
55
56 ``Pane`` instances can send commands directly to a pane, or traverse
57 between linked tmux objects.
58
59 Examples
60 --------
61 >>> pane
62 Pane(%1 Window(@1 1:..., Session($1 ...)))
63
64 >>> pane in window.panes
65 True
66
67 >>> pane.window
68 Window(@1 1:..., Session($1 ...))
69
70 >>> pane.session
71 Session($1 ...)
72
73 The pane can be used as a context manager to ensure proper cleanup:
74
75 >>> with window.split() as pane:
76 ... pane.send_keys('echo "Hello"')
77 ... # Do work with the pane
78 ... # Pane will be killed automatically when exiting the context
79
80 Notes
81 -----
82 .. versionchanged:: 0.8
83 Renamed from ``.tmux`` to ``.cmd``.
84
85 References
86 ----------
87 .. [pane_manual] tmux pane. openbsd manpage for TMUX(1).
88 "Each window displayed by tmux may be split into one or more
89 panes; each pane takes up a certain area of the display and is
90 a separate terminal."
91
92 https://man.openbsd.org/tmux.1#WINDOWS_AND_PANES.
93 Accessed April 1st, 2018.
94 """
95
96 default_option_scope: OptionScope | None = OptionScope.Pane
97 default_hook_scope: OptionScope | None = OptionScope.Pane
98 server: Server
99
100 def __enter__(self) -> Self:
101 """Enter the context, returning self.
102
103 Returns
104 -------
105 :class:`Pane`
106 The pane instance
107 """
108 return self
109
110 def __exit__(
111 self,
112 exc_type: type[BaseException] | None,
113 exc_value: BaseException | None,
114 exc_tb: types.TracebackType | None,
115 ) -> None:
116 """Exit the context, killing the pane if it exists.
117
118 Parameters
119 ----------
120 exc_type : type[BaseException] | None
121 The type of the exception that was raised
122 exc_value : BaseException | None
123 The instance of the exception that was raised
124 exc_tb : types.TracebackType | None
125 The traceback of the exception that was raised
126 """
127 if (
128 self.pane_id is not None
129 and len(self.window.panes.filter(pane_id=self.pane_id)) > 0
130 ):
131 self.kill()
132
133 def refresh(self) -> None:
134 """Refresh pane attributes from tmux.
135
136 Raises
137 ------
138 ValueError
139 When ``pane_id`` is unset. Surfaces a clear error under
140 ``python -O``, where an ``assert`` would be stripped.
141 """
142 if self.pane_id is None:
143 msg = "Pane must have a pane_id to refresh"
144 raise ValueError(msg)
145 return super()._refresh(
146 obj_key="pane_id",
147 obj_id=self.pane_id,
148 list_extra_args=("-a",),
149 )
150
151 @classmethod
152 def from_pane_id(cls, server: Server, pane_id: str) -> Pane:
153 """Create Pane from existing pane_id."""
154 pane = fetch_obj(
155 obj_key="pane_id",
156 obj_id=pane_id,
157 server=server,
158 list_cmd="list-panes",
159 list_extra_args=("-a",),
160 )
161 return cls(server=server, **pane)
162
163 #
164 # Relations
165 #
166 @property
167 def window(self) -> Window:
168 """Parent window of pane."""
169 assert isinstance(self.window_id, str)
170 from libtmux.window import Window
171
172 return Window.from_window_id(server=self.server, window_id=self.window_id)
173
174 @property
175 def session(self) -> Session:
176 """Parent session of pane."""
177 return self.window.session
178
179 """
180 Commands (pane-scoped)
181 """
182
183 def cmd(
184 self,
185 cmd: str,
186 *args: t.Any,
187 target: str | int | None = None,
188 ) -> tmux_cmd:
189 """Execute tmux subcommand within pane context.
190
191 Automatically binds target by adding ``-t`` for object's pane ID to the
192 command. Pass ``target`` to keyword arguments to override.
193
194 Examples
195 --------
196 >>> pane.cmd('split-window', '-P').stdout[0]
197 'libtmux...:...'
198
199 From raw output to an enriched `Pane` object:
200
201 >>> Pane.from_pane_id(pane_id=pane.cmd(
202 ... 'split-window', '-P', '-F#{pane_id}').stdout[0], server=pane.server)
203 Pane(%... Window(@... ...:..., Session($1 libtmux_...)))
204
205 Parameters
206 ----------
207 target : str, optional
208 Optional custom target override. By default, the target is the pane ID.
209
210 Returns
211 -------
212 :meth:`server.cmd`
213 """
214 if target is None:
215 target = self.pane_id
216
217 return self.server.cmd(cmd, *args, target=target)
218
219 """
220 Commands (tmux-like)
221 """
222
223 def resize(
224 self,
225 /,
226 # Adjustments
227 adjustment_direction: ResizeAdjustmentDirection | None = None,
228 adjustment: int | None = None,
229 # Manual
230 height: str | int | None = None,
231 width: str | int | None = None,
232 # Zoom
233 zoom: bool | None = None,
234 # Mouse
235 mouse: bool | None = None,
236 # Optional flags
237 trim_below: bool | None = None,
238 ) -> Pane:
239 """Resize tmux pane.
240
241 Parameters
242 ----------
243 adjustment_direction : ResizeAdjustmentDirection, optional
244 direction to adjust, ``Up``, ``Down``, ``Left``, ``Right``.
245 adjustment : ResizeAdjustmentDirection, optional
246
247 height : int, optional
248 ``resize-pane -y`` dimensions
249 width : int, optional
250 ``resize-pane -x`` dimensions
251
252 zoom : bool
253 expand pane
254
255 mouse : bool
256 resize via mouse
257
258 trim_below : bool
259 trim below cursor
260
261 Raises
262 ------
263 :exc:`exc.LibTmuxException`,
264 :exc:`exc.PaneAdjustmentDirectionRequiresAdjustment`,
265 :exc:`exc.RequiresDigitOrPercentage`
266
267 Returns
268 -------
269 :class:`Pane`
270
271 Notes
272 -----
273 Three types of resizing are available:
274
275 1. Adjustments: ``adjustment_direction`` and ``adjustment``.
276 2. Manual resizing: ``height`` and / or ``width``.
277 3. Zoom / Unzoom: ``zoom``.
278 """
279 tmux_args: tuple[str, ...] = ()
280
281 # Adjustments
282 if adjustment_direction:
283 if adjustment is None:
284 raise exc.PaneAdjustmentDirectionRequiresAdjustment
285 tmux_args += (
286 f"{RESIZE_ADJUSTMENT_DIRECTION_FLAG_MAP[adjustment_direction]}",
287 str(adjustment),
288 )
289 elif height or width:
290 # Manual resizing
291 if height:
292 if (
293 isinstance(height, str)
294 and not height.isdigit()
295 and not height.endswith("%")
296 ):
297 raise exc.RequiresDigitOrPercentage
298 tmux_args += (f"-y{height}",)
299
300 if width:
301 if (
302 isinstance(width, str)
303 and not width.isdigit()
304 and not width.endswith("%")
305 ):
306 raise exc.RequiresDigitOrPercentage
307 tmux_args += (f"-x{width}",)
308 elif zoom:
309 # Zoom / Unzoom
310 tmux_args += ("-Z",)
311 elif mouse:
312 tmux_args += ("-M",)
313
314 if trim_below:
315 tmux_args += ("-T",)
316
317 proc = self.cmd("resize-pane", *tmux_args)
318
319 raise_if_stderr(proc, "resize-pane")
320
321 self.refresh()
322 return self
323
324 @t.overload
325 def capture_pane(
326 self,
327 start: t.Literal["-"] | int | None = ...,
328 end: t.Literal["-"] | int | None = ...,
329 *,
330 escape_sequences: bool = ...,
331 escape_non_printable: bool = ...,
332 join_wrapped: bool = ...,
333 preserve_trailing: bool = ...,
334 trim_trailing: bool = ...,
335 alternate_screen: bool = ...,
336 quiet: bool = ...,
337 mode_screen: bool = ...,
338 pending: bool = ...,
339 hyperlinks: bool = ...,
340 line_numbers: bool = ...,
341 line_flags: bool = ...,
342 to_buffer: str,
343 ) -> None: ...
344
345 @t.overload
346 def capture_pane(
347 self,
348 start: t.Literal["-"] | int | None = ...,
349 end: t.Literal["-"] | int | None = ...,
350 *,
351 escape_sequences: bool = ...,
352 escape_non_printable: bool = ...,
353 join_wrapped: bool = ...,
354 preserve_trailing: bool = ...,
355 trim_trailing: bool = ...,
356 alternate_screen: bool = ...,
357 quiet: bool = ...,
358 mode_screen: bool = ...,
359 pending: bool = ...,
360 hyperlinks: bool = ...,
361 line_numbers: bool = ...,
362 line_flags: bool = ...,
363 to_buffer: None = ...,
364 ) -> list[str]: ...
365
366 def capture_pane(
367 self,
368 start: t.Literal["-"] | int | None = None,
369 end: t.Literal["-"] | int | None = None,
370 *,
371 escape_sequences: bool = False,
372 escape_non_printable: bool = False,
373 join_wrapped: bool = False,
374 preserve_trailing: bool = False,
375 trim_trailing: bool = False,
376 alternate_screen: bool = False,
377 quiet: bool = False,
378 mode_screen: bool = False,
379 pending: bool = False,
380 hyperlinks: bool = False,
381 line_numbers: bool = False,
382 line_flags: bool = False,
383 to_buffer: str | None = None,
384 ) -> list[str] | None:
385 r"""Capture text from pane.
386
387 ``$ tmux capture-pane`` to pane.
388 ``$ tmux capture-pane -S -10`` to pane.
389 ``$ tmux capture-pane -E 3`` to pane.
390 ``$ tmux capture-pane -S - -E -`` to pane.
391
392 Parameters
393 ----------
394 start : str | int, optional
395 Specify the starting line number.
396 Zero is the first line of the visible pane.
397 Positive numbers are lines in the visible pane.
398 Negative numbers are lines in the history.
399 ``-`` is the start of the history.
400 Default: None
401 end : str | int, optional
402 Specify the ending line number.
403 Zero is the first line of the visible pane.
404 Positive numbers are lines in the visible pane.
405 Negative numbers are lines in the history.
406 ``-`` is the end of the visible pane.
407 Default: None
408 escape_sequences : bool, optional
409 Include ANSI escape sequences for text and background attributes
410 (``-e`` flag). Useful for capturing colored output.
411 Default: False
412 escape_non_printable : bool, optional
413 Escape non-printable characters as octal ``\\xxx`` format
414 (``-C`` flag). Useful for binary-safe capture.
415 Default: False
416 join_wrapped : bool, optional
417 Join wrapped lines and preserve trailing spaces (``-J`` flag).
418 Lines that were wrapped by tmux will be joined back together.
419 Default: False
420 preserve_trailing : bool, optional
421 Preserve trailing spaces at each line's end (``-N`` flag).
422 Default: False
423 trim_trailing : bool, optional
424 Trim trailing positions with no characters (``-T`` flag).
425 Only includes characters up to the last used cell.
426 Requires tmux 3.4+. If used with tmux < 3.4, a warning
427 is issued and the flag is ignored.
428 Default: False
429 alternate_screen : bool, optional
430 Capture from the alternate screen (``-a`` flag).
431 Default: False
432
433 .. versionadded:: 0.56
434 quiet : bool, optional
435 Suppress errors silently (``-q`` flag).
436 Default: False
437
438 .. versionadded:: 0.56
439 mode_screen : bool, optional
440 Capture from the mode screen (e.g. copy mode) instead of the
441 pane (``-M`` flag). Requires tmux 3.6+.
442 Default: False
443
444 .. versionadded:: 0.56
445 pending : bool, optional
446 Capture *pending output* — the bytes tmux has read from the
447 pane but not yet committed to the terminal (``-P`` flag).
448 These are bytes that begin an incomplete escape sequence
449 and are still pending the parser's ground state (tmux's
450 ``input_pending()`` / ``since_ground`` buffer), distinct
451 from the default capture (the pane's screen history).
452 Useful for diagnosing programs whose output stalls
453 mid-sequence.
454 Default: False
455
456 .. versionadded:: 0.57
457 hyperlinks : bool, optional
458 Capture only hyperlink targets in the selected lines (``-H``
459 flag). Requires tmux 3.7+. If used with tmux < 3.7, a warning
460 is issued and the flag is ignored.
461 Default: False
462 line_numbers : bool, optional
463 Prefix each captured line with its line number (``-L`` flag).
464 Requires tmux 3.7+. If used with tmux < 3.7, a warning is issued
465 and the flag is ignored.
466 Default: False
467 line_flags : bool, optional
468 Prefix each captured line with its flags, e.g. ``H`` for a line
469 with a hyperlink (``-F`` flag). Requires tmux 3.7+. If used with
470 tmux < 3.7, a warning is issued and the flag is ignored.
471 Default: False
472 to_buffer : str, optional
473 Write the capture into the named tmux buffer (``-b`` flag)
474 instead of returning it. When set, ``-p`` is omitted and
475 the wrapper returns ``None``.
476
477 .. versionadded:: 0.56
478
479 Returns
480 -------
481 list[str] or None
482 Captured pane content, or ``None`` when *to_buffer* is set.
483
484 Examples
485 --------
486 >>> pane = window.split(shell='sh')
487 >>> pane.capture_pane()
488 ['$']
489
490 >>> pane.send_keys('echo "Hello world"', enter=True)
491
492 >>> pane.capture_pane()
493 ['$ echo "Hello world"', 'Hello world', '$']
494
495 >>> print(chr(10).join(pane.capture_pane()))
496 $ echo "Hello world"
497 Hello world
498 $
499 """
500 cmd = ["capture-pane"]
501 if to_buffer is not None:
502 cmd.extend(["-b", to_buffer])
503 else:
504 cmd.append("-p")
505 if start is not None:
506 cmd.extend(["-S", str(start)])
507 if end is not None:
508 cmd.extend(["-E", str(end)])
509 if escape_sequences:
510 cmd.append("-e")
511 if escape_non_printable:
512 cmd.append("-C")
513 if join_wrapped:
514 cmd.append("-J")
515 if preserve_trailing:
516 cmd.append("-N")
517 if trim_trailing:
518 if has_gte_version("3.4", tmux_bin=self.server.tmux_bin):
519 cmd.append("-T")
520 else:
521 warnings.warn(
522 "trim_trailing requires tmux 3.4+, ignoring",
523 stacklevel=2,
524 )
525 if alternate_screen:
526 cmd.append("-a")
527 if quiet:
528 cmd.append("-q")
529 if mode_screen:
530 if has_gte_version("3.6", tmux_bin=self.server.tmux_bin):
531 cmd.append("-M")
532 else:
533 warnings.warn(
534 "mode_screen requires tmux 3.6+, ignoring",
535 stacklevel=2,
536 )
537 if pending:
538 cmd.append("-P")
539 if hyperlinks:
540 if has_gte_version("3.7", tmux_bin=self.server.tmux_bin):
541 cmd.append("-H")
542 else:
543 warnings.warn(
544 "hyperlinks requires tmux 3.7+, ignoring",
545 stacklevel=2,
546 )
547 if line_numbers:
548 if has_gte_version("3.7", tmux_bin=self.server.tmux_bin):
549 cmd.append("-L")
550 else:
551 warnings.warn(
552 "line_numbers requires tmux 3.7+, ignoring",
553 stacklevel=2,
554 )
555 if line_flags:
556 if has_gte_version("3.7", tmux_bin=self.server.tmux_bin):
557 cmd.append("-F")
558 else:
559 warnings.warn(
560 "line_flags requires tmux 3.7+, ignoring",
561 stacklevel=2,
562 )
563 proc = self.cmd(*cmd)
564 if to_buffer is not None:
565 return None
566 return proc.stdout
567
568 def send_keys(
569 self,
570 cmd: str | None = None,
571 enter: bool | None = True,
572 suppress_history: bool | None = False,
573 literal: bool | None = False,
574 reset: bool | None = None,
575 copy_mode_cmd: str | None = None,
576 repeat: int | None = None,
577 expand_formats: bool | None = None,
578 hex_keys: bool | None = None,
579 target_client: str | None = None,
580 key_name: bool | None = None,
581 ) -> None:
582 r"""``$ tmux send-keys`` to the pane.
583
584 A leading space character is added to cmd to avoid polluting the
585 user's history.
586
587 When ``cmd`` is omitted (``None``), the wrapper emits a flag-only
588 invocation — useful with ``reset=True`` or ``repeat=N`` to invoke
589 tmux's deliberate ``count == 0`` branch in ``cmd-send-keys.c`` that
590 runs the flag effect without sending any keys. In flag-only mode,
591 ``enter`` is forced ``False`` (no keys → no Enter).
592
593 Parameters
594 ----------
595 cmd : str | None, optional
596 Text or input into pane. ``None`` for flag-only invocation
597 (requires ``reset``, ``repeat``, or ``copy_mode_cmd`` to be set).
598
599 .. versionchanged:: 0.57
600
601 Now optional. ``None`` triggers tmux's flag-only path.
602 enter : bool, optional
603 Send enter after sending the input, default True.
604 suppress_history : bool, optional
605 Prepend a space to command to suppress shell history, default False.
606
607 .. versionchanged:: 0.14
608
609 Default changed from True to False.
610 literal : bool, optional
611 Send keys literally, default False.
612 reset : bool, optional
613 Reset terminal state before sending keys (``-R`` flag).
614
615 .. versionadded:: 0.56
616 copy_mode_cmd : str, optional
617 Send a command to copy mode instead of keys (``-X`` flag).
618 When set, *cmd* is ignored.
619
620 .. versionadded:: 0.56
621 repeat : int, optional
622 Repeat count for the key (``-N`` flag).
623
624 .. versionadded:: 0.56
625 expand_formats : bool, optional
626 Expand tmux format strings in keys (``-F`` flag).
627
628 .. versionadded:: 0.56
629 hex_keys : bool, optional
630 Send keys as hex values (``-H`` flag).
631
632 .. versionadded:: 0.56
633 target_client : str, optional
634 Specify a target client (``-c`` flag). Requires tmux 3.4+.
635
636 .. versionadded:: 0.56
637 key_name : bool, optional
638 Handle keys as key names (``-K`` flag). Requires tmux 3.4+.
639
640 .. versionadded:: 0.56
641
642 Raises
643 ------
644 ValueError
645 If ``cmd`` is ``None`` and no flag-only path is selected
646 (``reset``, ``repeat``, or ``copy_mode_cmd``).
647
648 Examples
649 --------
650 >>> pane = window.split(shell='sh')
651 >>> pane.capture_pane()
652 ['$']
653
654 >>> pane.send_keys('echo "Hello world"', enter=True)
655
656 >>> pane.capture_pane()
657 ['$ echo "Hello world"', 'Hello world', '$']
658
659 >>> print('\n'.join(pane.capture_pane())) # doctest: +NORMALIZE_WHITESPACE
660 $ echo "Hello world"
661 Hello world
662 $
663
664 Flag-only invocation — reset terminal state without sending any keys:
665
666 >>> pane.send_keys(reset=True)
667 """
668 prefix = " " if suppress_history else ""
669
670 tmux_args: tuple[str, ...] = ()
671
672 if reset:
673 tmux_args += ("-R",)
674
675 if expand_formats:
676 tmux_args += ("-F",)
677
678 if hex_keys:
679 tmux_args += ("-H",)
680
681 if key_name:
682 if has_gte_version("3.4", tmux_bin=self.server.tmux_bin):
683 tmux_args += ("-K",)
684 else:
685 warnings.warn(
686 "key_name requires tmux 3.4+, ignoring",
687 stacklevel=2,
688 )
689
690 if literal:
691 tmux_args += ("-l",)
692
693 if repeat is not None:
694 tmux_args += ("-N", str(repeat))
695
696 if target_client is not None:
697 if has_gte_version("3.4", tmux_bin=self.server.tmux_bin):
698 tmux_args += ("-c", target_client)
699 else:
700 warnings.warn(
701 "target_client requires tmux 3.4+, ignoring",
702 stacklevel=2,
703 )
704
705 if copy_mode_cmd is not None:
706 tmux_args += ("-X",)
707 self.cmd("send-keys", *tmux_args, copy_mode_cmd)
708 elif cmd is None:
709 # Flag-only path — tmux's cmd-send-keys.c:223-225 explicitly
710 # supports count == 0 when -R or -N is set, returning
711 # CMD_RETURN_NORMAL without sending keys.
712 if not reset and repeat is None:
713 msg = (
714 "send_keys(cmd=None) requires at least one of: "
715 "reset=True, repeat=N, copy_mode_cmd=..."
716 )
717 raise ValueError(msg)
718 self.cmd("send-keys", *tmux_args)
719 return
720 else:
721 self.cmd("send-keys", *tmux_args, prefix + cmd)
722
723 if enter and copy_mode_cmd is None:
724 self.enter()
725
726 @t.overload
727 def display_message(
728 self,
729 cmd: str,
730 get_text: t.Literal[True],
731 *,
732 format_string: str | None = ...,
733 all_formats: bool | None = ...,
734 verbose: bool | None = ...,
735 no_expand: bool | None = ...,
736 target_client: str | None = ...,
737 delay: int | None = ...,
738 notify: bool | None = ...,
739 update_pane: bool | None = ...,
740 ) -> list[str]: ...
741
742 @t.overload
743 def display_message(
744 self,
745 cmd: str,
746 get_text: t.Literal[False] = ...,
747 *,
748 format_string: str | None = ...,
749 all_formats: bool | None = ...,
750 verbose: bool | None = ...,
751 no_expand: bool | None = ...,
752 target_client: str | None = ...,
753 delay: int | None = ...,
754 notify: bool | None = ...,
755 update_pane: bool | None = ...,
756 ) -> None: ...
757
758 def display_message(
759 self,
760 cmd: str,
761 get_text: bool = False,
762 *,
763 format_string: str | None = None,
764 all_formats: bool | None = None,
765 verbose: bool | None = None,
766 no_expand: bool | None = None,
767 target_client: str | None = None,
768 delay: int | None = None,
769 notify: bool | None = None,
770 update_pane: bool | None = None,
771 ) -> list[str] | None:
772 """Display message to pane.
773
774 Displays a message in target-client status line.
775 The ``get_text=False`` path renders in the status line and is not
776 programmatically verifiable; only ``get_text=True`` returns output.
777
778 Parameters
779 ----------
780 cmd : str
781 Special parameters to request from pane.
782 get_text : bool, optional
783 Returns only text without displaying a message in
784 target-client status line.
785 format_string : str, optional
786 Format string for output (``-F`` flag).
787
788 .. versionadded:: 0.56
789 all_formats : bool, optional
790 List all format variables (``-a`` flag).
791
792 .. versionadded:: 0.56
793 verbose : bool, optional
794 Show format variable types (``-v`` flag).
795
796 .. versionadded:: 0.56
797 no_expand : bool, optional
798 Suppress format expansion; output is returned as a literal string
799 (``-l`` flag). Requires tmux 3.4+.
800
801 .. versionadded:: 0.56
802 target_client : str, optional
803 Target client (``-c`` flag).
804
805 .. versionadded:: 0.56
806 delay : int, optional
807 Display time in milliseconds (``-d`` flag).
808
809 .. versionadded:: 0.56
810 notify : bool, optional
811 Do not wait for input (``-N`` flag).
812
813 .. versionadded:: 0.56
814 update_pane : bool, optional
815 Allow the pane to keep updating while the message is displayed
816 (``-C`` flag). By default tmux freezes the pane while a status
817 message is shown. Requires tmux 3.6+ (introduced upstream by
818 commit ``80eb460f``).
819
820 .. versionadded:: 0.56
821
822 Returns
823 -------
824 list[str] | None
825 Message output if get_text is True, otherwise None.
826
827 Notes
828 -----
829 Stderr from tmux is reported via :func:`warnings.warn`, not raised.
830 Callers that want to escalate to an exception can wrap the call in
831 :func:`warnings.catch_warnings` with ``filterwarnings("error")``.
832
833 .. versionchanged:: 0.57
834 Reports stderr via :func:`warnings.warn` instead of raising.
835 """
836 tmux_args: tuple[str, ...] = ()
837
838 if get_text:
839 tmux_args += ("-p",)
840
841 if all_formats:
842 tmux_args += ("-a",)
843
844 if verbose:
845 tmux_args += ("-v",)
846
847 if no_expand:
848 if has_gte_version("3.4", tmux_bin=self.server.tmux_bin):
849 tmux_args += ("-l",)
850 else:
851 warnings.warn(
852 "no_expand requires tmux 3.4+, ignoring",
853 stacklevel=2,
854 )
855
856 if notify:
857 tmux_args += ("-N",)
858
859 if update_pane:
860 if has_gte_version("3.6", tmux_bin=self.server.tmux_bin):
861 tmux_args += ("-C",)
862 else:
863 warnings.warn(
864 "update_pane requires tmux 3.6+, ignoring",
865 stacklevel=2,
866 )
867
868 if target_client is not None:
869 tmux_args += ("-c", target_client)
870
871 if delay is not None:
872 tmux_args += ("-d", str(delay))
873
874 if format_string is not None:
875 tmux_args += ("-F", format_string)
876
877 if cmd:
878 tmux_args += (cmd,)
879
880 proc = self.cmd("display-message", *tmux_args)
881 if proc.stderr:
882 warnings.warn(
883 f"display-message: {'; '.join(proc.stderr)}",
884 stacklevel=2,
885 )
886
887 if get_text:
888 return proc.stdout
889
890 return None
891
892 def kill(
893 self,
894 all_except: bool | None = None,
895 ) -> None:
896 """Kill :class:`Pane`.
897
898 ``$ tmux kill-pane``.
899
900 Examples
901 --------
902 Kill a pane:
903
904 >>> pane_1 = pane.split()
905
906 >>> pane_1 in window.panes
907 True
908
909 >>> pane_1.kill()
910
911 >>> pane_1 not in window.panes
912 True
913
914 Kill all panes except the current one:
915
916 >>> pane.window.resize(height=100, width=100)
917 Window(@1 1...)
918
919 >>> one_pane_to_rule_them_all = pane.split()
920
921 >>> other_panes = pane.split(
922 ... ), pane.split()
923
924 >>> all([p in window.panes for p in other_panes])
925 True
926
927 >>> one_pane_to_rule_them_all.kill(all_except=True)
928
929 >>> all([p not in window.panes for p in other_panes])
930 True
931
932 >>> one_pane_to_rule_them_all in window.panes
933 True
934 """
935 flags: tuple[str, ...] = ()
936
937 if all_except:
938 flags += ("-a",)
939
940 proc = self.cmd(
941 "kill-pane",
942 *flags,
943 )
944
945 raise_if_stderr(proc, "kill-pane")
946
947 extra: dict[str, str] = {
948 "tmux_subcommand": "kill-pane",
949 }
950 if self.pane_id is not None:
951 extra["tmux_pane"] = str(self.pane_id)
952 extra["tmux_target"] = str(self.pane_id)
953 msg = "other panes killed" if all_except else "pane killed"
954 logger.info(msg, extra=extra)
955
956 """
957 Commands ("climber"-helpers)
958
959 These are commands that climb to the parent scope's methods with
960 additional scoped window info.
961 """
962
963 def select(
964 self,
965 *,
966 direction: ResizeAdjustmentDirection | None = None,
967 last: bool | None = None,
968 keep_zoom: bool | None = None,
969 mark: bool | None = None,
970 clear_mark: bool | None = None,
971 disable_input: bool | None = None,
972 enable_input: bool | None = None,
973 ) -> Pane:
974 """Select pane.
975
976 Parameters
977 ----------
978 direction : ResizeAdjustmentDirection, optional
979 Select the pane in the given direction (``-U``, ``-D``, ``-L``,
980 ``-R``).
981
982 .. versionadded:: 0.56
983 last : bool, optional
984 Select the last (previously selected) pane (``-l`` flag).
985
986 .. versionadded:: 0.56
987 keep_zoom : bool, optional
988 Keep the window zoomed if it was zoomed (``-Z`` flag).
989
990 .. versionadded:: 0.56
991 mark : bool, optional
992 Set the marked pane (``-m`` flag).
993
994 .. versionadded:: 0.56
995 clear_mark : bool, optional
996 Clear the marked pane (``-M`` flag).
997
998 .. versionadded:: 0.56
999 disable_input : bool, optional
1000 Disable input to the pane (``-d`` flag).
1001
1002 .. versionadded:: 0.56
1003 enable_input : bool, optional
1004 Enable input to the pane (``-e`` flag).
1005
1006 .. versionadded:: 0.56
1007
1008 Returns
1009 -------
1010 :class:`Pane`
1011 Self, for method chaining.
1012
1013 Examples
1014 --------
1015 >>> pane = window.active_pane
1016 >>> new_pane = window.split()
1017 >>> pane.refresh()
1018 >>> active_panes = [p for p in window.panes if p.pane_active == '1']
1019
1020 >>> pane in active_panes
1021 True
1022 >>> new_pane in active_panes
1023 False
1024
1025 >>> new_pane.pane_active == '1'
1026 False
1027
1028 >>> new_pane.select()
1029 Pane(...)
1030
1031 >>> new_pane.pane_active == '1'
1032 True
1033 """
1034 tmux_args: tuple[str, ...] = ()
1035
1036 if direction is not None:
1037 tmux_args += (RESIZE_ADJUSTMENT_DIRECTION_FLAG_MAP[direction],)
1038
1039 if last:
1040 tmux_args += ("-l",)
1041
1042 if keep_zoom:
1043 tmux_args += ("-Z",)
1044
1045 if mark:
1046 tmux_args += ("-m",)
1047
1048 if clear_mark:
1049 tmux_args += ("-M",)
1050
1051 if disable_input:
1052 tmux_args += ("-d",)
1053
1054 if enable_input:
1055 tmux_args += ("-e",)
1056
1057 proc = self.cmd("select-pane", *tmux_args)
1058
1059 raise_if_stderr(proc, "select-pane")
1060
1061 self.refresh()
1062
1063 return self
1064
1065 def select_pane(self) -> Pane:
1066 """Select pane.
1067
1068 Notes
1069 -----
1070 .. deprecated:: 0.30
1071
1072 Deprecated in favor of :meth:`.select()`.
1073 """
1074 raise exc.DeprecatedError(
1075 deprecated="Pane.select_pane()",
1076 replacement="Pane.select()",
1077 version="0.30.0",
1078 )
1079
1080 def split(
1081 self,
1082 /,
1083 target: int | str | None = None,
1084 start_directory: StrPath | None = None,
1085 attach: bool = False,
1086 direction: PaneDirection | None = None,
1087 full_window_split: bool | None = None,
1088 zoom: bool | None = None,
1089 shell: str | None = None,
1090 size: str | int | None = None,
1091 percentage: int | None = None,
1092 environment: dict[str, str] | None = None,
1093 empty: bool | None = None,
1094 style: str | None = None,
1095 active_border_style: str | None = None,
1096 inactive_border_style: str | None = None,
1097 message: str | None = None,
1098 keep: bool | None = None,
1099 ) -> Pane:
1100 """Split window and return :class:`Pane`, by default beneath current pane.
1101
1102 Parameters
1103 ----------
1104 target : optional
1105 Optional, custom *target-pane*, used by :meth:`Window.split`.
1106 attach : bool, optional
1107 make new window the current window after creating it, default
1108 True.
1109 start_directory : str or PathLike, optional
1110 specifies the working directory in which the new window is created.
1111 direction : PaneDirection, optional
1112 split in direction. If none is specified, assume down.
1113 full_window_split: bool, optional
1114 split across full window width or height, rather than active pane.
1115 zoom: bool, optional
1116 expand pane
1117 shell : str, optional
1118 execute a command on splitting the window. The pane will close
1119 when the command exits.
1120
1121 NOTE: When this command exits the pane will close. This feature
1122 is useful for long-running processes where the closing of the
1123 window upon completion is desired.
1124 size: int, optional
1125 Cell/row count to occupy with respect to current window.
1126 percentage: int, optional
1127 Percentage (0-100) of the window to occupy (``-p`` flag).
1128 Mutually exclusive with *size*.
1129
1130 .. versionadded:: 0.56
1131 environment: dict, optional
1132 Environmental variables for new pane. Passthrough to ``-e``.
1133 empty : bool, optional
1134 Create an empty pane with no command (``-E`` flag) instead of
1135 spawning the default shell. Requires tmux 3.7+. If used with
1136 tmux < 3.7, a warning is issued and the flag is ignored.
1137 style : str, optional
1138 Style for the new pane (``-s``). Requires tmux 3.7+.
1139 active_border_style : str, optional
1140 Active-pane border style (``-S``). Requires tmux 3.7+.
1141 inactive_border_style : str, optional
1142 Inactive-pane border style (``-R``). Requires tmux 3.7+.
1143 message : str, optional
1144 Keep the pane open (until a key is pressed) after exit, showing this
1145 ``remain-on-exit-format`` message (``-m``). Requires tmux 3.7+.
1146 keep : bool, optional
1147 Keep the pane open until a key is pressed after exit (``-k``).
1148 Requires tmux 3.7+. These 3.7 flags warn and are ignored below 3.7.
1149
1150 Examples
1151 --------
1152 >>> (pane.at_left, pane.at_right,
1153 ... pane.at_top, pane.at_bottom)
1154 (True, True,
1155 True, True)
1156
1157 >>> new_pane = pane.split()
1158
1159 >>> (new_pane.at_left, new_pane.at_right,
1160 ... new_pane.at_top, new_pane.at_bottom)
1161 (True, True,
1162 False, True)
1163
1164 >>> right_pane = pane.split(direction=PaneDirection.Right)
1165
1166 >>> (right_pane.at_left, right_pane.at_right,
1167 ... right_pane.at_top, right_pane.at_bottom)
1168 (False, True,
1169 True, False)
1170
1171 >>> left_pane = pane.split(direction=PaneDirection.Left)
1172
1173 >>> (left_pane.at_left, left_pane.at_right,
1174 ... left_pane.at_top, left_pane.at_bottom)
1175 (True, False,
1176 True, False)
1177
1178 >>> top_pane = pane.split(direction=PaneDirection.Above)
1179
1180 >>> (top_pane.at_left, top_pane.at_right,
1181 ... top_pane.at_top, top_pane.at_bottom)
1182 (False, False,
1183 True, False)
1184
1185 >>> pane = session.new_window().active_pane
1186
1187 >>> top_pane = pane.split(direction=PaneDirection.Above, full_window_split=True)
1188
1189 >>> (top_pane.at_left, top_pane.at_right,
1190 ... top_pane.at_top, top_pane.at_bottom)
1191 (True, True,
1192 True, False)
1193
1194 >>> bottom_pane = pane.split(
1195 ... direction=PaneDirection.Below,
1196 ... full_window_split=True)
1197
1198 >>> (bottom_pane.at_left, bottom_pane.at_right,
1199 ... bottom_pane.at_top, bottom_pane.at_bottom)
1200 (True, True,
1201 False, True)
1202 """
1203 tmux_formats = ["#{pane_id}" + FORMAT_SEPARATOR]
1204
1205 tmux_args: tuple[str, ...] = ()
1206
1207 if direction:
1208 tmux_args += tuple(PANE_DIRECTION_FLAG_MAP[direction])
1209 else:
1210 tmux_args += tuple(PANE_DIRECTION_FLAG_MAP[PaneDirection.Below])
1211
1212 if size is not None and percentage is not None:
1213 msg = "Cannot specify both size and percentage"
1214 raise ValueError(msg)
1215
1216 if size is not None:
1217 tmux_args += (f"-l{size}",)
1218
1219 if percentage is not None:
1220 tmux_args += (f"-p{percentage}",)
1221
1222 if full_window_split:
1223 tmux_args += ("-f",)
1224
1225 if zoom:
1226 tmux_args += ("-Z",)
1227
1228 tmux_args += ("-P", "-F{}".format("".join(tmux_formats))) # output
1229
1230 if start_directory:
1231 start_path = pathlib.Path(start_directory).expanduser()
1232 tmux_args += (f"-c{start_path}",)
1233
1234 if not attach:
1235 tmux_args += ("-d",)
1236
1237 if environment:
1238 for k, v in environment.items():
1239 tmux_args += (f"-e{k}={v}",)
1240
1241 if empty:
1242 if has_gte_version("3.7", tmux_bin=self.server.tmux_bin):
1243 tmux_args += ("-E",)
1244 else:
1245 warnings.warn(
1246 "empty requires tmux 3.7+, ignoring",
1247 stacklevel=2,
1248 )
1249
1250 styling = {
1251 "-s": style,
1252 "-S": active_border_style,
1253 "-R": inactive_border_style,
1254 "-m": message,
1255 }
1256 if keep or any(v is not None for v in styling.values()):
1257 if has_gte_version("3.7", tmux_bin=self.server.tmux_bin):
1258 for flag, value in styling.items():
1259 if value is not None:
1260 tmux_args += (flag, value)
1261 if keep:
1262 tmux_args += ("-k",)
1263 else:
1264 warnings.warn(
1265 "style/border/message/keep on split require tmux 3.7+, ignoring",
1266 stacklevel=2,
1267 )
1268
1269 if shell:
1270 tmux_args += (shell,)
1271
1272 pane_cmd = self.cmd("split-window", *tmux_args, target=target)
1273
1274 if pane_cmd.stderr:
1275 if "pane too small" in pane_cmd.stderr:
1276 raise exc.LibTmuxException(pane_cmd.stderr)
1277
1278 raise exc.LibTmuxException(
1279 pane_cmd.stderr,
1280 self.__dict__,
1281 self.window.panes,
1282 )
1283
1284 pane_output = pane_cmd.stdout[0]
1285
1286 pane_formatters = dict(
1287 zip(["pane_id"], pane_output.split(FORMAT_SEPARATOR), strict=False),
1288 )
1289
1290 pane = self.from_pane_id(server=self.server, pane_id=pane_formatters["pane_id"])
1291
1292 extra: dict[str, str] = {
1293 "tmux_subcommand": "split-window",
1294 "tmux_pane": str(pane.pane_id),
1295 }
1296 if self.session.session_name is not None:
1297 extra["tmux_session"] = str(self.session.session_name)
1298 if self.window.window_name is not None:
1299 extra["tmux_window"] = str(self.window.window_name)
1300 if target is not None:
1301 extra["tmux_target"] = str(target)
1302
1303 logger.info("pane created", extra=extra)
1304
1305 return pane
1306
1307 def new_pane(
1308 self,
1309 /,
1310 target: int | str | None = None,
1311 start_directory: StrPath | None = None,
1312 attach: bool = False,
1313 shell: str | None = None,
1314 environment: dict[str, str] | None = None,
1315 width: int | None = None,
1316 height: int | None = None,
1317 x: int | None = None,
1318 y: int | None = None,
1319 zoom: bool | None = None,
1320 empty: bool | None = None,
1321 style: str | None = None,
1322 active_border_style: str | None = None,
1323 inactive_border_style: str | None = None,
1324 message: str | None = None,
1325 keep: bool | None = None,
1326 ) -> Pane:
1327 """Create a floating :class:`Pane` via ``$ tmux new-pane`` (tmux 3.7+).
1328
1329 Use :meth:`split` for a tiled pane. Floating panes sit above the tiled
1330 layout like a popup, but unlike a popup they are not modal and behave
1331 like normal panes. The returned pane has ``pane_floating_flag == "1"``.
1332
1333 Parameters
1334 ----------
1335 target : int or str, optional
1336 Custom *target-pane*, used by :meth:`Window.new_pane`.
1337 start_directory : str or PathLike, optional
1338 Working directory for the new pane (``-c`` flag).
1339 attach : bool, optional
1340 Make the new pane the active pane, default False (``-d`` when
1341 not attaching).
1342 shell : str, optional
1343 Command to run in the pane. The pane closes when it exits.
1344 environment : dict, optional
1345 Environment variables for the new pane (``-e`` flag).
1346 width : int, optional
1347 Width of the floating pane in cells (``-x`` flag).
1348 height : int, optional
1349 Height of the floating pane in cells (``-y`` flag).
1350 x : int, optional
1351 X position of the floating pane in cells (``-X`` flag).
1352 y : int, optional
1353 Y position of the floating pane in cells (``-Y`` flag).
1354 zoom : bool, optional
1355 Zoom the pane (``-Z`` flag).
1356 empty : bool, optional
1357 Create an empty pane with no command (``-E`` flag).
1358 style : str, optional
1359 Style for the floating pane (``-s`` flag).
1360 active_border_style : str, optional
1361 Border style when the pane is active (``-S`` flag).
1362 inactive_border_style : str, optional
1363 Border style when the pane is inactive (``-R`` flag).
1364 message : str, optional
1365 Keep the pane open (until a key is pressed) after the command
1366 exits, showing this ``remain-on-exit-format`` message (``-m`` flag).
1367 keep : bool, optional
1368 Keep the pane open until a key is pressed after the command exits
1369 (``-k`` flag), using the default ``remain-on-exit-format``.
1370
1371 Returns
1372 -------
1373 :class:`Pane`
1374 The newly created floating pane.
1375
1376 Raises
1377 ------
1378 :exc:`libtmux.exc.LibTmuxException`
1379 If the tmux server is older than 3.7 (``new-pane`` is unavailable).
1380
1381 Examples
1382 --------
1383 >>> from libtmux.common import has_gte_version
1384 >>> if has_gte_version("3.7"):
1385 ... floating = pane.new_pane(width=40, height=10, shell="sleep 5")
1386 ... is_floating = floating.pane_floating_flag
1387 ... else:
1388 ... is_floating = "1"
1389 >>> is_floating
1390 '1'
1391 """
1392 if not has_gte_version("3.7", tmux_bin=self.server.tmux_bin):
1393 msg = "new_pane (floating panes) requires tmux 3.7+"
1394 raise exc.LibTmuxException(msg)
1395
1396 tmux_formats = ["#{pane_id}" + FORMAT_SEPARATOR]
1397
1398 tmux_args: tuple[str, ...] = ()
1399
1400 if width is not None:
1401 tmux_args += (f"-x{width}",)
1402 if height is not None:
1403 tmux_args += (f"-y{height}",)
1404 if x is not None:
1405 tmux_args += (f"-X{x}",)
1406 if y is not None:
1407 tmux_args += (f"-Y{y}",)
1408 if zoom:
1409 tmux_args += ("-Z",)
1410 if style is not None:
1411 tmux_args += ("-s", style)
1412 if active_border_style is not None:
1413 tmux_args += ("-S", active_border_style)
1414 if inactive_border_style is not None:
1415 tmux_args += ("-R", inactive_border_style)
1416 if message is not None:
1417 tmux_args += ("-m", message)
1418 if keep:
1419 tmux_args += ("-k",)
1420
1421 tmux_args += ("-P", "-F{}".format("".join(tmux_formats))) # output
1422
1423 if start_directory:
1424 start_path = pathlib.Path(start_directory).expanduser()
1425 tmux_args += (f"-c{start_path}",)
1426
1427 if not attach:
1428 tmux_args += ("-d",)
1429
1430 if environment:
1431 for k, v in environment.items():
1432 tmux_args += (f"-e{k}={v}",)
1433
1434 if empty:
1435 tmux_args += ("-E",)
1436
1437 if shell:
1438 tmux_args += (shell,)
1439
1440 pane_cmd = self.cmd("new-pane", *tmux_args, target=target)
1441
1442 raise_if_stderr(pane_cmd, "new-pane")
1443
1444 pane_output = pane_cmd.stdout[0]
1445
1446 pane_formatters = dict(
1447 zip(["pane_id"], pane_output.split(FORMAT_SEPARATOR), strict=False),
1448 )
1449
1450 pane = self.from_pane_id(server=self.server, pane_id=pane_formatters["pane_id"])
1451
1452 extra: dict[str, str] = {
1453 "tmux_subcommand": "new-pane",
1454 "tmux_pane": str(pane.pane_id),
1455 }
1456 if self.session.session_name is not None:
1457 extra["tmux_session"] = str(self.session.session_name)
1458 if self.window.window_name is not None:
1459 extra["tmux_window"] = str(self.window.window_name)
1460 if target is not None:
1461 extra["tmux_target"] = str(target)
1462
1463 logger.info("floating pane created", extra=extra)
1464
1465 return pane
1466
1467 """
1468 Commands (helpers)
1469 """
1470
1471 def set_width(self, width: int) -> Pane:
1472 """Set pane width.
1473
1474 Parameters
1475 ----------
1476 width : int
1477 Pane width, in cells.
1478
1479 Returns
1480 -------
1481 :class:`Pane`
1482 Self, for method chaining.
1483 """
1484 self.resize(width=width)
1485 return self
1486
1487 def set_height(self, height: int) -> Pane:
1488 """Set pane height.
1489
1490 Parameters
1491 ----------
1492 height : int
1493 Pane height, in cells.
1494
1495 Returns
1496 -------
1497 :class:`Pane`
1498 Self, for method chaining.
1499 """
1500 self.resize(height=height)
1501 return self
1502
1503 def set_title(self, title: str) -> Pane:
1504 """Set pane title via ``select-pane -T``.
1505
1506 Parameters
1507 ----------
1508 title : str
1509 Title to set for the pane.
1510
1511 Returns
1512 -------
1513 :class:`Pane`
1514 The pane instance, for method chaining.
1515
1516 Examples
1517 --------
1518 >>> pane.set_title('my-title')
1519 Pane(...)
1520
1521 >>> pane.pane_title
1522 'my-title'
1523 """
1524 proc = self.cmd("select-pane", "-T", title)
1525 raise_if_stderr(proc, "select-pane")
1526 self.refresh()
1527 return self
1528
1529 def enter(self) -> Pane:
1530 """Send carriage return to pane.
1531
1532 ``$ tmux send-keys`` send Enter to the pane.
1533 """
1534 self.cmd("send-keys", "Enter")
1535 return self
1536
1537 def display_popup(
1538 self,
1539 command: str | None = None,
1540 *,
1541 close_on_exit: bool | None = None,
1542 close_on_success: bool | None = None,
1543 close_existing: bool | None = None,
1544 target_client: str | None = None,
1545 width: int | str | None = None,
1546 height: int | str | None = None,
1547 x: int | str | None = None,
1548 y: int | str | None = None,
1549 start_directory: StrPath | None = None,
1550 title: str | None = None,
1551 border_lines: str | None = None,
1552 style: str | None = None,
1553 border_style: str | None = None,
1554 environment: dict[str, str] | None = None,
1555 no_border: bool | None = None,
1556 close_on_any_key: bool | None = None,
1557 no_keys: bool | None = None,
1558 ) -> None:
1559 """Display a popup overlay via ``$ tmux display-popup``.
1560
1561 Requires tmux 3.2+ and an attached client. Use
1562 :class:`~libtmux._internal.control_mode.ControlMode` in tests to provide
1563 a client.
1564
1565 Parameters
1566 ----------
1567 command : str, optional
1568 Shell command to run in the popup.
1569 close_on_exit : bool, optional
1570 Close popup when command exits (``-E`` flag).
1571 close_on_success : bool, optional
1572 Close popup only on success exit code (``-EE`` flag, passing ``-E``
1573 twice).
1574 close_existing : bool, optional
1575 Close any existing popup on the client (``-C`` flag).
1576 target_client : str, optional
1577 Display the popup on this specific client (``-c`` flag).
1578 When omitted, tmux selects the client attached to this
1579 pane's session. With multiple clients attached, pass
1580 *target_client* to direct the popup at one of them.
1581 width : int or str, optional
1582 Popup width (``-w`` flag).
1583 height : int or str, optional
1584 Popup height (``-h`` flag).
1585 x : int or str, optional
1586 Popup x position (``-x`` flag).
1587 y : int or str, optional
1588 Popup y position (``-y`` flag).
1589 start_directory : str or PathLike, optional
1590 Working directory (``-d`` flag).
1591 title : str, optional
1592 Popup title (``-T`` flag). Requires tmux 3.3+.
1593 border_lines : str, optional
1594 Border line style (``-b`` flag). Requires tmux 3.3+.
1595 style : str, optional
1596 Popup style (``-s`` flag). Requires tmux 3.3+.
1597 border_style : str, optional
1598 Border style (``-S`` flag). Requires tmux 3.3+.
1599 environment : dict, optional
1600 Environment variables (``-e`` flag). Requires tmux 3.3+.
1601 no_border : bool, optional
1602 Open the popup without a border (``-B`` flag). If
1603 *border_lines* is also set, tmux ignores it. Requires tmux 3.3+.
1604 close_on_any_key : bool, optional
1605 Dismiss the popup on any key press once the inner
1606 command has exited (``-k`` flag). Requires tmux 3.6+.
1607 no_keys : bool, optional
1608 Do not auto-close the popup on any close-trigger keys
1609 (``-N`` flag). Requires tmux 3.6+.
1610
1611 Examples
1612 --------
1613 Not directly testable — popup rendering requires a TTY-backed client.
1614 Control-mode provides an attached client for invocation but the popup
1615 itself is not visible or verifiable.
1616
1617 >>> with control_mode() as ctl:
1618 ... pane.display_popup(command='true', close_on_exit=True)
1619 """
1620 if close_on_exit and close_on_success:
1621 msg = (
1622 "close_on_exit and close_on_success are mutually exclusive: "
1623 "use close_on_exit=True for -E (close on any exit) "
1624 "or close_on_success=True for -EE (close on zero exit code only)"
1625 )
1626 raise ValueError(msg)
1627
1628 tmux_args: tuple[str, ...] = ()
1629
1630 if close_existing:
1631 tmux_args += ("-C",)
1632
1633 if target_client is not None:
1634 tmux_args += ("-c", target_client)
1635
1636 if close_on_exit:
1637 tmux_args += ("-E",)
1638
1639 if close_on_success:
1640 tmux_args += ("-E", "-E")
1641
1642 if width is not None:
1643 tmux_args += ("-w", str(width))
1644
1645 if height is not None:
1646 tmux_args += ("-h", str(height))
1647
1648 if x is not None:
1649 tmux_args += ("-x", str(x))
1650
1651 if y is not None:
1652 tmux_args += ("-y", str(y))
1653
1654 if start_directory is not None:
1655 start_path = pathlib.Path(start_directory).expanduser()
1656 tmux_args += ("-d", str(start_path))
1657
1658 if title is not None:
1659 if has_gte_version("3.3", tmux_bin=self.server.tmux_bin):
1660 tmux_args += ("-T", title)
1661 else:
1662 warnings.warn(
1663 "title requires tmux 3.3+, ignoring",
1664 stacklevel=2,
1665 )
1666
1667 if border_lines is not None:
1668 if has_gte_version("3.3", tmux_bin=self.server.tmux_bin):
1669 tmux_args += ("-b", border_lines)
1670 else:
1671 warnings.warn(
1672 "border_lines requires tmux 3.3+, ignoring",
1673 stacklevel=2,
1674 )
1675
1676 if style is not None:
1677 if has_gte_version("3.3", tmux_bin=self.server.tmux_bin):
1678 tmux_args += ("-s", style)
1679 else:
1680 warnings.warn(
1681 "style requires tmux 3.3+, ignoring",
1682 stacklevel=2,
1683 )
1684
1685 if border_style is not None:
1686 if has_gte_version("3.3", tmux_bin=self.server.tmux_bin):
1687 tmux_args += ("-S", border_style)
1688 else:
1689 warnings.warn(
1690 "border_style requires tmux 3.3+, ignoring",
1691 stacklevel=2,
1692 )
1693
1694 if environment:
1695 if has_gte_version("3.3", tmux_bin=self.server.tmux_bin):
1696 for k, v in environment.items():
1697 tmux_args += (f"-e{k}={v}",)
1698 else:
1699 warnings.warn(
1700 "environment requires tmux 3.3+, ignoring",
1701 stacklevel=2,
1702 )
1703
1704 if no_border:
1705 if has_gte_version("3.3", tmux_bin=self.server.tmux_bin):
1706 tmux_args += ("-B",)
1707 else:
1708 warnings.warn(
1709 "no_border requires tmux 3.3+, ignoring",
1710 stacklevel=2,
1711 )
1712
1713 if close_on_any_key:
1714 if has_gte_version("3.6", tmux_bin=self.server.tmux_bin):
1715 tmux_args += ("-k",)
1716 else:
1717 warnings.warn(
1718 "close_on_any_key requires tmux 3.6+, ignoring",
1719 stacklevel=2,
1720 )
1721
1722 if no_keys:
1723 if has_gte_version("3.6", tmux_bin=self.server.tmux_bin):
1724 tmux_args += ("-N",)
1725 else:
1726 warnings.warn(
1727 "no_keys requires tmux 3.6+, ignoring",
1728 stacklevel=2,
1729 )
1730
1731 if command is not None:
1732 tmux_args += (command,)
1733
1734 proc = self.cmd("display-popup", *tmux_args)
1735
1736 raise_if_stderr(proc, "display-popup")
1737
1738 def paste_buffer(
1739 self,
1740 *,
1741 buffer_name: str | None = None,
1742 delete_after: bool | None = None,
1743 linefeed_separator: bool | None = None,
1744 bracket: bool | None = None,
1745 separator: str | None = None,
1746 no_vis: bool | None = None,
1747 ) -> None:
1748 """Paste a buffer into the pane via ``$ tmux paste-buffer``.
1749
1750 Parameters
1751 ----------
1752 buffer_name : str, optional
1753 Name of the buffer to paste (``-b`` flag).
1754 delete_after : bool, optional
1755 Delete the buffer after pasting (``-d`` flag).
1756 linefeed_separator : bool, optional
1757 Use newline as the line separator instead of carriage return
1758 (``-r`` flag).
1759 bracket : bool, optional
1760 Use bracketed paste mode (``-p`` flag).
1761 separator : str, optional
1762 Separator between lines (``-s`` flag).
1763 no_vis : bool, optional
1764 Paste the buffer's raw bytes without passing them through
1765 ``vis(3)`` escaping (``-S`` flag). tmux 3.7 escapes pasted
1766 content by default; set this to restore the raw behaviour.
1767 Requires tmux 3.7+. If used with tmux < 3.7, a warning is issued
1768 and the flag is ignored.
1769
1770 Examples
1771 --------
1772 >>> server.set_buffer('pasted_text')
1773 >>> pane.paste_buffer()
1774 """
1775 tmux_args: tuple[str, ...] = ()
1776
1777 if delete_after:
1778 tmux_args += ("-d",)
1779
1780 if linefeed_separator:
1781 tmux_args += ("-r",)
1782
1783 if bracket:
1784 tmux_args += ("-p",)
1785
1786 if buffer_name is not None:
1787 tmux_args += ("-b", buffer_name)
1788
1789 if separator is not None:
1790 tmux_args += ("-s", separator)
1791
1792 if no_vis:
1793 if has_gte_version("3.7", tmux_bin=self.server.tmux_bin):
1794 tmux_args += ("-S",)
1795 else:
1796 warnings.warn(
1797 "no_vis requires tmux 3.7+, ignoring",
1798 stacklevel=2,
1799 )
1800
1801 proc = self.cmd("paste-buffer", *tmux_args)
1802
1803 raise_if_stderr(proc, "paste-buffer")
1804
1805 def pipe(
1806 self,
1807 command: str | None = None,
1808 *,
1809 output_only: bool | None = None,
1810 input_only: bool | None = None,
1811 toggle: bool | None = None,
1812 ) -> None:
1813 """Pipe pane output to a shell command via ``$ tmux pipe-pane``.
1814
1815 Parameters
1816 ----------
1817 command : str, optional
1818 Shell command to pipe to. If None, stops piping.
1819 output_only : bool, optional
1820 Only pipe output from the pane (``-O`` flag).
1821 input_only : bool, optional
1822 Only pipe input to the pane (``-I`` flag).
1823 toggle : bool, optional
1824 Toggle piping on/off (``-o`` flag).
1825
1826 Examples
1827 --------
1828 >>> pane.pipe('cat >> /tmp/output.txt')
1829
1830 Stop piping:
1831
1832 >>> pane.pipe()
1833 """
1834 tmux_args: tuple[str, ...] = ()
1835
1836 if output_only:
1837 tmux_args += ("-O",)
1838
1839 if input_only:
1840 tmux_args += ("-I",)
1841
1842 if toggle:
1843 tmux_args += ("-o",)
1844
1845 if command is not None:
1846 tmux_args += (command,)
1847
1848 proc = self.cmd("pipe-pane", *tmux_args)
1849
1850 raise_if_stderr(proc, "pipe-pane")
1851
1852 def copy_mode(
1853 self,
1854 *,
1855 scroll_up: bool | None = None,
1856 exit_on_bottom: bool | None = None,
1857 mouse_drag: bool | None = None,
1858 cancel: bool | None = None,
1859 page_down: bool | None = None,
1860 source_pane: str | None = None,
1861 ) -> None:
1862 """Enter copy mode via ``$ tmux copy-mode``.
1863
1864 Parameters
1865 ----------
1866 scroll_up : bool, optional
1867 Start scrolled up one page (``-u`` flag).
1868 exit_on_bottom : bool, optional
1869 Exit copy mode when scrolling reaches the bottom of the
1870 history (``-e`` flag).
1871 mouse_drag : bool, optional
1872 Start mouse drag (``-M`` flag).
1873 cancel : bool, optional
1874 Cancel copy mode and any other modes (``-q`` flag).
1875 page_down : bool, optional
1876 Scroll a page down if already in copy mode (``-d`` flag).
1877 Requires tmux 3.5+.
1878 source_pane : str, optional
1879 Source pane whose contents should be displayed in copy
1880 mode (``-s`` flag). Lets you scroll/copy from another
1881 pane's history. Requires tmux 3.2+.
1882
1883 Examples
1884 --------
1885 >>> pane.copy_mode()
1886 """
1887 tmux_args: tuple[str, ...] = ()
1888
1889 if scroll_up:
1890 tmux_args += ("-u",)
1891
1892 if exit_on_bottom:
1893 tmux_args += ("-e",)
1894
1895 if mouse_drag:
1896 tmux_args += ("-M",)
1897
1898 if page_down:
1899 if has_gte_version("3.5", tmux_bin=self.server.tmux_bin):
1900 tmux_args += ("-d",)
1901 else:
1902 warnings.warn(
1903 "page_down requires tmux 3.5+, ignoring",
1904 stacklevel=2,
1905 )
1906
1907 if source_pane is not None:
1908 tmux_args += ("-s", source_pane)
1909
1910 if cancel:
1911 tmux_args += ("-q",)
1912
1913 proc = self.cmd("copy-mode", *tmux_args)
1914
1915 raise_if_stderr(proc, "copy-mode")
1916
1917 def clock_mode(self) -> None:
1918 """Enter clock mode via ``$ tmux clock-mode``.
1919
1920 >>> pane.clock_mode()
1921 """
1922 proc = self.cmd("clock-mode")
1923
1924 raise_if_stderr(proc, "clock-mode")
1925
1926 def display_panes(
1927 self,
1928 *,
1929 duration: int | None = None,
1930 no_select: bool | None = None,
1931 ) -> None:
1932 """Show pane numbers via ``$ tmux display-panes``.
1933
1934 Requires an attached client.
1935
1936 Parameters
1937 ----------
1938 duration : int, optional
1939 Duration in milliseconds to display pane numbers (``-d`` flag).
1940 no_select : bool, optional
1941 Do not select a pane on keypress (``-N`` flag).
1942
1943 Examples
1944 --------
1945 >>> with control_mode() as ctl:
1946 ... window.active_pane.display_panes()
1947 """
1948 tmux_args: tuple[str, ...] = ()
1949
1950 if duration is not None:
1951 tmux_args += ("-d", str(duration))
1952
1953 if no_select:
1954 tmux_args += ("-N",)
1955
1956 proc = self.server.cmd("display-panes", *tmux_args)
1957
1958 raise_if_stderr(proc, "display-panes")
1959
1960 def choose_buffer(self) -> None:
1961 """Enter buffer chooser via ``$ tmux choose-buffer``.
1962
1963 >>> pane.choose_buffer()
1964 """
1965 proc = self.cmd("choose-buffer")
1966
1967 raise_if_stderr(proc, "choose-buffer")
1968
1969 def choose_client(self) -> None:
1970 """Enter client chooser via ``$ tmux choose-client``.
1971
1972 >>> pane.choose_client()
1973 """
1974 proc = self.cmd("choose-client")
1975
1976 raise_if_stderr(proc, "choose-client")
1977
1978 def choose_tree(
1979 self,
1980 *,
1981 sessions_collapsed: bool | None = None,
1982 windows_collapsed: bool | None = None,
1983 format_string: str | None = None,
1984 filter_expression: str | None = None,
1985 sort_order: t.Literal["index", "name", "time", "size"] | None = None,
1986 reverse: bool | None = None,
1987 zoom: bool | None = None,
1988 ) -> None:
1989 """Enter tree chooser via ``$ tmux choose-tree``.
1990
1991 Parameters
1992 ----------
1993 sessions_collapsed : bool, optional
1994 Start with sessions collapsed (``-s`` flag).
1995 windows_collapsed : bool, optional
1996 Start with windows collapsed (``-w`` flag).
1997 format_string : str, optional
1998 Format for each item shown in the chooser (``-F`` flag).
1999 filter_expression : str, optional
2000 Filter expression evaluated per item; only items whose
2001 filter expands non-zero are shown (``-f`` flag).
2002 sort_order : str, optional
2003 Sort field (``-O`` flag).
2004 reverse : bool, optional
2005 Reverse the sort order (``-r`` flag).
2006 zoom : bool, optional
2007 Zoom the pane while the chooser is active (``-Z`` flag).
2008
2009 Examples
2010 --------
2011 >>> pane.choose_tree()
2012 """
2013 tmux_args: tuple[str, ...] = ()
2014
2015 if sessions_collapsed:
2016 tmux_args += ("-s",)
2017
2018 if windows_collapsed:
2019 tmux_args += ("-w",)
2020
2021 if zoom:
2022 tmux_args += ("-Z",)
2023
2024 if reverse:
2025 tmux_args += ("-r",)
2026
2027 if format_string is not None:
2028 tmux_args += ("-F", format_string)
2029
2030 if filter_expression is not None:
2031 tmux_args += ("-f", filter_expression)
2032
2033 if sort_order is not None:
2034 tmux_args += ("-O", sort_order)
2035
2036 proc = self.cmd("choose-tree", *tmux_args)
2037
2038 raise_if_stderr(proc, "choose-tree")
2039
2040 def customize_mode(self) -> None:
2041 """Enter customize mode via ``$ tmux customize-mode``.
2042
2043 >>> pane.customize_mode()
2044 """
2045 proc = self.cmd("customize-mode")
2046
2047 raise_if_stderr(proc, "customize-mode")
2048
2049 def find_window(
2050 self,
2051 match_string: str,
2052 *,
2053 match_content: bool | None = None,
2054 case_insensitive: bool | None = None,
2055 match_name: bool | None = None,
2056 regex: bool | None = None,
2057 match_title: bool | None = None,
2058 ) -> None:
2059 """Search for a window matching a string via ``$ tmux find-window``.
2060
2061 Opens a choose-tree filtered to matching windows.
2062
2063 Parameters
2064 ----------
2065 match_string : str
2066 String to search for in window names, titles, and content.
2067 match_content : bool, optional
2068 Match visible pane content (``-C`` flag).
2069 case_insensitive : bool, optional
2070 Case-insensitive matching (``-i`` flag).
2071 match_name : bool, optional
2072 Match window name only (``-N`` flag).
2073 regex : bool, optional
2074 Treat match string as a regex (``-r`` flag).
2075 match_title : bool, optional
2076 Match pane title (``-T`` flag).
2077
2078 Examples
2079 --------
2080 >>> pane.find_window('sh')
2081 """
2082 tmux_args: tuple[str, ...] = ()
2083
2084 if match_content:
2085 tmux_args += ("-C",)
2086
2087 if case_insensitive:
2088 tmux_args += ("-i",)
2089
2090 if match_name:
2091 tmux_args += ("-N",)
2092
2093 if regex:
2094 tmux_args += ("-r",)
2095
2096 if match_title:
2097 tmux_args += ("-T",)
2098
2099 tmux_args += (match_string,)
2100
2101 proc = self.cmd("find-window", *tmux_args)
2102
2103 raise_if_stderr(proc, "find-window")
2104
2105 def send_prefix(self, *, secondary: bool | None = None) -> None:
2106 """Send the prefix key to the pane via ``$ tmux send-prefix``.
2107
2108 Parameters
2109 ----------
2110 secondary : bool, optional
2111 Send the secondary prefix key (``-2`` flag).
2112
2113 Examples
2114 --------
2115 >>> pane.send_prefix()
2116 """
2117 tmux_args: tuple[str, ...] = ()
2118
2119 if secondary:
2120 tmux_args += ("-2",)
2121
2122 proc = self.cmd("send-prefix", *tmux_args)
2123
2124 raise_if_stderr(proc, "send-prefix")
2125
2126 def respawn(
2127 self,
2128 *,
2129 shell: str | None = None,
2130 start_directory: StrPath | None = None,
2131 environment: dict[str, str] | None = None,
2132 kill: bool | None = None,
2133 ) -> None:
2134 """Respawn the pane process via ``$ tmux respawn-pane``.
2135
2136 Parameters
2137 ----------
2138 shell : str, optional
2139 Shell command to run in the respawned pane.
2140 start_directory : str or PathLike, optional
2141 Working directory for the respawned pane (``-c`` flag).
2142 environment : dict, optional
2143 Environment variables (``-e`` flag).
2144 kill : bool, optional
2145 Kill the current process before respawning (``-k`` flag).
2146 Required if the pane is still active.
2147
2148 Examples
2149 --------
2150 >>> pane = window.split(shell='sleep 1m')
2151 >>> pane.respawn(kill=True, shell='sh')
2152 """
2153 tmux_args: tuple[str, ...] = ()
2154
2155 if kill:
2156 tmux_args += ("-k",)
2157
2158 if start_directory is not None:
2159 start_path = pathlib.Path(start_directory).expanduser()
2160 tmux_args += (f"-c{start_path}",)
2161
2162 if environment:
2163 for k, v in environment.items():
2164 tmux_args += (f"-e{k}={v}",)
2165
2166 if shell:
2167 tmux_args += (shell,)
2168
2169 proc = self.cmd("respawn-pane", *tmux_args)
2170
2171 raise_if_stderr(proc, "respawn-pane")
2172
2173 def move(
2174 self,
2175 target: str | Pane | Window,
2176 *,
2177 vertical: bool = True,
2178 detach: bool = True,
2179 full_window: bool | None = None,
2180 size: str | int | None = None,
2181 before: bool | None = None,
2182 ) -> None:
2183 """Move this pane to another window via ``$ tmux move-pane``.
2184
2185 Similar to :meth:`join` but invokes the ``move-pane`` command directly.
2186
2187 Parameters
2188 ----------
2189 target : str, Pane, or Window
2190 Target pane or window to move into.
2191 vertical : bool, optional
2192 Split vertically (``-v`` flag), default True. False for
2193 horizontal (``-h``).
2194 detach : bool, optional
2195 Do not switch to the target window (``-d`` flag), default True.
2196 full_window : bool, optional
2197 Use the full window width/height (``-f`` flag).
2198 size : str or int, optional
2199 Size for the moved pane (``-l`` flag).
2200 before : bool, optional
2201 Place the pane before the target (``-b`` flag).
2202
2203 Examples
2204 --------
2205 >>> pane_to_move = window.split(shell='sleep 1m')
2206 >>> w2 = session.new_window(window_name='move_target')
2207 >>> pane_to_move.move(w2)
2208 """
2209 tmux_args: tuple[str, ...] = ()
2210
2211 if vertical:
2212 tmux_args += ("-v",)
2213 else:
2214 tmux_args += ("-h",)
2215
2216 if detach:
2217 tmux_args += ("-d",)
2218
2219 if full_window:
2220 tmux_args += ("-f",)
2221
2222 if size is not None:
2223 tmux_args += (f"-l{size}",)
2224
2225 if before:
2226 tmux_args += ("-b",)
2227
2228 from libtmux.window import Window
2229
2230 if isinstance(target, Pane):
2231 target_id = str(target.pane_id)
2232 elif isinstance(target, Window):
2233 target_id = str(target.window_id)
2234 else:
2235 target_id = target
2236
2237 tmux_args += ("-s", str(self.pane_id), "-t", target_id)
2238
2239 # Use server.cmd to avoid auto-adding -t from self.cmd
2240 proc = self.server.cmd("move-pane", *tmux_args)
2241
2242 raise_if_stderr(proc, "move-pane")
2243
2244 def join(
2245 self,
2246 target: str | Pane | Window,
2247 *,
2248 vertical: bool = True,
2249 detach: bool = True,
2250 full_window: bool | None = None,
2251 size: str | int | None = None,
2252 before: bool | None = None,
2253 ) -> None:
2254 """Join this pane into another window/pane via ``$ tmux join-pane``.
2255
2256 This is the inverse of :meth:`break_pane`.
2257
2258 Parameters
2259 ----------
2260 target : str, Pane, or Window
2261 Target pane or window to join into.
2262 vertical : bool, optional
2263 Join vertically (``-v`` flag), default True. Set to False for
2264 horizontal (``-h``).
2265 detach : bool, optional
2266 Do not switch to the target window (``-d`` flag), default True.
2267 full_window : bool, optional
2268 Join spanning the full window width/height (``-f`` flag).
2269 size : str or int, optional
2270 Size for the joined pane (``-l`` flag).
2271 before : bool, optional
2272 Place the pane before the target (``-b`` flag).
2273
2274 Examples
2275 --------
2276 >>> pane_to_join = window.split(shell='sleep 1m')
2277 >>> new_window = pane_to_join.break_pane()
2278 >>> pane_to_join.join(window)
2279 """
2280 tmux_args: tuple[str, ...] = ()
2281
2282 if vertical:
2283 tmux_args += ("-v",)
2284 else:
2285 tmux_args += ("-h",)
2286
2287 if detach:
2288 tmux_args += ("-d",)
2289
2290 if full_window:
2291 tmux_args += ("-f",)
2292
2293 if size is not None:
2294 tmux_args += (f"-l{size}",)
2295
2296 if before:
2297 tmux_args += ("-b",)
2298
2299 from libtmux.window import Window
2300
2301 if isinstance(target, Pane):
2302 target_id = str(target.pane_id)
2303 elif isinstance(target, Window):
2304 target_id = str(target.window_id)
2305 else:
2306 target_id = target
2307
2308 tmux_args += ("-s", str(self.pane_id), "-t", target_id)
2309
2310 # Use server.cmd to avoid auto-adding -t from self.cmd
2311 proc = self.server.cmd("join-pane", *tmux_args)
2312
2313 raise_if_stderr(proc, "join-pane")
2314
2315 def break_pane(
2316 self,
2317 *,
2318 detach: bool = True,
2319 window_name: str | None = None,
2320 ) -> Window:
2321 """Break this pane out into a new window via ``$ tmux break-pane``.
2322
2323 Parameters
2324 ----------
2325 detach : bool, optional
2326 Do not switch to the new window (``-d`` flag), default True.
2327 window_name : str, optional
2328 Name for the new window (``-n`` flag).
2329
2330 Returns
2331 -------
2332 :class:`Window`
2333 The newly created window containing the pane.
2334
2335 Examples
2336 --------
2337 >>> pane_to_break = window.split(shell='sleep 1m')
2338 >>> new_window = pane_to_break.break_pane(window_name='broken')
2339 >>> new_window.window_name
2340 'broken'
2341 """
2342 # tmux 3.7 segfaults break-pane when -n is absent and ignores -n when
2343 # given (NULL-deref); 3.7a reverted it. When needed, pass a placeholder
2344 # -n then set the real name via rename-window below. Compare the raw
2345 # version string to gate the workaround on the literal 3.7 release only.
2346 breaks_without_name = get_version_str(tmux_bin=self.server.tmux_bin) == "3.7"
2347
2348 tmux_args: tuple[str, ...] = ("-P", "-F#{window_id}")
2349
2350 if detach:
2351 tmux_args += ("-d",)
2352
2353 if window_name is not None:
2354 tmux_args += ("-n", window_name)
2355 elif breaks_without_name:
2356 tmux_args += ("-n", "libtmux")
2357
2358 tmux_args += ("-s", str(self.pane_id))
2359
2360 # Use server.cmd to avoid auto-adding -t from self.cmd
2361 proc = self.server.cmd("break-pane", *tmux_args)
2362
2363 raise_if_stderr(proc, "break-pane")
2364
2365 window_id = proc.stdout[0].strip()
2366
2367 from libtmux.window import Window
2368
2369 window = Window.from_window_id(server=self.server, window_id=window_id)
2370
2371 if window_name is not None and breaks_without_name:
2372 window.rename_window(window_name)
2373
2374 return window
2375
2376 def swap(
2377 self,
2378 target: str | Pane | None = None,
2379 *,
2380 detach: bool | None = None,
2381 move_up: bool | None = None,
2382 move_down: bool | None = None,
2383 keep_zoom: bool | None = None,
2384 ) -> None:
2385 """Swap this pane with another via ``$ tmux swap-pane``.
2386
2387 Parameters
2388 ----------
2389 target : str or Pane, optional
2390 Target pane to swap with. Can be a pane ID string or Pane object.
2391 Mutually exclusive with *move_up* / *move_down*.
2392
2393 .. versionchanged:: 0.56
2394 Now optional; required only when *move_up* / *move_down* are
2395 not set.
2396 detach : bool, optional
2397 Do not change the active pane (``-d`` flag).
2398 move_up : bool, optional
2399 Swap with the pane above (``-U`` flag). Mutually exclusive with
2400 *target* and *move_down*.
2401 move_down : bool, optional
2402 Swap with the pane below (``-D`` flag). Mutually exclusive with
2403 *target* and *move_up*.
2404 keep_zoom : bool, optional
2405 Keep the window zoomed if it was zoomed (``-Z`` flag).
2406
2407 Examples
2408 --------
2409 >>> pane1 = window.active_pane
2410 >>> pane2 = window.split()
2411 >>> pane1_id, pane2_id = pane1.pane_id, pane2.pane_id
2412 >>> pane1.swap(pane2)
2413 >>> pane1.refresh()
2414 >>> pane2.refresh()
2415 """
2416 if move_up and move_down:
2417 msg = "move_up and move_down are mutually exclusive"
2418 raise exc.LibTmuxException(msg)
2419
2420 if target is not None and (move_up or move_down):
2421 msg = "target is mutually exclusive with move_up/move_down"
2422 raise exc.LibTmuxException(msg)
2423
2424 if target is None and not move_up and not move_down:
2425 msg = "swap requires target or move_up=True or move_down=True"
2426 raise exc.LibTmuxException(msg)
2427
2428 tmux_args: tuple[str, ...] = ()
2429
2430 if detach:
2431 tmux_args += ("-d",)
2432
2433 if move_up:
2434 tmux_args += ("-U",)
2435
2436 if move_down:
2437 tmux_args += ("-D",)
2438
2439 if keep_zoom:
2440 tmux_args += ("-Z",)
2441
2442 if target is not None:
2443 target_id = target.pane_id if isinstance(target, Pane) else target
2444 tmux_args += ("-s", str(target_id))
2445
2446 proc = self.cmd("swap-pane", *tmux_args)
2447
2448 raise_if_stderr(proc, "swap-pane")
2449
2450 def clear_history(self, *, reset_hyperlinks: bool | None = None) -> None:
2451 """Clear pane history buffer via ``$ tmux clear-history``.
2452
2453 Parameters
2454 ----------
2455 reset_hyperlinks : bool, optional
2456 Also reset hyperlinks (``-H`` flag). Requires tmux 3.4+.
2457
2458 .. versionadded:: 0.56
2459
2460 Examples
2461 --------
2462 >>> pane.clear_history()
2463 """
2464 tmux_args: tuple[str, ...] = ()
2465
2466 if reset_hyperlinks:
2467 if has_gte_version("3.4", tmux_bin=self.server.tmux_bin):
2468 tmux_args += ("-H",)
2469 else:
2470 warnings.warn(
2471 "reset_hyperlinks requires tmux 3.4+, ignoring",
2472 stacklevel=2,
2473 )
2474
2475 proc = self.cmd("clear-history", *tmux_args)
2476
2477 raise_if_stderr(proc, "clear-history")
2478
2479 def clear(self) -> Pane:
2480 """Clear pane."""
2481 self.send_keys("reset")
2482 return self
2483
2484 def reset(self) -> Pane:
2485 r"""Reset terminal state and clear pane history.
2486
2487 Sends ``send-keys -R`` and ``clear-history`` to the pane in one
2488 targeted tmux command sequence so output cannot land in the
2489 freshly-cleared grid between the terminal-state reset and the
2490 history clear.
2491
2492 Examples
2493 --------
2494 >>> pane.reset()
2495 Pane(%... Window(@... ...:..., Session($1 libtmux_...)))
2496 """
2497 self.server.cmd(
2498 "send-keys",
2499 "-t",
2500 self.pane_id,
2501 "-R",
2502 ";",
2503 "clear-history",
2504 "-t",
2505 self.pane_id,
2506 )
2507 return self
2508
2509 #
2510 # Dunder
2511 #
2512 def __eq__(self, other: object) -> bool:
2513 """Equal operator for :class:`Pane` object."""
2514 if isinstance(other, Pane):
2515 return self.pane_id == other.pane_id
2516 return False
2517
2518 def __repr__(self) -> str:
2519 """Representation of :class:`Pane` object."""
2520 return f"{self.__class__.__name__}({self.pane_id} {self.window})"
2521
2522 #
2523 # Aliases
2524 #
2525 @property
2526 def id(self) -> str | None:
2527 """Alias of :attr:`Pane.pane_id`.
2528
2529 >>> pane.id
2530 '%1'
2531
2532 >>> pane.id == pane.pane_id
2533 True
2534 """
2535 return self.pane_id
2536
2537 @property
2538 def index(self) -> str | None:
2539 """Alias of :attr:`Pane.pane_index`.
2540
2541 >>> pane.index
2542 '0'
2543
2544 >>> pane.index == pane.pane_index
2545 True
2546 """
2547 return self.pane_index
2548
2549 @property
2550 def height(self) -> str | None:
2551 """Alias of :attr:`Pane.pane_height`.
2552
2553 >>> pane.height.isdigit()
2554 True
2555
2556 >>> pane.height == pane.pane_height
2557 True
2558 """
2559 return self.pane_height
2560
2561 @property
2562 def width(self) -> str | None:
2563 """Alias of :attr:`Pane.pane_width`.
2564
2565 >>> pane.width.isdigit()
2566 True
2567
2568 >>> pane.width == pane.pane_width
2569 True
2570 """
2571 return self.pane_width
2572
2573 @property
2574 def title(self) -> str | None:
2575 """Alias for :attr:`pane_title`.
2576
2577 >>> pane.set_title('test-alias')
2578 Pane(...)
2579
2580 >>> pane.title == pane.pane_title
2581 True
2582 """
2583 return self.pane_title
2584
2585 @property
2586 def at_top(self) -> bool:
2587 """Typed, converted wrapper around :attr:`Pane.pane_at_top`.
2588
2589 >>> pane.pane_at_top
2590 '1'
2591
2592 >>> pane.at_top
2593 True
2594 """
2595 return self.pane_at_top == "1"
2596
2597 @property
2598 def at_bottom(self) -> bool:
2599 """Typed, converted wrapper around :attr:`Pane.pane_at_bottom`.
2600
2601 >>> pane.pane_at_bottom
2602 '1'
2603
2604 >>> pane.at_bottom
2605 True
2606 """
2607 return self.pane_at_bottom == "1"
2608
2609 @property
2610 def at_left(self) -> bool:
2611 """Typed, converted wrapper around :attr:`Pane.pane_at_left`.
2612
2613 >>> pane.pane_at_left
2614 '1'
2615
2616 >>> pane.at_left
2617 True
2618 """
2619 return self.pane_at_left == "1"
2620
2621 @property
2622 def at_right(self) -> bool:
2623 """Typed, converted wrapper around :attr:`Pane.pane_at_right`.
2624
2625 >>> pane.pane_at_right
2626 '1'
2627
2628 >>> pane.at_right
2629 True
2630 """
2631 return self.pane_at_right == "1"
2632
2633 #
2634 # Legacy: Redundant stuff we want to remove
2635 #
2636 def split_window(
2637 self,
2638 target: int | str | None = None,
2639 attach: bool = False,
2640 start_directory: StrPath | None = None,
2641 vertical: bool = True,
2642 shell: str | None = None,
2643 size: str | int | None = None,
2644 percent: int | None = None, # deprecated
2645 environment: dict[str, str] | None = None,
2646 ) -> Pane: # New Pane, not self
2647 """Split window at pane and return newly created :class:`Pane`.
2648
2649 Parameters
2650 ----------
2651 attach : bool, optional
2652 Attach / select pane after creation.
2653 start_directory : str or PathLike, optional
2654 specifies the working directory in which the new pane is created.
2655 vertical : bool, optional
2656 split vertically
2657 percent: int, optional
2658 percentage to occupy with respect to current pane
2659 environment: dict, optional
2660 Environmental variables for new pane. Passthrough to ``-e``.
2661
2662 Notes
2663 -----
2664 .. deprecated:: 0.33
2665
2666 Deprecated in favor of :meth:`.split`.
2667 """
2668 raise exc.DeprecatedError(
2669 deprecated="Pane.split_window()",
2670 replacement="Pane.split()",
2671 version="0.33.0",
2672 )
2673
2674 def get(self, key: str, default: t.Any | None = None) -> t.Any:
2675 """Return key-based lookup. Deprecated by attributes.
2676
2677 .. deprecated:: 0.17
2678
2679 Deprecated by attribute lookup, e.g. ``pane['window_name']`` is now
2680 accessed via ``pane.window_name``.
2681
2682 """
2683 raise exc.DeprecatedError(
2684 deprecated="Pane.get()",
2685 replacement="direct attribute access (e.g., pane.pane_id)",
2686 version="0.17.0",
2687 )
2688
2689 def __getitem__(self, key: str) -> t.Any:
2690 """Return item lookup by key. Deprecated in favor of attributes.
2691
2692 .. deprecated:: 0.17
2693
2694 Deprecated in favor of attributes. e.g. ``pane['window_name']`` is now
2695 accessed via ``pane.window_name``.
2696
2697 """
2698 raise exc.DeprecatedError(
2699 deprecated="Pane[key] lookup",
2700 replacement="direct attribute access (e.g., pane.pane_id)",
2701 version="0.17.0",
2702 )
2703
2704 def resize_pane(
2705 self,
2706 # Adjustments
2707 adjustment_direction: ResizeAdjustmentDirection | None = None,
2708 adjustment: int | None = None,
2709 # Manual
2710 height: str | int | None = None,
2711 width: str | int | None = None,
2712 # Zoom
2713 zoom: bool | None = None,
2714 # Mouse
2715 mouse: bool | None = None,
2716 # Optional flags
2717 trim_below: bool | None = None,
2718 ) -> Pane:
2719 """Resize pane, deprecated by :meth:`Pane.resize`.
2720
2721 .. deprecated:: 0.28
2722
2723 Deprecated by :meth:`Pane.resize`.
2724 """
2725 raise exc.DeprecatedError(
2726 deprecated="Pane.resize_pane()",
2727 replacement="Pane.resize()",
2728 version="0.28.0",
2729 )