Debian Codegraph @

src/libtmux/server.py

raw symbols SCIP
1 """Wrapper for :term:`tmux(1)` server.
2
3 libtmux.server
4 ~~~~~~~~~~~~~~
5
6 """
7
8 from __future__ import annotations
9
10 import logging
11 import os
12 import pathlib
13 import shutil
14 import subprocess
15 import typing as t
16 import warnings
17
18 from libtmux import exc
19 from libtmux._internal.query_list import QueryList
20 from libtmux.client import Client
21 from libtmux.common import get_version, has_gte_version, raise_if_stderr, tmux_cmd
22 from libtmux.constants import OptionScope
23 from libtmux.hooks import HooksMixin
24 from libtmux.neo import fetch_objs, get_output_format, parse_output
25 from libtmux.pane import Pane
26 from libtmux.session import Session
27 from libtmux.window import Window
28
29 from .common import (
30 EnvironmentMixin,
31 PaneDict,
32 SessionDict,
33 WindowDict,
34 session_check_name,
35 )
36 from .options import OptionsMixin
37
38 if t.TYPE_CHECKING:
39 import types
40 from typing import TypeAlias
41
42 from typing_extensions import Self
43
44 from libtmux._internal.types import StrPath
45
46 DashLiteral: TypeAlias = t.Literal["-"]
47
48 logger = logging.getLogger(__name__)
49
50
51 def _is_daemon_not_up_error(stderr_text: str) -> bool:
52 """Return True if the error indicates the tmux server is not running.
53
54 tmux signals this in two ways:
55 1. "no server running" (socket exists but no daemon is listening)
56 2. "error connecting to ... (No such file or directory)" (socket file is missing)
57 """
58 return "no server running" in stderr_text or (
59 "error connecting to" in stderr_text
60 and "No such file or directory" in stderr_text
61 )
62
63
64 def _fetch_or_empty(
65 server: Server,
66 list_cmd: str,
67 **kwargs: t.Any,
68 ) -> list[dict[str, t.Any]]:
69 """Wrap :func:`fetch_objs`: treat a not-yet-started server as empty.
70
71 A fresh :class:`~libtmux.Server` can be introspected via
72 :attr:`Server.sessions`, :attr:`Server.windows`, etc. before the
73 daemon is up. Other tmux errors, such as socket permission
74 failures, still propagate.
75 """
76 try:
77 return fetch_objs(server=server, list_cmd=list_cmd, **kwargs) # type: ignore[arg-type]
78 except exc.LibTmuxException as e:
79 if e.args and _is_daemon_not_up_error(str(e.args[0])):
80 return []
81 raise
82
83
84 class Server(
85 EnvironmentMixin,
86 OptionsMixin,
87 HooksMixin,
88 ):
89 """:term:`tmux(1)` :term:`Server` [server_manual]_.
90
91 - :attr:`Server.sessions` [:class:`Session`, ...]
92
93 - :attr:`Session.windows` [:class:`Window`, ...]
94
95 - :attr:`Window.panes` [:class:`Pane`, ...]
96
97 - :class:`Pane`
98
99 When instantiated stores information on live, running tmux server.
100
101 Parameters
102 ----------
103 socket_name : str, optional
104 socket_path : str, optional
105 config_file : str, optional
106 colors : str, optional
107 on_init : callable, optional
108 socket_name_factory : callable, optional
109 tmux_bin : str or pathlib.Path, optional
110
111 Examples
112 --------
113 >>> server
114 Server(socket_name=libtmux_test...)
115
116 >>> server.sessions
117 [Session($1 ...)]
118
119 >>> server.sessions[0].windows
120 [Window(@1 1:..., Session($1 ...))]
121
122 >>> server.sessions[0].active_window
123 Window(@1 1:..., Session($1 ...))
124
125 >>> server.sessions[0].active_pane
126 Pane(%1 Window(@1 1:..., Session($1 ...)))
127
128 The server can be used as a context manager to ensure proper cleanup:
129
130 >>> with Server() as server:
131 ... session = server.new_session()
132 ... # Do work with the session
133 ... # Server will be killed automatically when exiting the context
134
135 References
136 ----------
137 .. [server_manual] CLIENTS AND SESSIONS. openbsd manpage for TMUX(1)
138 "The tmux server manages clients, sessions, windows and panes.
139 Clients are attached to sessions to interact with them, either when
140 they are created with the new-session command, or later with the
141 attach-session command. Each session has one or more windows linked
142 into it. Windows may be linked to multiple sessions and are made up
143 of one or more panes, each of which contains a pseudo terminal."
144
145 https://man.openbsd.org/tmux.1#CLIENTS_AND_SESSIONS.
146 Accessed April 1st, 2018.
147 """
148
149 socket_name = None
150 """Passthrough to ``[-L socket-name]``"""
151 socket_path = None
152 """Passthrough to ``[-S socket-path]``"""
153 config_file = None
154 """Passthrough to ``[-f file]``"""
155 colors = None
156 """``256`` or ``88``"""
157 child_id_attribute = "session_id"
158 """Unique child ID used by :class:`~libtmux.common.TmuxRelationalObject`"""
159 formatter_prefix = "server_"
160 """Namespace used for :class:`~libtmux.common.TmuxMappingObject`"""
161
162 default_option_scope: OptionScope | None = OptionScope.Server
163 """For option management."""
164 default_hook_scope: OptionScope | None = OptionScope.Server
165 """For hook management."""
166 tmux_bin: str | None = None
167 """Custom path to tmux binary. Falls back to ``shutil.which("tmux")``."""
168
169 def __init__(
170 self,
171 socket_name: str | None = None,
172 socket_path: str | pathlib.Path | None = None,
173 config_file: str | None = None,
174 colors: int | None = None,
175 on_init: t.Callable[[Server], None] | None = None,
176 socket_name_factory: t.Callable[[], str] | None = None,
177 tmux_bin: str | pathlib.Path | None = None,
178 **kwargs: t.Any,
179 ) -> None:
180 EnvironmentMixin.__init__(self, "-g")
181 self.tmux_bin = str(tmux_bin) if tmux_bin is not None else None
182 self._windows: list[WindowDict] = []
183 self._panes: list[PaneDict] = []
184
185 if socket_path is not None:
186 self.socket_path = socket_path
187 elif socket_name is not None:
188 self.socket_name = socket_name
189 elif socket_name_factory is not None:
190 self.socket_name = socket_name_factory()
191
192 tmux_tmpdir = pathlib.Path(os.getenv("TMUX_TMPDIR", "/tmp"))
193 socket_name = self.socket_name or "default"
194 if (
195 tmux_tmpdir is not None
196 and self.socket_path is None
197 and self.socket_name is None
198 and socket_name != "default"
199 ):
200 self.socket_path = str(tmux_tmpdir / f"tmux-{os.geteuid()}" / socket_name)
201
202 if config_file:
203 self.config_file = config_file
204
205 if colors:
206 self.colors = colors
207
208 if on_init is not None:
209 on_init(self)
210
211 def __enter__(self) -> Self:
212 """Enter the context, returning self.
213
214 Returns
215 -------
216 :class:`Server`
217 The server instance
218 """
219 return self
220
221 def __exit__(
222 self,
223 exc_type: type[BaseException] | None,
224 exc_value: BaseException | None,
225 exc_tb: types.TracebackType | None,
226 ) -> None:
227 """Exit the context, killing the server if it exists.
228
229 Parameters
230 ----------
231 exc_type : type[BaseException] | None
232 The type of the exception that was raised
233 exc_value : BaseException | None
234 The instance of the exception that was raised
235 exc_tb : types.TracebackType | None
236 The traceback of the exception that was raised
237 """
238 if self.is_alive():
239 self.kill()
240
241 def is_alive(self) -> bool:
242 """Return True if tmux server alive.
243
244 >>> tmux = Server(socket_name="no_exist")
245 >>> assert not tmux.is_alive()
246 """
247 try:
248 res = self.cmd("list-sessions")
249 except Exception:
250 return False
251 return res.returncode == 0
252
253 def raise_if_dead(self) -> None:
254 """Raise if server not connected.
255
256 Raises
257 ------
258 :exc:`exc.TmuxCommandNotFound`
259 When the tmux binary cannot be found or executed.
260 :class:`subprocess.CalledProcessError`
261 When the tmux server is not running (non-zero exit from
262 ``list-sessions``).
263
264 >>> tmux = Server(socket_name="no_exist")
265 >>> try:
266 ... tmux.raise_if_dead()
267 ... except Exception as e:
268 ... print(type(e))
269 <class 'subprocess.CalledProcessError'>
270 """
271 resolved = self.tmux_bin or shutil.which("tmux")
272 if resolved is None:
273 raise exc.TmuxCommandNotFound
274
275 cmd_args: list[str] = ["list-sessions"]
276 if self.socket_name:
277 cmd_args.insert(0, f"-L{self.socket_name}")
278 if self.socket_path:
279 cmd_args.insert(0, f"-S{self.socket_path}")
280 if self.config_file:
281 cmd_args.insert(0, f"-f{self.config_file}")
282
283 try:
284 subprocess.check_call([resolved, *cmd_args])
285 except FileNotFoundError:
286 raise exc.TmuxCommandNotFound from None
287
288 #
289 # Command
290 #
291 def cmd(
292 self,
293 cmd: str,
294 *args: t.Any,
295 target: str | int | None = None,
296 ) -> tmux_cmd:
297 """Execute tmux command respective of socket name and file, return output.
298
299 Examples
300 --------
301 >>> server.cmd('display-message', 'hi')
302 <libtmux.common.tmux_cmd object at ...>
303
304 New session:
305
306 >>> server.cmd('new-session', '-d', '-P', '-F#{session_id}').stdout[0]
307 '$2'
308
309 >>> session.cmd('new-window', '-P').stdout[0]
310 'libtmux...:2.0'
311
312 Output of `tmux -L ... new-window -P -F#{window_id}` to a `Window` object:
313
314 >>> Window.from_window_id(window_id=session.cmd(
315 ... 'new-window', '-P', '-F#{window_id}').stdout[0], server=session.server)
316 Window(@4 3:..., Session($1 libtmux_...))
317
318 Create a pane from a window:
319
320 >>> window.cmd('split-window', '-P', '-F#{pane_id}').stdout[0]
321 '%5'
322
323 Output of `tmux -L ... split-window -P -F#{pane_id}` to a `Pane` object:
324
325 >>> Pane.from_pane_id(pane_id=window.cmd(
326 ... 'split-window', '-P', '-F#{pane_id}').stdout[0], server=window.server)
327 Pane(%... Window(@... ...:..., Session($1 libtmux_...)))
328
329 Parameters
330 ----------
331 target : str, optional
332 Optional custom target.
333
334 Returns
335 -------
336 :class:`common.tmux_cmd`
337
338 Notes
339 -----
340 .. versionchanged:: 0.8
341
342 Renamed from ``.tmux`` to ``.cmd``.
343 """
344 svr_args: list[str | int] = [cmd]
345 cmd_args: list[str | int] = []
346 if self.socket_name:
347 svr_args.insert(0, f"-L{self.socket_name}")
348 if self.socket_path:
349 svr_args.insert(0, f"-S{self.socket_path}")
350 if self.config_file:
351 svr_args.insert(0, f"-f{self.config_file}")
352 if self.colors:
353 if self.colors == 256:
354 svr_args.insert(0, "-2")
355 elif self.colors == 88:
356 svr_args.insert(0, "-8")
357 else:
358 raise exc.UnknownColorOption
359
360 cmd_args = ["-t", str(target), *args] if target is not None else [*args]
361
362 return tmux_cmd(*svr_args, *cmd_args, tmux_bin=self.tmux_bin)
363
364 @property
365 def attached_sessions(self) -> list[Session]:
366 """Return active :class:`Session` instances.
367
368 Examples
369 --------
370 >>> server.attached_sessions
371 []
372
373 Returns
374 -------
375 list[:class:`Session`]
376 Sessions that are attached.
377 """
378 return self.sessions.filter(session_attached__noeq="1")
379
380 def has_session(self, target_session: str, exact: bool = True) -> bool:
381 """Return True if session exists.
382
383 Parameters
384 ----------
385 target_session : str
386 session name
387 exact : bool
388 match the session name exactly. tmux uses fnmatch by default.
389 Internally prepends ``=`` to the session in ``$ tmux has-session``.
390
391 Raises
392 ------
393 :exc:`exc.BadSessionName`
394
395 Returns
396 -------
397 bool
398 """
399 session_check_name(target_session)
400
401 if exact:
402 target_session = f"={target_session}"
403
404 proc = self.cmd("has-session", target=target_session)
405
406 return bool(not proc.returncode)
407
408 def kill(self) -> None:
409 """Kill tmux server.
410
411 >>> svr = Server(socket_name="testing")
412 >>> svr
413 Server(socket_name=testing)
414
415 >>> svr.new_session()
416 Session(...)
417
418 >>> svr.is_alive()
419 True
420
421 >>> svr.kill()
422
423 >>> svr.is_alive()
424 False
425 """
426 proc = self.cmd("kill-server")
427 if proc.stderr:
428 stderr_text = " ".join(str(line) for line in proc.stderr)
429 if _is_daemon_not_up_error(stderr_text):
430 return
431 raise exc.LibTmuxException(proc.stderr)
432 logger.info("server killed", extra={"tmux_subcommand": "kill-server"})
433
434 def kill_session(self, target_session: str | int) -> Server:
435 """Kill tmux session.
436
437 Parameters
438 ----------
439 target_session : str, optional
440 target_session: str. note this accepts ``fnmatch(3)``. 'asdf' will
441 kill 'asdfasd'.
442
443 Returns
444 -------
445 :class:`Server`
446
447 Raises
448 ------
449 :exc:`exc.BadSessionName`
450 """
451 proc = self.cmd("kill-session", target=target_session)
452
453 raise_if_stderr(proc, "kill-session")
454
455 return self
456
457 def run_shell(
458 self,
459 command: str,
460 *,
461 background: bool | None = None,
462 delay: str | None = None,
463 as_tmux_command: bool | None = None,
464 target_pane: str | None = None,
465 cwd: StrPath | None = None,
466 show_stderr: bool | None = None,
467 args: list[str] | None = None,
468 ) -> list[str] | None:
469 r"""Execute a shell command via ``$ tmux run-shell``.
470
471 Parameters
472 ----------
473 command : str
474 Shell command to execute.
475 background : bool, optional
476 Run in background (``-b`` flag).
477 delay : str, optional
478 Delay before execution (``-d`` flag).
479 as_tmux_command : bool, optional
480 Parse argument as a tmux command instead of a shell command
481 (``-C`` flag).
482 target_pane : str, optional
483 Target pane for output (``-t`` flag).
484 cwd : str or PathLike, optional
485 Start directory for the shell command (``-c`` flag). When
486 omitted, tmux uses the target client's current working
487 directory. Requires tmux 3.4+; on older tmux a warning is
488 emitted and the kwarg is ignored.
489
490 Note: tmux's ``-c`` is a *start directory*, not subprocess
491 semantics. If ``chdir(cwd)`` fails, tmux falls back to the
492 user's home directory, then to ``/``, rather than raising
493 — unlike Python's ``subprocess.Popen(cwd=)`` which errors
494 on a failed chdir.
495
496 .. versionadded:: 0.57
497 show_stderr : bool, optional
498 Combine the command's stderr into the captured output stream
499 (``-E`` flag, maps to ``JOB_SHOWSTDERR``). Requires tmux 3.6+;
500 on older tmux a warning is emitted and the kwarg is ignored.
501
502 .. versionadded:: 0.57
503 args : list of str, optional
504 Positional arguments passed after *command*, expanded as
505 ``#{1}``, ``#{2}``, … inside it. Requires tmux 3.7+; warns and
506 is ignored on older tmux.
507
508 Returns
509 -------
510 list[str] | None
511 Stdout lines, or None when *background* is True. Empty list on
512 tmux 3.3a/3.4 (upstream stdout passthrough was broken until 3.5).
513
514 Examples
515 --------
516 >>> result = server.run_shell('true')
517 >>> isinstance(result, list)
518 True
519 """
520 tmux_args: tuple[str, ...] = ()
521
522 if background:
523 tmux_args += ("-b",)
524
525 if delay is not None:
526 tmux_args += ("-d", delay)
527
528 if as_tmux_command:
529 tmux_args += ("-C",)
530
531 if target_pane is not None:
532 tmux_args += ("-t", target_pane)
533
534 if cwd is not None:
535 if has_gte_version("3.4", tmux_bin=self.tmux_bin):
536 tmux_args += ("-c", str(cwd))
537 else:
538 warnings.warn(
539 "cwd requires tmux 3.4+, ignoring",
540 stacklevel=2,
541 )
542
543 if show_stderr:
544 if has_gte_version("3.6", tmux_bin=self.tmux_bin):
545 tmux_args += ("-E",)
546 else:
547 warnings.warn(
548 "show_stderr requires tmux 3.6+, ignoring",
549 stacklevel=2,
550 )
551
552 tmux_args += (command,)
553
554 if args:
555 if has_gte_version("3.7", tmux_bin=self.tmux_bin):
556 tmux_args += tuple(args)
557 else:
558 warnings.warn(
559 "args requires tmux 3.7+, ignoring",
560 stacklevel=2,
561 )
562
563 proc = self.cmd("run-shell", *tmux_args)
564
565 raise_if_stderr(proc, "run-shell")
566
567 if background:
568 return None
569 return proc.stdout
570
571 def wait_for(
572 self,
573 channel: str,
574 *,
575 lock: bool | None = None,
576 unlock: bool | None = None,
577 set_flag: bool | None = None,
578 ) -> None:
579 """Wait for, signal, or lock a channel via ``$ tmux wait-for``.
580
581 Parameters
582 ----------
583 channel : str
584 Channel name.
585 lock : bool, optional
586 Lock the channel (``-L`` flag).
587 unlock : bool, optional
588 Unlock the channel (``-U`` flag).
589 set_flag : bool, optional
590 Set the channel flag and wake waiters (``-S`` flag).
591
592 Examples
593 --------
594 >>> server.new_session(session_name='wait_test')
595 Session(...)
596 >>> server.wait_for('test_channel', set_flag=True)
597 """
598 tmux_args: tuple[str, ...] = ()
599
600 if lock:
601 tmux_args += ("-L",)
602
603 if unlock:
604 tmux_args += ("-U",)
605
606 if set_flag:
607 tmux_args += ("-S",)
608
609 tmux_args += (channel,)
610
611 proc = self.cmd("wait-for", *tmux_args)
612
613 raise_if_stderr(proc, "wait-for")
614
615 def bind_key(
616 self,
617 key: str,
618 command: str,
619 *,
620 key_table: str | None = None,
621 note: str | None = None,
622 repeat: bool | None = None,
623 ) -> None:
624 """Bind a key to a command via ``$ tmux bind-key``.
625
626 Parameters
627 ----------
628 key : str
629 Key to bind (e.g. ``C-a``, ``F12``, ``M-x``).
630 command : str
631 Tmux command to run when key is pressed.
632 key_table : str, optional
633 Key table to bind in (``-T`` flag). Defaults to ``prefix``.
634 note : str, optional
635 Note for the binding (``-N`` flag).
636 repeat : bool, optional
637 Allow the key to repeat (``-r`` flag).
638
639 Examples
640 --------
641 >>> server.bind_key('F12', 'display-message test', key_table='root')
642 >>> server.unbind_key('F12', key_table='root')
643 """
644 tmux_args: tuple[str, ...] = ()
645
646 if repeat:
647 tmux_args += ("-r",)
648
649 if note is not None:
650 tmux_args += ("-N", note)
651
652 if key_table is not None:
653 tmux_args += ("-T", key_table)
654
655 tmux_args += (key, command)
656
657 proc = self.cmd("bind-key", *tmux_args)
658
659 raise_if_stderr(proc, "bind-key")
660
661 def unbind_key(
662 self,
663 key: str | None = None,
664 *,
665 key_table: str | None = None,
666 all_keys: bool | None = None,
667 quiet: bool | None = None,
668 ) -> None:
669 """Unbind a key via ``$ tmux unbind-key``.
670
671 Parameters
672 ----------
673 key : str, optional
674 Key to unbind. Required unless *all_keys* is True.
675 key_table : str, optional
676 Key table (``-T`` flag). Defaults to ``prefix``.
677 all_keys : bool, optional
678 Unbind all keys (``-a`` flag).
679 quiet : bool, optional
680 Suppress errors for missing bindings (``-q`` flag).
681
682 Examples
683 --------
684 >>> server.bind_key('F11', 'display-message test', key_table='root')
685 >>> server.unbind_key('F11', key_table='root')
686 """
687 tmux_args: tuple[str, ...] = ()
688
689 if all_keys:
690 tmux_args += ("-a",)
691
692 if quiet:
693 tmux_args += ("-q",)
694
695 if key_table is not None:
696 tmux_args += ("-T", key_table)
697
698 if key is not None:
699 tmux_args += (key,)
700
701 proc = self.cmd("unbind-key", *tmux_args)
702
703 raise_if_stderr(proc, "unbind-key")
704
705 def list_keys(
706 self,
707 *,
708 key_table: str | None = None,
709 format_: str | None = None,
710 ) -> list[str]:
711 """List key bindings via ``$ tmux list-keys``.
712
713 Parameters
714 ----------
715 key_table : str, optional
716 Filter by key table (``-T`` flag).
717 format_ : str, optional
718 Custom output format applied to each line (``-F`` flag).
719 Requires tmux 3.7+; warns and is ignored on older tmux.
720
721 Returns
722 -------
723 list[str]
724 Key binding lines.
725
726 Examples
727 --------
728 >>> result = server.list_keys()
729 >>> isinstance(result, list)
730 True
731 """
732 tmux_args: tuple[str, ...] = ()
733
734 if key_table is not None:
735 tmux_args += ("-T", key_table)
736
737 if format_ is not None:
738 if has_gte_version("3.7", tmux_bin=self.tmux_bin):
739 tmux_args += ("-F", format_)
740 else:
741 warnings.warn(
742 "format requires tmux 3.7+, ignoring",
743 stacklevel=2,
744 )
745
746 proc = self.cmd("list-keys", *tmux_args)
747
748 raise_if_stderr(proc, "list-keys")
749
750 return proc.stdout
751
752 def list_commands(self, *, command_name: str | None = None) -> list[str]:
753 """List tmux commands via ``$ tmux list-commands``.
754
755 Parameters
756 ----------
757 command_name : str, optional
758 Filter to a specific command.
759
760 Returns
761 -------
762 list[str]
763 Command listing lines.
764
765 Examples
766 --------
767 >>> result = server.list_commands(command_name='send-keys')
768 >>> len(result) >= 1
769 True
770 """
771 tmux_args: tuple[str, ...] = ()
772
773 if command_name is not None:
774 tmux_args += (command_name,)
775
776 proc = self.cmd("list-commands", *tmux_args)
777
778 raise_if_stderr(proc, "list-commands")
779
780 return proc.stdout
781
782 def lock_server(self) -> None:
783 """Lock the tmux server via ``$ tmux lock-server``.
784
785 Requires an attached client.
786
787 >>> with control_mode() as ctl:
788 ... server.lock_server()
789 """
790 proc = self.cmd("lock-server")
791
792 raise_if_stderr(proc, "lock-server")
793
794 def server_access(
795 self,
796 *,
797 allow: str | None = None,
798 deny: str | None = None,
799 list_access: bool | None = None,
800 read_only: bool | None = None,
801 write: bool | None = None,
802 ) -> list[str] | None:
803 """Manage server access control via ``$ tmux server-access``.
804
805 Requires tmux 3.3+ (introduced in 3.3).
806
807 Parameters
808 ----------
809 allow : str, optional
810 Allow a user (``-a`` flag).
811 deny : str, optional
812 Deny a user (``-d`` flag).
813 list_access : bool, optional
814 List access rules (``-l`` flag).
815 read_only : bool, optional
816 Force the user to attach read-only (``-r`` flag). Implies
817 allow if the user is not already in the ACL. Mutually
818 exclusive with *write* — tmux rejects ``-r -w``.
819 write : bool, optional
820 Allow the user to attach read-write (``-w`` flag). Implies
821 allow if the user is not already in the ACL. Mutually
822 exclusive with *read_only*.
823
824 Returns
825 -------
826 list[str] | None
827 Access list when *list_access* is True, None otherwise.
828
829 Examples
830 --------
831 >>> from libtmux.common import has_gte_version
832 >>> if has_gte_version("3.3"):
833 ... result = server.server_access(list_access=True)
834 ... assert isinstance(result, list)
835 """
836 if not has_gte_version("3.3", tmux_bin=self.tmux_bin):
837 msg = "server_access requires tmux 3.3+"
838 raise exc.LibTmuxException(msg)
839
840 if read_only and write:
841 msg = "read_only and write are mutually exclusive (tmux rejects -r -w)"
842 raise ValueError(msg)
843
844 tmux_args: tuple[str, ...] = ()
845
846 if allow is not None:
847 tmux_args += ("-a", allow)
848
849 if deny is not None:
850 tmux_args += ("-d", deny)
851
852 if list_access:
853 tmux_args += ("-l",)
854
855 if read_only:
856 tmux_args += ("-r",)
857
858 if write:
859 tmux_args += ("-w",)
860
861 proc = self.cmd("server-access", *tmux_args)
862
863 raise_if_stderr(proc, "server-access")
864
865 if list_access:
866 return proc.stdout
867 return None
868
869 def refresh_client(
870 self,
871 *,
872 target_client: str | None = None,
873 request_clipboard: bool = False,
874 ) -> None:
875 """Refresh a client's display via ``$ tmux refresh-client``.
876
877 Requires an attached client.
878
879 Parameters
880 ----------
881 target_client : str, optional
882 Target client (``-t`` flag).
883 request_clipboard : bool, optional
884 Request the clipboard from the terminal (``-l`` flag,
885 ``tty_clipboard_query``) — the runtime companion to the
886 ``get-clipboard`` option. Requires tmux 3.7+; warns and is
887 ignored on older tmux (where ``-l`` is the legacy forward form).
888
889 Examples
890 --------
891 >>> with control_mode() as ctl:
892 ... server.refresh_client()
893 """
894 tmux_args: tuple[str, ...] = ()
895
896 if target_client is not None:
897 tmux_args += ("-t", target_client)
898
899 if request_clipboard:
900 if has_gte_version("3.7", tmux_bin=self.tmux_bin):
901 tmux_args += ("-l",)
902 else:
903 warnings.warn(
904 "request_clipboard requires tmux 3.7+, ignoring",
905 stacklevel=2,
906 )
907
908 proc = self.cmd("refresh-client", *tmux_args)
909
910 raise_if_stderr(proc, "refresh-client")
911
912 def suspend_client(self, *, target_client: str | None = None) -> None:
913 """Suspend a client via ``$ tmux suspend-client``.
914
915 Requires an attached client.
916
917 Parameters
918 ----------
919 target_client : str, optional
920 Target client (``-t`` flag).
921
922 Examples
923 --------
924 >>> with control_mode() as ctl:
925 ... server.suspend_client()
926 """
927 tmux_args: tuple[str, ...] = ()
928
929 if target_client is not None:
930 tmux_args += ("-t", target_client)
931
932 proc = self.cmd("suspend-client", *tmux_args)
933
934 raise_if_stderr(proc, "suspend-client")
935
936 def lock_client(self, *, target_client: str | None = None) -> None:
937 """Lock a client via ``$ tmux lock-client``.
938
939 Requires an attached client.
940
941 Parameters
942 ----------
943 target_client : str, optional
944 Target client (``-t`` flag).
945
946 Examples
947 --------
948 >>> with control_mode() as ctl:
949 ... server.lock_client()
950 """
951 tmux_args: tuple[str, ...] = ()
952
953 if target_client is not None:
954 tmux_args += ("-t", target_client)
955
956 proc = self.cmd("lock-client", *tmux_args)
957
958 raise_if_stderr(proc, "lock-client")
959
960 def detach_client(
961 self,
962 *,
963 target_client: str | None = None,
964 shell_command: str | None = None,
965 ) -> None:
966 """Detach a specific client via ``$ tmux detach-client``.
967
968 Maps to ``$ tmux detach-client [-t <target_client>]``. tmux
969 resolves ``-t`` over the global client list (see
970 ``cmd-find.c``); the named client may be attached to any
971 session, so this method lives on :class:`Server` rather than
972 :class:`Session`.
973
974 Parameters
975 ----------
976 target_client : str, optional
977 Client name (``-t`` flag). When omitted, tmux falls back to
978 the most-recently-active client.
979 shell_command : str, optional
980 Run a shell command on the detached client after detach
981 (``-E`` flag).
982
983 See Also
984 --------
985 :meth:`Session.detach_client` : detach every client attached to
986 a session (``-s`` flag).
987 :meth:`detach_all_clients` : detach every client on the server
988 (``-a`` flag).
989
990 .. versionadded:: 0.56
991
992 Examples
993 --------
994 >>> with control_mode() as ctl:
995 ... server.detach_client(target_client=ctl.client_name)
996 """
997 tmux_args: tuple[str, ...] = ()
998
999 if shell_command is not None:
1000 tmux_args += ("-E", shell_command)
1001
1002 if target_client is not None:
1003 tmux_args += ("-t", target_client)
1004
1005 proc = self.cmd("detach-client", *tmux_args)
1006
1007 raise_if_stderr(proc, "detach-client")
1008
1009 def detach_all_clients(
1010 self,
1011 *,
1012 keep_client: str | None = None,
1013 shell_command: str | None = None,
1014 ) -> None:
1015 """Detach every client on this server via ``$ tmux detach-client -a``.
1016
1017 tmux's ``-a`` always preserves one client; when *keep_client* is
1018 omitted, the most-recently-active client survives.
1019
1020 Parameters
1021 ----------
1022 keep_client : str, optional
1023 Client to preserve (``-t`` flag). All other clients on the
1024 server, regardless of which session they are attached to,
1025 are detached.
1026 shell_command : str, optional
1027 Run a shell command on the detached client(s) after detach
1028 (``-E`` flag).
1029
1030 See Also
1031 --------
1032 :meth:`Session.detach_client` : detach every client attached to
1033 a session (``-s`` flag).
1034 :meth:`detach_client` : detach a single named client (``-t``
1035 flag).
1036
1037 .. versionadded:: 0.56
1038
1039 Examples
1040 --------
1041 >>> with control_mode() as ctl:
1042 ... server.detach_all_clients(keep_client=ctl.client_name)
1043 """
1044 tmux_args: tuple[str, ...] = ("-a",)
1045
1046 if shell_command is not None:
1047 tmux_args += ("-E", shell_command)
1048
1049 if keep_client is not None:
1050 tmux_args += ("-t", keep_client)
1051
1052 proc = self.cmd("detach-client", *tmux_args)
1053
1054 raise_if_stderr(proc, "detach-client")
1055
1056 def confirm_before(
1057 self,
1058 command: str,
1059 *,
1060 prompt: str | None = None,
1061 confirm_key: str | None = None,
1062 default_yes: bool | None = None,
1063 target_client: str | None = None,
1064 ) -> None:
1065 """Run a command after confirmation via ``$ tmux confirm-before``.
1066
1067 Always uses ``-b`` (background) to avoid blocking the command queue.
1068 Use ``send-keys -K -c <client>`` to provide the confirmation key.
1069
1070 Requires tmux 3.3+ for ``-b`` flag support.
1071
1072 Parameters
1073 ----------
1074 command : str
1075 Tmux command to run after confirmation.
1076 prompt : str, optional
1077 Custom prompt text (``-p`` flag).
1078 confirm_key : str, optional
1079 Key to accept as confirmation (``-c`` flag). Default is ``y``.
1080 Requires tmux 3.4+.
1081 default_yes : bool, optional
1082 Make Enter default to yes (``-y`` flag). Requires tmux 3.4+.
1083 target_client : str, optional
1084 Target client (``-t`` flag).
1085
1086 Examples
1087 --------
1088 Interactive confirmation requires tmux 3.4+; the wrapper itself
1089 works on 3.3+ but the ``send-keys -K -c <client>`` round-trip
1090 used here is unreliable on 3.3a:
1091
1092 >>> from libtmux.common import has_gte_version
1093 >>> if has_gte_version("3.4"):
1094 ... with control_mode() as ctl:
1095 ... server.confirm_before(
1096 ... 'set -g @cf_test yes',
1097 ... target_client=ctl.client_name,
1098 ... )
1099 ... _ = server.cmd('send-keys', '-K', '-c', ctl.client_name, 'y')
1100 ... result = server.cmd('show-options', '-gv', '@cf_test').stdout[0]
1101 ... else:
1102 ... result = 'yes'
1103 >>> result
1104 'yes'
1105 """
1106 if not has_gte_version("3.3", tmux_bin=self.tmux_bin):
1107 msg = "confirm_before requires tmux 3.3+"
1108 raise exc.LibTmuxException(msg)
1109
1110 tmux_args: tuple[str, ...] = ("-b",)
1111
1112 if prompt is not None:
1113 tmux_args += ("-p", prompt)
1114
1115 if confirm_key is not None:
1116 if has_gte_version("3.4", tmux_bin=self.tmux_bin):
1117 tmux_args += ("-c", confirm_key)
1118 else:
1119 warnings.warn(
1120 "confirm_key requires tmux 3.4+, ignoring",
1121 stacklevel=2,
1122 )
1123
1124 if default_yes:
1125 if has_gte_version("3.4", tmux_bin=self.tmux_bin):
1126 tmux_args += ("-y",)
1127 else:
1128 warnings.warn(
1129 "default_yes requires tmux 3.4+, ignoring",
1130 stacklevel=2,
1131 )
1132
1133 if target_client is not None:
1134 tmux_args += ("-t", target_client)
1135
1136 tmux_args += (command,)
1137
1138 proc = self.cmd("confirm-before", *tmux_args)
1139
1140 raise_if_stderr(proc, "confirm-before")
1141
1142 def command_prompt(
1143 self,
1144 template: str,
1145 *,
1146 prompt: str | None = None,
1147 inputs: str | None = None,
1148 target_client: str | None = None,
1149 one_key: bool | None = None,
1150 key_only: bool | None = None,
1151 on_input_change: bool | None = None,
1152 numeric: bool | None = None,
1153 prompt_type: t.Literal["command", "search", "target", "window-target"]
1154 | None = None,
1155 expand_format: bool | None = None,
1156 literal: bool | None = None,
1157 bspace_exit: bool | None = None,
1158 no_freeze: bool | None = None,
1159 ) -> None:
1160 """Open a command prompt via ``$ tmux command-prompt``.
1161
1162 Always uses ``-b`` (background) to avoid blocking the command queue.
1163 Use ``send-keys -K -c <client>`` to type into the prompt and submit.
1164
1165 Requires tmux 3.3+ for ``-b`` flag support.
1166
1167 Parameters
1168 ----------
1169 template : str
1170 Tmux command template. Use ``%1``, ``%2`` for prompt values.
1171 prompt : str, optional
1172 Custom prompt text (``-p`` flag). Commas separate multiple prompts.
1173 inputs : str, optional
1174 Pre-fill prompt input (``-I`` flag). Commas separate multiple.
1175 target_client : str, optional
1176 Target client (``-t`` flag).
1177 one_key : bool, optional
1178 Accept only one key press (``-1`` flag).
1179 key_only : bool, optional
1180 Only accept key presses, not text (``-k`` flag).
1181 on_input_change : bool, optional
1182 Run template on each keystroke (``-i`` flag).
1183 numeric : bool, optional
1184 Accept only numeric input (``-N`` flag).
1185 prompt_type : str, optional
1186 Prompt type (``-T`` flag).
1187 expand_format : bool, optional
1188 Pass the template through ``args_make_commands_prepare``
1189 (``-F`` flag) so format strings expand. Requires tmux 3.3+.
1190 literal : bool, optional
1191 Disable splitting *prompt* on commas — treat it as a single
1192 prompt (``-l`` flag). Requires tmux 3.6+.
1193 bspace_exit : bool, optional
1194 Close the prompt when the user empties it with backspace
1195 (``-e`` flag, ``PROMPT_BSPACE_EXIT``). Requires tmux 3.7+ (upstream master).
1196 no_freeze : bool, optional
1197 Do not freeze panes while the prompt is open (``-C`` flag,
1198 ``PROMPT_NOFREEZE``), matching ``display-message -C``. Requires
1199 tmux 3.7+; warns and is ignored on older tmux.
1200
1201 Examples
1202 --------
1203 Interactive prompts require tmux 3.4+; the wrapper itself works
1204 on 3.3+ but the ``send-keys -K -c <client>`` round-trip used
1205 here is unreliable on 3.3a:
1206
1207 >>> from libtmux.common import has_gte_version
1208 >>> if has_gte_version("3.4"):
1209 ... with control_mode() as ctl:
1210 ... server.command_prompt(
1211 ... "set -g @cp_test '%1'",
1212 ... target_client=ctl.client_name,
1213 ... )
1214 ... for key in ['h', 'i', 'Enter']:
1215 ... _ = server.cmd('send-keys', '-K', '-c', ctl.client_name, key)
1216 ... result = server.cmd('show-options', '-gv', '@cp_test').stdout[0]
1217 ... else:
1218 ... result = 'hi'
1219 >>> result
1220 'hi'
1221 """
1222 if not has_gte_version("3.3", tmux_bin=self.tmux_bin):
1223 msg = "command_prompt requires tmux 3.3+"
1224 raise exc.LibTmuxException(msg)
1225
1226 tmux_args: tuple[str, ...] = ("-b",)
1227
1228 if one_key:
1229 tmux_args += ("-1",)
1230
1231 if key_only:
1232 tmux_args += ("-k",)
1233
1234 if on_input_change:
1235 tmux_args += ("-i",)
1236
1237 if numeric:
1238 tmux_args += ("-N",)
1239
1240 if expand_format:
1241 tmux_args += ("-F",)
1242
1243 if literal:
1244 if has_gte_version("3.6", tmux_bin=self.tmux_bin):
1245 tmux_args += ("-l",)
1246 else:
1247 warnings.warn(
1248 "literal requires tmux 3.6+, ignoring",
1249 stacklevel=2,
1250 )
1251
1252 if bspace_exit:
1253 if has_gte_version("3.7", tmux_bin=self.tmux_bin):
1254 tmux_args += ("-e",)
1255 else:
1256 warnings.warn(
1257 "bspace_exit requires tmux 3.7+ (upstream master), ignoring",
1258 stacklevel=2,
1259 )
1260
1261 if no_freeze:
1262 if has_gte_version("3.7", tmux_bin=self.tmux_bin):
1263 tmux_args += ("-C",)
1264 else:
1265 warnings.warn(
1266 "no_freeze requires tmux 3.7+, ignoring",
1267 stacklevel=2,
1268 )
1269
1270 if prompt is not None:
1271 tmux_args += ("-p", prompt)
1272
1273 if inputs is not None:
1274 tmux_args += ("-I", inputs)
1275
1276 if prompt_type is not None:
1277 tmux_args += ("-T", prompt_type)
1278
1279 if target_client is not None:
1280 tmux_args += ("-t", target_client)
1281
1282 tmux_args += (template,)
1283
1284 proc = self.cmd("command-prompt", *tmux_args)
1285
1286 raise_if_stderr(proc, "command-prompt")
1287
1288 def display_menu(
1289 self,
1290 *items: str,
1291 title: str | None = None,
1292 target_pane: str | None = None,
1293 target_client: str | None = None,
1294 x: int | str | None = None,
1295 y: int | str | None = None,
1296 starting_choice: int | str | None = None,
1297 border_lines: str | None = None,
1298 style: str | None = None,
1299 border_style: str | None = None,
1300 selected_style: str | None = None,
1301 mouse: bool | None = None,
1302 stay_open: bool | None = None,
1303 ) -> None:
1304 """Display a popup menu via ``$ tmux display-menu``.
1305
1306 Requires a TTY-backed attached client. Control-mode clients have
1307 ``tty.sy=0``, which causes ``menu_prepare()`` to return NULL.
1308 This method cannot be tested with
1309 :class:`~libtmux._internal.control_mode.ControlMode`.
1310
1311 Parameters
1312 ----------
1313 *items : str
1314 Menu items as positional args in tmux's ``name key command``
1315 triple format. Use empty strings for separators.
1316 title : str, optional
1317 Menu title (``-T`` flag).
1318 target_pane : str, optional
1319 Target pane for format expansion (``-t`` flag).
1320 target_client : str, optional
1321 Target client (``-c`` flag).
1322 x : int or str, optional
1323 Menu x position (``-x`` flag).
1324 y : int or str, optional
1325 Menu y position (``-y`` flag).
1326 starting_choice : int or str, optional
1327 Pre-selected item index (``-C`` flag). Use ``-`` for none.
1328 Requires tmux 3.4+.
1329 border_lines : str, optional
1330 Border line style (``-b`` flag). Requires tmux 3.4+.
1331 style : str, optional
1332 Menu style (``-s`` flag). Requires tmux 3.4+.
1333 border_style : str, optional
1334 Border style (``-S`` flag). Requires tmux 3.4+.
1335 selected_style : str, optional
1336 Style for the currently selected menu item (``-H`` flag).
1337 Requires tmux 3.4+.
1338 mouse : bool, optional
1339 Always enable mouse handling in the menu (``-M`` flag).
1340 Requires tmux 3.5+.
1341 stay_open : bool, optional
1342 Keep the menu open when the mouse is released (``-O`` flag).
1343 Requires tmux 3.2+.
1344
1345 Examples
1346 --------
1347 Cannot run end-to-end (requires a TTY-backed client; see the
1348 ``tty.sy=0`` note above). For broader coverage, see
1349 ``tests/test_server.py::test_display_menu_flags``.
1350
1351 >>> captured = []
1352 >>> def fake_cmd(name, *args, **_kw):
1353 ... captured.append((name, args))
1354 ... return type('R', (), {'stderr': [], 'stdout': []})()
1355 >>> monkeypatch.setattr(server, 'cmd', fake_cmd)
1356 >>> server.display_menu('First', '1', 'select-pane', title='menu')
1357 >>> captured[0][0]
1358 'display-menu'
1359 """
1360 tmux_args: tuple[str, ...] = ()
1361
1362 if title is not None:
1363 tmux_args += ("-T", title)
1364
1365 if target_client is not None:
1366 tmux_args += ("-c", target_client)
1367
1368 if target_pane is not None:
1369 tmux_args += ("-t", target_pane)
1370
1371 if x is not None:
1372 tmux_args += ("-x", str(x))
1373
1374 if y is not None:
1375 tmux_args += ("-y", str(y))
1376
1377 if starting_choice is not None:
1378 if has_gte_version("3.4", tmux_bin=self.tmux_bin):
1379 tmux_args += ("-C", str(starting_choice))
1380 else:
1381 warnings.warn(
1382 "starting_choice requires tmux 3.4+, ignoring",
1383 stacklevel=2,
1384 )
1385
1386 if border_lines is not None:
1387 if has_gte_version("3.4", tmux_bin=self.tmux_bin):
1388 tmux_args += ("-b", border_lines)
1389 else:
1390 warnings.warn(
1391 "border_lines requires tmux 3.4+, ignoring",
1392 stacklevel=2,
1393 )
1394
1395 if style is not None:
1396 if has_gte_version("3.4", tmux_bin=self.tmux_bin):
1397 tmux_args += ("-s", style)
1398 else:
1399 warnings.warn(
1400 "style requires tmux 3.4+, ignoring",
1401 stacklevel=2,
1402 )
1403
1404 if border_style is not None:
1405 if has_gte_version("3.4", tmux_bin=self.tmux_bin):
1406 tmux_args += ("-S", border_style)
1407 else:
1408 warnings.warn(
1409 "border_style requires tmux 3.4+, ignoring",
1410 stacklevel=2,
1411 )
1412
1413 if selected_style is not None:
1414 if has_gte_version("3.4", tmux_bin=self.tmux_bin):
1415 tmux_args += ("-H", selected_style)
1416 else:
1417 warnings.warn(
1418 "selected_style requires tmux 3.4+, ignoring",
1419 stacklevel=2,
1420 )
1421
1422 if mouse:
1423 if has_gte_version("3.5", tmux_bin=self.tmux_bin):
1424 tmux_args += ("-M",)
1425 else:
1426 warnings.warn(
1427 "mouse requires tmux 3.5+, ignoring",
1428 stacklevel=2,
1429 )
1430
1431 if stay_open:
1432 tmux_args += ("-O",)
1433
1434 tmux_args += items
1435
1436 proc = self.cmd("display-menu", *tmux_args)
1437
1438 raise_if_stderr(proc, "display-menu")
1439
1440 def start_server(self) -> None:
1441 """Start the tmux server via ``$ tmux start-server``.
1442
1443 Usually not needed since the server starts automatically on first
1444 session creation.
1445
1446 >>> server.start_server()
1447 """
1448 proc = self.cmd("start-server")
1449
1450 raise_if_stderr(proc, "start-server")
1451
1452 def show_messages(
1453 self,
1454 *,
1455 target_client: str | None = None,
1456 terminals: bool | None = None,
1457 jobs: bool | None = None,
1458 ) -> list[str]:
1459 """Show server message log via ``$ tmux show-messages``.
1460
1461 Without ``-T``/``-J``, tmux resolves the message log against a
1462 target client; if no client is attached and *target_client* is
1463 omitted, tmux raises ``no current client``. Provide
1464 *target_client* (e.g. via :class:`~libtmux._internal.control_mode.ControlMode`)
1465 when running headless, or use *terminals*/*jobs* — those modes
1466 don't require a client.
1467
1468 Parameters
1469 ----------
1470 target_client : str, optional
1471 Target client (``-t`` flag).
1472 terminals : bool, optional
1473 List terminal capabilities and flags instead of the message
1474 log (``-T`` flag).
1475 jobs : bool, optional
1476 Print the tmux job server summary instead of the message
1477 log (``-J`` flag).
1478
1479 Returns
1480 -------
1481 list[str]
1482 Server message log lines (or terminal/job summary when
1483 *terminals*/*jobs* is set).
1484
1485 Examples
1486 --------
1487 >>> with control_mode() as ctl:
1488 ... result = server.show_messages(target_client=ctl.client_name)
1489 >>> isinstance(result, list)
1490 True
1491 """
1492 tmux_args: tuple[str, ...] = ()
1493
1494 if terminals:
1495 tmux_args += ("-T",)
1496
1497 if jobs:
1498 tmux_args += ("-J",)
1499
1500 if target_client is not None:
1501 tmux_args += ("-t", target_client)
1502
1503 proc = self.cmd("show-messages", *tmux_args)
1504
1505 raise_if_stderr(proc, "show-messages")
1506
1507 return proc.stdout
1508
1509 @t.overload
1510 def display_message(
1511 self,
1512 cmd: str,
1513 get_text: t.Literal[True],
1514 *,
1515 format_string: str | None = ...,
1516 all_formats: bool | None = ...,
1517 verbose: bool | None = ...,
1518 no_expand: bool | None = ...,
1519 target_client: str | None = ...,
1520 delay: int | None = ...,
1521 notify: bool | None = ...,
1522 ) -> list[str]: ...
1523
1524 @t.overload
1525 def display_message(
1526 self,
1527 cmd: str,
1528 get_text: t.Literal[False] = ...,
1529 *,
1530 format_string: str | None = ...,
1531 all_formats: bool | None = ...,
1532 verbose: bool | None = ...,
1533 no_expand: bool | None = ...,
1534 target_client: str | None = ...,
1535 delay: int | None = ...,
1536 notify: bool | None = ...,
1537 ) -> None: ...
1538
1539 def display_message(
1540 self,
1541 cmd: str,
1542 get_text: bool = False,
1543 *,
1544 format_string: str | None = None,
1545 all_formats: bool | None = None,
1546 verbose: bool | None = None,
1547 no_expand: bool | None = None,
1548 target_client: str | None = None,
1549 delay: int | None = None,
1550 notify: bool | None = None,
1551 ) -> list[str] | None:
1552 """Display message at server scope via ``$ tmux display-message``.
1553
1554 Like :meth:`Pane.display_message` but without ``-t <pane-id>`` injection.
1555 tmux's ``cmd-display-message`` entry uses ``CMD_FIND_CANFAIL`` so the
1556 target is optional; server-scoped format reads (``#{version}``,
1557 ``#{socket_path}``, ``#{pid}``) resolve without a specific pane handle.
1558
1559 With no client attached and ``target_client`` omitted, the status-line
1560 path (``get_text=False``) issues a ``no current client`` warning. Use
1561 ``get_text=True`` for headless reads, or pair with
1562 :class:`~libtmux._internal.control_mode.ControlMode`.
1563
1564 Notes
1565 -----
1566 Stderr from tmux is reported via :func:`warnings.warn`, not raised.
1567 tmux uses stderr for both genuine errors and informational messages,
1568 and the right escalation depends on tmux version and call shape.
1569 Callers that want to escalate to an exception can wrap the call in
1570 :func:`warnings.catch_warnings` with ``filterwarnings("error")``.
1571
1572 .. versionchanged:: 0.57
1573 Reports stderr via :func:`warnings.warn` instead of raising.
1574
1575 Parameters
1576 ----------
1577 cmd : str
1578 Format string to display or evaluate (e.g. ``"#{version}"``).
1579 Pass ``""`` together with ``all_formats=True`` to dump every
1580 variable.
1581
1582 .. versionadded:: 0.57
1583 get_text : bool, optional
1584 Return tmux's stdout instead of rendering to the status line
1585 (``-p`` flag).
1586
1587 .. versionadded:: 0.57
1588 format_string : str, optional
1589 Alternative format template (``-F`` flag).
1590
1591 .. versionadded:: 0.57
1592 all_formats : bool, optional
1593 List all format variables (``-a`` flag).
1594
1595 .. versionadded:: 0.57
1596 verbose : bool, optional
1597 Show format variable types (``-v`` flag).
1598
1599 .. versionadded:: 0.57
1600 no_expand : bool, optional
1601 Output the literal string without format expansion (``-l`` flag).
1602 Requires tmux 3.4+.
1603
1604 .. versionadded:: 0.57
1605 target_client : str, optional
1606 Target client (``-c`` flag).
1607
1608 .. versionadded:: 0.57
1609 delay : int, optional
1610 Display time in milliseconds (``-d`` flag).
1611
1612 .. versionadded:: 0.57
1613 notify : bool, optional
1614 Do not wait for input (``-N`` flag).
1615
1616 .. versionadded:: 0.57
1617
1618 Returns
1619 -------
1620 list[str] | None
1621 Message output if ``get_text`` is True, otherwise ``None``.
1622
1623 Examples
1624 --------
1625 Read tmux version without needing a pane handle:
1626
1627 >>> result = server.display_message("#{version}", get_text=True)
1628 >>> isinstance(result, list) and len(result) == 1
1629 True
1630
1631 Dump every format variable:
1632
1633 >>> result = server.display_message("", get_text=True, all_formats=True)
1634 >>> any("session_name=" in line for line in result)
1635 True
1636 """
1637 tmux_args: tuple[str, ...] = ()
1638
1639 if get_text:
1640 tmux_args += ("-p",)
1641
1642 if all_formats:
1643 tmux_args += ("-a",)
1644
1645 if verbose:
1646 tmux_args += ("-v",)
1647
1648 if no_expand:
1649 if has_gte_version("3.4", tmux_bin=self.tmux_bin):
1650 tmux_args += ("-l",)
1651 else:
1652 warnings.warn(
1653 "no_expand requires tmux 3.4+, ignoring",
1654 stacklevel=2,
1655 )
1656
1657 if notify:
1658 tmux_args += ("-N",)
1659
1660 if target_client is not None:
1661 tmux_args += ("-c", target_client)
1662
1663 if delay is not None:
1664 tmux_args += ("-d", str(delay))
1665
1666 if format_string is not None:
1667 tmux_args += ("-F", format_string)
1668
1669 if cmd:
1670 tmux_args += (cmd,)
1671
1672 proc = self.cmd("display-message", *tmux_args)
1673 if proc.stderr:
1674 warnings.warn(
1675 f"display-message: {'; '.join(proc.stderr)}",
1676 stacklevel=2,
1677 )
1678
1679 if get_text:
1680 return proc.stdout
1681
1682 return None
1683
1684 def show_prompt_history(
1685 self,
1686 *,
1687 prompt_type: t.Literal["command", "search", "target", "window-target"]
1688 | None = None,
1689 ) -> list[str]:
1690 """Show prompt history via ``$ tmux show-prompt-history``.
1691
1692 Parameters
1693 ----------
1694 prompt_type : str, optional
1695 Prompt type to show (``-T`` flag).
1696
1697 Returns
1698 -------
1699 list[str]
1700 Prompt history lines.
1701
1702 Examples
1703 --------
1704 >>> from libtmux.common import has_gte_version
1705 >>> if has_gte_version("3.3"):
1706 ... result = server.show_prompt_history()
1707 ... else:
1708 ... result = []
1709 >>> isinstance(result, list)
1710 True
1711 """
1712 if not has_gte_version("3.3", tmux_bin=self.tmux_bin):
1713 msg = "show_prompt_history requires tmux 3.3+"
1714 raise exc.LibTmuxException(msg)
1715
1716 tmux_args: tuple[str, ...] = ()
1717
1718 if prompt_type is not None:
1719 tmux_args += ("-T", prompt_type)
1720
1721 proc = self.cmd("show-prompt-history", *tmux_args)
1722
1723 raise_if_stderr(proc, "show-prompt-history")
1724
1725 return proc.stdout
1726
1727 def clear_prompt_history(
1728 self,
1729 *,
1730 prompt_type: t.Literal["command", "search", "target", "window-target"]
1731 | None = None,
1732 ) -> None:
1733 """Clear prompt history via ``$ tmux clear-prompt-history``.
1734
1735 Parameters
1736 ----------
1737 prompt_type : str, optional
1738 Prompt type to clear (``-T`` flag).
1739
1740 Examples
1741 --------
1742 >>> from libtmux.common import has_gte_version
1743 >>> if has_gte_version("3.3"):
1744 ... server.clear_prompt_history()
1745 """
1746 if not has_gte_version("3.3", tmux_bin=self.tmux_bin):
1747 msg = "clear_prompt_history requires tmux 3.3+"
1748 raise exc.LibTmuxException(msg)
1749
1750 tmux_args: tuple[str, ...] = ()
1751
1752 if prompt_type is not None:
1753 tmux_args += ("-T", prompt_type)
1754
1755 proc = self.cmd("clear-prompt-history", *tmux_args)
1756
1757 raise_if_stderr(proc, "clear-prompt-history")
1758
1759 def set_buffer(
1760 self,
1761 data: str,
1762 *,
1763 buffer_name: str | None = None,
1764 append: bool | None = None,
1765 ) -> None:
1766 """Set a paste buffer via ``$ tmux set-buffer``.
1767
1768 Parameters
1769 ----------
1770 data : str
1771 Data to store in the buffer.
1772 buffer_name : str, optional
1773 Name of the buffer (``-b`` flag).
1774 append : bool, optional
1775 Append to the buffer instead of replacing (``-a`` flag).
1776
1777 Examples
1778 --------
1779 >>> server.set_buffer('hello')
1780 >>> server.show_buffer()
1781 'hello'
1782 """
1783 tmux_args: tuple[str, ...] = ()
1784
1785 if append:
1786 tmux_args += ("-a",)
1787
1788 if buffer_name is not None:
1789 tmux_args += ("-b", buffer_name)
1790
1791 tmux_args += (data,)
1792
1793 proc = self.cmd("set-buffer", *tmux_args)
1794
1795 raise_if_stderr(proc, "set-buffer")
1796
1797 def show_buffer(self, *, buffer_name: str | None = None) -> str:
1798 """Show content of a paste buffer via ``$ tmux show-buffer``.
1799
1800 Parameters
1801 ----------
1802 buffer_name : str, optional
1803 Name of the buffer (``-b`` flag). Defaults to the most recent.
1804
1805 Returns
1806 -------
1807 str
1808 Buffer content.
1809
1810 Examples
1811 --------
1812 >>> server.set_buffer('test_data')
1813 >>> server.show_buffer()
1814 'test_data'
1815 """
1816 tmux_args: tuple[str, ...] = ()
1817
1818 if buffer_name is not None:
1819 tmux_args += ("-b", buffer_name)
1820
1821 proc = self.cmd("show-buffer", *tmux_args)
1822
1823 raise_if_stderr(proc, "show-buffer")
1824
1825 return "\n".join(proc.stdout)
1826
1827 def delete_buffer(self, *, buffer_name: str | None = None) -> None:
1828 """Delete a paste buffer via ``$ tmux delete-buffer``.
1829
1830 Parameters
1831 ----------
1832 buffer_name : str, optional
1833 Name of the buffer to delete (``-b`` flag). Defaults to the most
1834 recent.
1835
1836 Examples
1837 --------
1838 >>> server.set_buffer('to_delete', buffer_name='del_buf')
1839 >>> server.delete_buffer(buffer_name='del_buf')
1840 """
1841 tmux_args: tuple[str, ...] = ()
1842
1843 if buffer_name is not None:
1844 tmux_args += ("-b", buffer_name)
1845
1846 proc = self.cmd("delete-buffer", *tmux_args)
1847
1848 raise_if_stderr(proc, "delete-buffer")
1849
1850 def save_buffer(
1851 self,
1852 path: StrPath,
1853 *,
1854 buffer_name: str | None = None,
1855 append: bool | None = None,
1856 ) -> None:
1857 """Save a paste buffer to a file via ``$ tmux save-buffer``.
1858
1859 Parameters
1860 ----------
1861 path : str or PathLike
1862 File path to save the buffer to.
1863 buffer_name : str, optional
1864 Name of the buffer (``-b`` flag). Defaults to the most recent.
1865 append : bool, optional
1866 Append to the file instead of overwriting (``-a`` flag).
1867
1868 Examples
1869 --------
1870 >>> import pathlib
1871 >>> server.set_buffer('save_me')
1872 >>> path = pathlib.Path(request.config.rootdir) / '..' / 'tmp_save.txt'
1873 >>> server.save_buffer(str(path))
1874 """
1875 tmux_args: tuple[str, ...] = ()
1876
1877 if append:
1878 tmux_args += ("-a",)
1879
1880 if buffer_name is not None:
1881 tmux_args += ("-b", buffer_name)
1882
1883 tmux_args += (str(pathlib.Path(path).expanduser()),)
1884
1885 proc = self.cmd("save-buffer", *tmux_args)
1886
1887 raise_if_stderr(proc, "save-buffer")
1888
1889 def load_buffer(
1890 self,
1891 path: StrPath,
1892 *,
1893 buffer_name: str | None = None,
1894 ) -> None:
1895 """Load a file into a paste buffer via ``$ tmux load-buffer``.
1896
1897 Parameters
1898 ----------
1899 path : str or PathLike
1900 File path to load into the buffer.
1901 buffer_name : str, optional
1902 Name of the buffer (``-b`` flag).
1903
1904 Examples
1905 --------
1906 >>> import pathlib
1907 >>> path = pathlib.Path(request.config.rootdir) / '..' / 'tmp_load.txt'
1908 >>> _ = path.write_text('loaded')
1909 >>> server.load_buffer(str(path), buffer_name='loaded_buf')
1910 """
1911 tmux_args: tuple[str, ...] = ()
1912
1913 if buffer_name is not None:
1914 tmux_args += ("-b", buffer_name)
1915
1916 tmux_args += (str(pathlib.Path(path).expanduser()),)
1917
1918 proc = self.cmd("load-buffer", *tmux_args)
1919
1920 raise_if_stderr(proc, "load-buffer")
1921
1922 def list_buffers(
1923 self,
1924 *,
1925 format_string: str | None = None,
1926 filter: str | None = None, # noqa: A002
1927 ) -> list[str]:
1928 """List paste buffers via ``$ tmux list-buffers``.
1929
1930 Without arguments returns tmux's default template
1931 (``name: N bytes: "sample"``) — kept for backward compatibility.
1932 Pass *format_string* to request a specific tmux format, or *filter*
1933 to have tmux return only matching buffers.
1934
1935 Parameters
1936 ----------
1937 format_string : str, optional
1938 Output template (``-F`` flag). Example: ``"#{buffer_name}"`` for
1939 raw names only.
1940
1941 .. versionadded:: 0.57
1942 filter : str, optional
1943 Filter expression evaluated by tmux (``-f`` flag). Buffers for
1944 which the expanded expression is false are omitted. Example:
1945 ``"#{m:libtmux_mcp_*,#{buffer_name}}"``.
1946
1947 Note: this kwarg shadows the Python builtin ``filter`` by design —
1948 it mirrors tmux's own flag name (``-f filter``) for grep-friendly
1949 symmetry between the wrapper and the tmux manual.
1950
1951 .. warning::
1952
1953 tmux silently expands a malformed filter (unclosed
1954 ``#{...}``, unknown format token) to empty, which the
1955 filter treats as false — every row is suppressed and no
1956 stderr is emitted. A bad filter is
1957 indistinguishable from "filter matched nothing"; verify
1958 filter syntax against the FORMATS section of ``tmux(1)``.
1959
1960 .. versionadded:: 0.57
1961
1962 Returns
1963 -------
1964 list[str]
1965 Raw output lines.
1966
1967 Examples
1968 --------
1969 Default template (backward-compatible):
1970
1971 >>> server.set_buffer('buf_data')
1972 >>> result = server.list_buffers()
1973 >>> len(result) >= 1
1974 True
1975
1976 Project just the names:
1977
1978 >>> server.set_buffer('hello', buffer_name='gap6_demo')
1979 >>> 'gap6_demo' in server.list_buffers(format_string='#{buffer_name}')
1980 True
1981
1982 Filter via tmux:
1983
1984 >>> matches = server.list_buffers(
1985 ... format_string='#{buffer_name}',
1986 ... filter='#{m:gap6_*,#{buffer_name}}',
1987 ... )
1988 >>> 'gap6_demo' in matches
1989 True
1990 """
1991 tmux_args: tuple[str, ...] = ()
1992
1993 if format_string is not None:
1994 tmux_args += ("-F", format_string)
1995
1996 if filter is not None:
1997 tmux_args += ("-f", filter)
1998
1999 proc = self.cmd("list-buffers", *tmux_args)
2000
2001 raise_if_stderr(proc, "list-buffers")
2002
2003 return proc.stdout
2004
2005 def if_shell(
2006 self,
2007 shell_command: str,
2008 tmux_command: str,
2009 *,
2010 else_command: str | None = None,
2011 background: bool | None = None,
2012 target_pane: str | None = None,
2013 ) -> None:
2014 """Execute a tmux command conditionally via ``$ tmux if-shell``.
2015
2016 Parameters
2017 ----------
2018 shell_command : str
2019 Shell command whose exit status determines which tmux command runs.
2020 tmux_command : str
2021 Tmux command to run if *shell_command* succeeds (exit 0).
2022 else_command : str, optional
2023 Tmux command to run if *shell_command* fails (non-zero exit).
2024 background : bool, optional
2025 Run the shell command in the background (``-b`` flag).
2026 target_pane : str, optional
2027 Target pane for format expansion (``-t`` flag).
2028
2029 Examples
2030 --------
2031 >>> server.if_shell('true', 'set -g @if_test yes')
2032 >>> server.cmd('show-options', '-gv', '@if_test').stdout[0]
2033 'yes'
2034 """
2035 tmux_args: tuple[str, ...] = ()
2036
2037 if background:
2038 tmux_args += ("-b",)
2039
2040 if target_pane is not None:
2041 tmux_args += ("-t", target_pane)
2042
2043 tmux_args += (shell_command, tmux_command)
2044
2045 if else_command is not None:
2046 tmux_args += (else_command,)
2047
2048 proc = self.cmd("if-shell", *tmux_args)
2049
2050 raise_if_stderr(proc, "if-shell")
2051
2052 def source_file(
2053 self,
2054 path: StrPath,
2055 *,
2056 quiet: bool | None = None,
2057 parse_only: bool | None = None,
2058 verbose: bool | None = None,
2059 ) -> None:
2060 """Source a tmux configuration file via ``$ tmux source-file``.
2061
2062 Parameters
2063 ----------
2064 path : str or PathLike
2065 Path to the configuration file.
2066 quiet : bool, optional
2067 Suppress errors for missing files (``-q`` flag).
2068 parse_only : bool, optional
2069 Check syntax only, do not execute (``-n`` flag).
2070 verbose : bool, optional
2071 Show parsed commands (``-v`` flag).
2072
2073 Examples
2074 --------
2075 >>> import pathlib
2076 >>> conf = pathlib.Path(request.config.rootdir) / '..' / 'tmp_src.conf'
2077 >>> _ = conf.write_text('set -g @test_source yes')
2078 >>> server.source_file(str(conf))
2079 """
2080 tmux_args: tuple[str, ...] = ()
2081
2082 if quiet:
2083 tmux_args += ("-q",)
2084
2085 if parse_only:
2086 tmux_args += ("-n",)
2087
2088 if verbose:
2089 tmux_args += ("-v",)
2090
2091 tmux_args += (str(pathlib.Path(path).expanduser()),)
2092
2093 proc = self.cmd("source-file", *tmux_args)
2094
2095 raise_if_stderr(proc, "source-file")
2096
2097 def list_clients(self) -> list[str]:
2098 """List connected clients via ``$ tmux list-clients``.
2099
2100 Returns
2101 -------
2102 list[str]
2103 Raw output lines from list-clients.
2104
2105 Examples
2106 --------
2107 >>> isinstance(server.list_clients(), list)
2108 True
2109 """
2110 proc = self.cmd("list-clients")
2111
2112 raise_if_stderr(proc, "list-clients")
2113
2114 return proc.stdout
2115
2116 def switch_client(self, target_session: str) -> None:
2117 """Switch tmux client.
2118
2119 Parameters
2120 ----------
2121 target_session : str
2122 name of the session. fnmatch(3) works.
2123
2124 Raises
2125 ------
2126 :exc:`exc.BadSessionName`
2127 """
2128 session_check_name(target_session)
2129
2130 proc = self.cmd("switch-client", target=target_session)
2131
2132 raise_if_stderr(proc, "switch-client")
2133
2134 def attach_session(self, target_session: str | None = None) -> None:
2135 """Attach tmux session.
2136
2137 Parameters
2138 ----------
2139 target_session : str
2140 name of the session. fnmatch(3) works.
2141
2142 Raises
2143 ------
2144 :exc:`exc.BadSessionName`
2145 """
2146 session_check_name(target_session)
2147 proc = self.cmd("attach-session", target=target_session)
2148
2149 raise_if_stderr(proc, "attach-session")
2150
2151 def new_session(
2152 self,
2153 session_name: str | None = None,
2154 kill_session: bool = False,
2155 attach: bool = False,
2156 start_directory: StrPath | None = None,
2157 window_name: str | None = None,
2158 window_command: str | None = None,
2159 x: int | DashLiteral | None = None,
2160 y: int | DashLiteral | None = None,
2161 environment: dict[str, str] | None = None,
2162 *args: t.Any,
2163 detach_others: bool | None = None,
2164 no_size: bool | None = None,
2165 client_flags: str | None = None,
2166 **kwargs: t.Any,
2167 ) -> Session:
2168 """Create new session, returns new :class:`Session`.
2169
2170 Uses ``-P`` flag to print session info, ``-F`` for return formatting
2171 returns new Session object.
2172
2173 ``$ tmux new-session -d`` will create the session in the background
2174 ``$ tmux new-session -Ad`` will move to the session name if it already
2175 exists. todo: make an option to handle this.
2176
2177 Parameters
2178 ----------
2179 session_name : str, optional
2180 ::
2181
2182 $ tmux new-session -s <session_name>
2183 attach : bool, optional
2184 create session in the foreground. ``attach=False`` is equivalent
2185 to::
2186
2187 $ tmux new-session -d
2188
2189 Other Parameters
2190 ----------------
2191 kill_session : bool, optional
2192 Kill current session if ``$ tmux has-session``.
2193 Useful for testing workspaces.
2194 start_directory : str or PathLike, optional
2195 specifies the working directory in which the
2196 new session is created.
2197 window_name : str, optional
2198 ::
2199
2200 $ tmux new-session -n <window_name>
2201 window_command : str, optional
2202 execute a command on starting the session. The window will close
2203 when the command exits. NOTE: When this command exits the window
2204 will close. This feature is useful for long-running processes
2205 where the closing of the window upon completion is desired.
2206 x : int | str, optional
2207 Force the specified width instead of the tmux default for a
2208 detached session
2209 y : int | str, optional
2210 Force the specified height instead of the tmux default for a
2211 detached session
2212 detach_others : bool, optional
2213 Detach other clients from the session (``-D`` flag).
2214
2215 .. versionadded:: 0.56
2216 no_size : bool, optional
2217 Do not set the initial window size (``-X`` flag).
2218
2219 .. versionadded:: 0.56
2220 client_flags : str, optional
2221 Set client flags (``-f`` flag), e.g. ``no-output``,
2222 ``read-only``. Requires tmux 3.2+.
2223
2224 .. versionadded:: 0.56
2225
2226 Returns
2227 -------
2228 :class:`Session`
2229
2230 Raises
2231 ------
2232 :exc:`exc.BadSessionName`
2233
2234 Examples
2235 --------
2236 Sessions can be created without a session name (0.14.2+):
2237
2238 >>> server.new_session()
2239 Session($2 2)
2240
2241 Creating them in succession will enumerate IDs (via tmux):
2242
2243 >>> server.new_session()
2244 Session($3 3)
2245
2246 With a `session_name`:
2247
2248 >>> server.new_session(session_name='my session')
2249 Session($4 my session)
2250 """
2251 if session_name is not None:
2252 session_check_name(session_name)
2253
2254 if self.has_session(session_name):
2255 if kill_session:
2256 proc = self.cmd("kill-session", target=session_name)
2257 raise_if_stderr(proc, "kill-session")
2258 logger.info(
2259 "existing session killed",
2260 extra={
2261 "tmux_session": session_name,
2262 "tmux_subcommand": "kill-session",
2263 },
2264 )
2265 else:
2266 msg = f"Session named {session_name} exists"
2267 raise exc.TmuxSessionExists(
2268 msg,
2269 )
2270
2271 extra: dict[str, str] = {
2272 "tmux_subcommand": "new-session",
2273 }
2274 if session_name is not None:
2275 extra["tmux_session"] = str(session_name)
2276 logger.debug("creating session", extra=extra)
2277
2278 env = os.environ.get("TMUX")
2279
2280 if env:
2281 del os.environ["TMUX"]
2282
2283 try:
2284 tmux_version = str(get_version(tmux_bin=self.tmux_bin))
2285 _fields, format_string = get_output_format("list-sessions", tmux_version)
2286
2287 tmux_args: tuple[str | int, ...] = (
2288 "-P",
2289 f"-F{format_string}",
2290 )
2291
2292 if detach_others:
2293 tmux_args += ("-D",)
2294
2295 if no_size:
2296 tmux_args += ("-X",)
2297
2298 if client_flags is not None:
2299 tmux_args += ("-f", client_flags)
2300
2301 if session_name is not None:
2302 tmux_args += (f"-s{session_name}",)
2303
2304 if not attach:
2305 tmux_args += ("-d",)
2306
2307 if start_directory:
2308 start_directory = pathlib.Path(start_directory).expanduser()
2309 tmux_args += ("-c", str(start_directory))
2310
2311 if window_name:
2312 tmux_args += ("-n", window_name)
2313
2314 if x is not None:
2315 tmux_args += ("-x", x)
2316
2317 if y is not None:
2318 tmux_args += ("-y", y)
2319
2320 if environment:
2321 for k, v in environment.items():
2322 tmux_args += (f"-e{k}={v}",)
2323
2324 if window_command:
2325 tmux_args += (window_command,)
2326
2327 proc = self.cmd("new-session", *tmux_args)
2328
2329 raise_if_stderr(proc, "new-session")
2330
2331 session_stdout = proc.stdout[0]
2332
2333 finally:
2334 if env:
2335 os.environ["TMUX"] = env
2336
2337 session_data = parse_output(session_stdout, "list-sessions", tmux_version)
2338
2339 session = Session(server=self, **session_data)
2340
2341 info_extra: dict[str, str] = {
2342 "tmux_subcommand": "new-session",
2343 }
2344 if session.session_name is not None:
2345 info_extra["tmux_session"] = str(session.session_name)
2346 logger.info("session created", extra=info_extra)
2347
2348 return session
2349
2350 #
2351 # Relations
2352 #
2353 @property
2354 def sessions(self) -> QueryList[Session]:
2355 """Sessions contained in server.
2356
2357 Can be accessed via
2358 :meth:`.sessions.get() <libtmux._internal.query_list.QueryList.get()>` and
2359 :meth:`.sessions.filter() <libtmux._internal.query_list.QueryList.filter()>`
2360
2361 Returns an empty :class:`~libtmux._internal.query_list.QueryList` when
2362 tmux's ``list-sessions`` fails for any reason — no running daemon, a
2363 missing socket, a permission error, or a subprocess failure. To
2364 distinguish "no sessions" from "tmux unreachable", call
2365 :meth:`Server.is_alive` or :meth:`Server.raise_if_dead`.
2366 """
2367 try:
2368 sessions: list[Session] = [
2369 Session(server=self, **obj)
2370 for obj in fetch_objs(server=self, list_cmd="list-sessions")
2371 ]
2372 except exc.LibTmuxException:
2373 return QueryList([])
2374 return QueryList(sessions)
2375
2376 @property
2377 def windows(self) -> QueryList[Window]:
2378 """Windows contained in server's sessions.
2379
2380 Can be accessed via
2381 :meth:`.windows.get() <libtmux._internal.query_list.QueryList.get()>` and
2382 :meth:`.windows.filter() <libtmux._internal.query_list.QueryList.filter()>`
2383 """
2384 windows: list[Window] = [
2385 Window(server=self, **obj)
2386 for obj in _fetch_or_empty(
2387 server=self,
2388 list_cmd="list-windows",
2389 list_extra_args=("-a",),
2390 )
2391 ]
2392
2393 return QueryList(windows)
2394
2395 @property
2396 def panes(self) -> QueryList[Pane]:
2397 """Panes contained in tmux server (across all windows in all sessions).
2398
2399 Can be accessed via
2400 :meth:`.panes.get() <libtmux._internal.query_list.QueryList.get()>` and
2401 :meth:`.panes.filter() <libtmux._internal.query_list.QueryList.filter()>`
2402 """
2403 panes: list[Pane] = [
2404 Pane(server=self, **obj)
2405 for obj in _fetch_or_empty(
2406 server=self,
2407 list_cmd="list-panes",
2408 list_extra_args=("-a",),
2409 )
2410 ]
2411
2412 return QueryList(panes)
2413
2414 @property
2415 def clients(self) -> QueryList[Client]:
2416 """Clients attached to this tmux server.
2417
2418 Each attached terminal is a separate :class:`Client`. ``server.clients``
2419 returns the typed view; ``client.client_readonly``, ``client.client_termtype``,
2420 ``client.client_session`` etc. read tmux's ``client_*`` format tokens.
2421
2422 Returns an empty :class:`~libtmux._internal.query_list.QueryList` when
2423 tmux's ``list-clients`` fails for any reason — no running daemon, a
2424 missing socket, a permission error, or a subprocess failure. To
2425 distinguish "no clients attached" from "tmux unreachable", call
2426 :meth:`Server.is_alive` or :meth:`Server.raise_if_dead`.
2427
2428 Returns
2429 -------
2430 :class:`~libtmux._internal.query_list.QueryList` of :class:`Client`
2431
2432 Examples
2433 --------
2434 >>> with control_mode() as ctl:
2435 ... names = [c.client_name for c in server.clients]
2436 ... ctl.client_name in names
2437 True
2438 """
2439 try:
2440 clients: list[Client] = [
2441 Client(server=self, **obj)
2442 for obj in fetch_objs(server=self, list_cmd="list-clients")
2443 ]
2444 except exc.LibTmuxException:
2445 return QueryList([])
2446 return QueryList(clients)
2447
2448 def search_sessions(
2449 self,
2450 *,
2451 filter: str | None = None, # noqa: A002
2452 ) -> QueryList[Session]:
2453 """Sessions, optionally filtered by tmux before rows are returned.
2454
2455 Like :attr:`Server.sessions` but adds an optional ``filter`` kwarg
2456 passed to ``$ tmux list-sessions -f <filter>``.
2457
2458 Parameters
2459 ----------
2460 filter : str, optional
2461 tmux format expression (``-f`` flag). tmux omits sessions whose
2462 expanded expression is false before libtmux builds objects.
2463
2464 .. warning::
2465
2466 tmux silently expands a malformed filter (unclosed
2467 ``#{...}``, unknown format token) to empty, which the
2468 filter treats as false — every row is suppressed and no
2469 stderr is emitted. A bad filter is
2470 indistinguishable from "filter matched nothing"; verify
2471 filter syntax against the FORMATS section of ``tmux(1)``.
2472
2473 .. versionadded:: 0.57
2474
2475 Returns
2476 -------
2477 :class:`~libtmux._internal.query_list.QueryList` of :class:`Session`
2478
2479 See Also
2480 --------
2481 :attr:`Server.sessions` : unfiltered :class:`QueryList` of every
2482 session (Python-side ``.filter()`` runs against this).
2483 :ref:`native-filtering` : when to pick ``search_*`` over
2484 ``QueryList.filter()``.
2485
2486 Examples
2487 --------
2488 >>> server.new_session(session_name='gap7_alpha')
2489 Session($... gap7_alpha)
2490 >>> server.new_session(session_name='other_beta')
2491 Session($... other_beta)
2492 >>> matches = server.search_sessions(filter='#{m:gap7_*,#{session_name}}')
2493 >>> [s.session_name for s in matches]
2494 ['gap7_alpha']
2495 """
2496 sessions: list[Session] = [
2497 Session(server=self, **obj)
2498 for obj in _fetch_or_empty(
2499 server=self,
2500 list_cmd="list-sessions",
2501 filter=filter,
2502 )
2503 ]
2504 return QueryList(sessions)
2505
2506 def search_windows(
2507 self,
2508 *,
2509 filter: str | None = None, # noqa: A002
2510 ) -> QueryList[Window]:
2511 """All windows across sessions, optionally filtered by tmux.
2512
2513 Like :attr:`Server.windows` but with a ``filter`` kwarg passed to
2514 ``$ tmux list-windows -a -f <filter>``.
2515
2516 Parameters
2517 ----------
2518 filter : str, optional
2519 tmux format expression (``-f`` flag).
2520
2521 .. warning::
2522
2523 tmux silently expands a malformed filter (unclosed
2524 ``#{...}``, unknown format token) to empty, which the
2525 filter treats as false — every row is suppressed and no
2526 stderr is emitted. A bad filter is
2527 indistinguishable from "filter matched nothing"; verify
2528 filter syntax against the FORMATS section of ``tmux(1)``.
2529
2530 .. versionadded:: 0.57
2531
2532 See Also
2533 --------
2534 :attr:`Server.windows` : unfiltered :class:`QueryList` of every
2535 window across every session (Python-side ``.filter()`` runs
2536 against this).
2537 :ref:`native-filtering` : when to pick ``search_*`` over
2538 ``QueryList.filter()``.
2539
2540 Examples
2541 --------
2542 >>> sess = server.new_session(session_name='gap7_win_demo')
2543 >>> _ = sess.new_window(window_name='gap7_target')
2544 >>> _ = sess.new_window(window_name='other_window')
2545 >>> matches = server.search_windows(filter='#{m:gap7_*,#{window_name}}')
2546 >>> any(w.window_name == 'gap7_target' for w in matches)
2547 True
2548 >>> any(w.window_name == 'other_window' for w in matches)
2549 False
2550 """
2551 windows: list[Window] = [
2552 Window(server=self, **obj)
2553 for obj in _fetch_or_empty(
2554 server=self,
2555 list_cmd="list-windows",
2556 list_extra_args=("-a",),
2557 filter=filter,
2558 )
2559 ]
2560
2561 return QueryList(windows)
2562
2563 def search_panes(
2564 self,
2565 *,
2566 filter: str | None = None, # noqa: A002
2567 ) -> QueryList[Pane]:
2568 """All panes across the server, optionally filtered by tmux.
2569
2570 Like :attr:`Server.panes` but with a ``filter`` kwarg passed to
2571 ``$ tmux list-panes -a -f <filter>``. tmux drops non-matching panes
2572 before libtmux builds objects.
2573
2574 Parameters
2575 ----------
2576 filter : str, optional
2577 tmux format expression (``-f`` flag). Example:
2578 ``'#{m:%5,#{pane_id}}'`` (id match) or
2579 ``'#{C/i:libtmux,#{pane_current_command}}'`` (case-insensitive
2580 substring on the current command).
2581
2582 .. warning::
2583
2584 tmux silently expands a malformed filter (unclosed
2585 ``#{...}``, unknown format token) to empty, which the
2586 filter treats as false — every row is suppressed and no
2587 stderr is emitted. A bad filter is
2588 indistinguishable from "filter matched nothing"; verify
2589 filter syntax against the FORMATS section of ``tmux(1)``.
2590
2591 .. versionadded:: 0.57
2592
2593 See Also
2594 --------
2595 :attr:`Server.panes` : unfiltered :class:`QueryList` of every
2596 pane (Python-side ``.filter()`` runs against this).
2597 :ref:`native-filtering` : when to pick ``search_*`` over
2598 ``QueryList.filter()``.
2599
2600 Examples
2601 --------
2602 >>> sess = server.new_session(session_name='gap7_pane_demo')
2603 >>> window = sess.active_window
2604 >>> target_pane = window.split()
2605 >>> matches = server.search_panes(
2606 ... filter=f'#{{m:{target_pane.pane_id},#{{pane_id}}}}'
2607 ... )
2608 >>> [p.pane_id for p in matches] == [target_pane.pane_id]
2609 True
2610 """
2611 panes: list[Pane] = [
2612 Pane(server=self, **obj)
2613 for obj in _fetch_or_empty(
2614 server=self,
2615 list_cmd="list-panes",
2616 list_extra_args=("-a",),
2617 filter=filter,
2618 )
2619 ]
2620
2621 return QueryList(panes)
2622
2623 #
2624 # Dunder
2625 #
2626 def __eq__(self, other: object) -> bool:
2627 """Equal operator for :class:`Server` object."""
2628 if isinstance(other, Server):
2629 return (
2630 self.socket_name == other.socket_name
2631 and self.socket_path == other.socket_path
2632 )
2633 return False
2634
2635 def __repr__(self) -> str:
2636 """Representation of :class:`Server` object."""
2637 if self.socket_name is not None:
2638 return (
2639 f"{self.__class__.__name__}"
2640 f"(socket_name={getattr(self, 'socket_name', 'default')})"
2641 )
2642 if self.socket_path is not None:
2643 return f"{self.__class__.__name__}(socket_path={self.socket_path})"
2644 return (
2645 f"{self.__class__.__name__}(socket_path=/tmp/tmux-{os.geteuid()}/default)"
2646 )
2647
2648 #
2649 # Legacy: Redundant stuff we want to remove
2650 #
2651 def kill_server(self) -> None:
2652 """Kill tmux server.
2653
2654 Notes
2655 -----
2656 .. deprecated:: 0.30
2657
2658 Deprecated in favor of :meth:`.kill()`.
2659
2660 """
2661 raise exc.DeprecatedError(
2662 deprecated="Server.kill_server()",
2663 replacement="Server.kill()",
2664 version="0.30.0",
2665 )
2666
2667 def _list_panes(self) -> list[PaneDict]:
2668 """Return list of panes in :py:obj:`dict` form.
2669
2670 Retrieved from ``$ tmux(1) list-panes`` stdout.
2671
2672 The :py:obj:`list` is derived from ``stdout`` in
2673 :class:`util.tmux_cmd` which wraps :py:class:`subprocess.Popen`.
2674
2675 .. deprecated:: 0.17
2676
2677 Deprecated in favor of :attr:`.panes`.
2678
2679 """
2680 raise exc.DeprecatedError(
2681 deprecated="Server._list_panes()",
2682 replacement="Server.panes property",
2683 version="0.17.0",
2684 )
2685
2686 def _update_panes(self) -> Server:
2687 """Update internal pane data and return ``self`` for chainability.
2688
2689 .. deprecated:: 0.17
2690
2691 Deprecated in favor of :attr:`.panes` and returning ``self``.
2692
2693 Returns
2694 -------
2695 :class:`Server`
2696 """
2697 raise exc.DeprecatedError(
2698 deprecated="Server._update_panes()",
2699 replacement="Server.panes property",
2700 version="0.17.0",
2701 )
2702
2703 def get_by_id(self, session_id: str) -> Session | None:
2704 """Return session by id. Deprecated in favor of :meth:`.sessions.get()`.
2705
2706 .. deprecated:: 0.16
2707
2708 Deprecated by :meth:`.sessions.get()`.
2709
2710 """
2711 raise exc.DeprecatedError(
2712 deprecated="Server.get_by_id()",
2713 replacement="Server.sessions.get(session_id=..., default=None)",
2714 version="0.16.0",
2715 )
2716
2717 def where(self, kwargs: dict[str, t.Any]) -> list[Session]:
2718 """Filter through sessions, return list of :class:`Session`.
2719
2720 .. deprecated:: 0.17
2721
2722 Deprecated by :meth:`.session.filter()`.
2723
2724 """
2725 raise exc.DeprecatedError(
2726 deprecated="Server.where()",
2727 replacement="Server.sessions.filter()",
2728 version="0.17.0",
2729 )
2730
2731 def find_where(self, kwargs: dict[str, t.Any]) -> Session | None:
2732 """Filter through sessions, return first :class:`Session`.
2733
2734 .. deprecated:: 0.17
2735
2736 Slated to be removed in favor of :meth:`.sessions.get()`.
2737
2738 """
2739 raise exc.DeprecatedError(
2740 deprecated="Server.find_where()",
2741 replacement="Server.sessions.get(default=None, **kwargs)",
2742 version="0.17.0",
2743 )
2744
2745 def _list_windows(self) -> list[WindowDict]:
2746 """Return list of windows in :py:obj:`dict` form.
2747
2748 Retrieved from ``$ tmux(1) list-windows`` stdout.
2749
2750 The :py:obj:`list` is derived from ``stdout`` in
2751 :class:`common.tmux_cmd` which wraps :py:class:`subprocess.Popen`.
2752
2753 .. deprecated:: 0.17
2754
2755 Slated to be removed in favor of :attr:`.windows`.
2756
2757 """
2758 raise exc.DeprecatedError(
2759 deprecated="Server._list_windows()",
2760 replacement="Server.windows property",
2761 version="0.17.0",
2762 )
2763
2764 def _update_windows(self) -> Server:
2765 """Update internal window data and return ``self`` for chainability.
2766
2767 .. deprecated:: 0.17
2768
2769 Deprecated in favor of :attr:`.windows` and returning ``self``.
2770
2771 """
2772 raise exc.DeprecatedError(
2773 deprecated="Server._update_windows()",
2774 replacement="Server.windows property",
2775 version="0.17.0",
2776 )
2777
2778 @property
2779 def _sessions(self) -> list[SessionDict]:
2780 """Property / alias to return :meth:`~._list_sessions`.
2781
2782 .. deprecated:: 0.17
2783
2784 Slated to be removed in favor of :attr:`.sessions`.
2785
2786 """
2787 raise exc.DeprecatedError(
2788 deprecated="Server._sessions",
2789 replacement="Server.sessions property",
2790 version="0.17.0",
2791 )
2792
2793 def _list_sessions(self) -> list[SessionDict]:
2794 """Return list of session object dictionaries.
2795
2796 .. deprecated:: 0.17
2797
2798 Slated to be removed in favor of :attr:`.sessions`.
2799 """
2800 raise exc.DeprecatedError(
2801 deprecated="Server._list_sessions()",
2802 replacement="Server.sessions property",
2803 version="0.17.0",
2804 )
2805
2806 def list_sessions(self) -> list[Session]:
2807 """Return list of :class:`Session` from the ``tmux(1)`` session.
2808
2809 .. deprecated:: 0.17
2810
2811 Slated to be removed in favor of :attr:`.sessions`.
2812
2813 Returns
2814 -------
2815 list of :class:`Session`
2816 """
2817 raise exc.DeprecatedError(
2818 deprecated="Server.list_sessions()",
2819 replacement="Server.sessions property",
2820 version="0.17.0",
2821 )
2822
2823 @property
2824 def children(self) -> QueryList[Session]:
2825 """Was used by TmuxRelationalObject (but that's longer used in this class).
2826
2827 .. deprecated:: 0.17
2828
2829 Slated to be removed in favor of :attr:`.sessions`.
2830
2831 """
2832 raise exc.DeprecatedError(
2833 deprecated="Server.children",
2834 replacement="Server.sessions property",
2835 version="0.17.0",
2836 )