| 1 |
"""Pythonization of the :term:`tmux(1)` session. |
| 2 |
|
| 3 |
libtmux.session |
| 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._internal.query_list import QueryList |
| 17 |
from libtmux.common import has_gte_version, raise_if_stderr, tmux_cmd |
| 18 |
from libtmux.constants import WINDOW_DIRECTION_FLAG_MAP, OptionScope, WindowDirection |
| 19 |
from libtmux.formats import FORMAT_SEPARATOR |
| 20 |
from libtmux.hooks import HooksMixin |
| 21 |
from libtmux.neo import Obj, fetch_obj, fetch_objs |
| 22 |
from libtmux.options import OptionsMixin |
| 23 |
from libtmux.pane import Pane |
| 24 |
from libtmux.window import Window |
| 25 |
|
| 26 |
from . import exc |
| 27 |
from .common import ( |
| 28 |
EnvironmentMixin, |
| 29 |
WindowDict, |
| 30 |
session_check_name, |
| 31 |
) |
| 32 |
|
| 33 |
if t.TYPE_CHECKING: |
| 34 |
import sys |
| 35 |
import types |
| 36 |
|
| 37 |
from libtmux._internal.types import StrPath |
| 38 |
from libtmux.common import tmux_cmd |
| 39 |
|
| 40 |
if sys.version_info >= (3, 11): |
| 41 |
from typing import Self |
| 42 |
else: |
| 43 |
from typing_extensions import Self |
| 44 |
|
| 45 |
from .server import Server |
| 46 |
|
| 47 |
|
| 48 |
logger = logging.getLogger(__name__) |
| 49 |
|
| 50 |
|
| 51 |
@dataclasses.dataclass() |
| 52 |
class Session( |
| 53 |
Obj, |
| 54 |
EnvironmentMixin, |
| 55 |
OptionsMixin, |
| 56 |
HooksMixin, |
| 57 |
): |
| 58 |
""":term:`tmux(1)` :term:`Session` [session_manual]_. |
| 59 |
|
| 60 |
Holds :class:`Window` objects. |
| 61 |
|
| 62 |
Parameters |
| 63 |
---------- |
| 64 |
server : :class:`Server` |
| 65 |
|
| 66 |
Examples |
| 67 |
-------- |
| 68 |
>>> session |
| 69 |
Session($1 ...) |
| 70 |
|
| 71 |
>>> session.windows |
| 72 |
[Window(@1 ...:..., Session($1 ...)] |
| 73 |
|
| 74 |
>>> session.active_window |
| 75 |
Window(@1 ...:..., Session($1 ...)) |
| 76 |
|
| 77 |
>>> session.active_pane |
| 78 |
Pane(%1 Window(@1 ...:..., Session($1 ...))) |
| 79 |
|
| 80 |
The session can be used as a context manager to ensure proper cleanup: |
| 81 |
|
| 82 |
>>> with server.new_session() as session: |
| 83 |
... window = session.new_window() |
| 84 |
... # Do work with the window |
| 85 |
... # Session will be killed automatically when exiting the context |
| 86 |
|
| 87 |
References |
| 88 |
---------- |
| 89 |
.. [session_manual] tmux session. openbsd manpage for TMUX(1). |
| 90 |
"When tmux is started it creates a new session with a single window |
| 91 |
and displays it on screen..." |
| 92 |
|
| 93 |
"A session is a single collection of pseudo terminals under the |
| 94 |
management of tmux. Each session has one or more windows linked to |
| 95 |
it." |
| 96 |
|
| 97 |
https://man.openbsd.org/tmux.1#DESCRIPTION. Accessed April 1st, 2018. |
| 98 |
""" |
| 99 |
|
| 100 |
default_option_scope: OptionScope | None = None |
| 101 |
default_hook_scope: OptionScope | None = None |
| 102 |
server: Server |
| 103 |
|
| 104 |
def __enter__(self) -> Self: |
| 105 |
"""Enter the context, returning self. |
| 106 |
|
| 107 |
Returns |
| 108 |
------- |
| 109 |
:class:`Session` |
| 110 |
The session instance |
| 111 |
""" |
| 112 |
return self |
| 113 |
|
| 114 |
def __exit__( |
| 115 |
self, |
| 116 |
exc_type: type[BaseException] | None, |
| 117 |
exc_value: BaseException | None, |
| 118 |
exc_tb: types.TracebackType | None, |
| 119 |
) -> None: |
| 120 |
"""Exit the context, killing the session if it exists. |
| 121 |
|
| 122 |
Parameters |
| 123 |
---------- |
| 124 |
exc_type : type[BaseException] | None |
| 125 |
The type of the exception that was raised |
| 126 |
exc_value : BaseException | None |
| 127 |
The instance of the exception that was raised |
| 128 |
exc_tb : types.TracebackType | None |
| 129 |
The traceback of the exception that was raised |
| 130 |
""" |
| 131 |
if self.session_name is not None and self.server.has_session(self.session_name): |
| 132 |
self.kill() |
| 133 |
|
| 134 |
def refresh(self) -> None: |
| 135 |
"""Refresh session attributes from tmux. |
| 136 |
|
| 137 |
Raises |
| 138 |
------ |
| 139 |
ValueError |
| 140 |
When ``session_id`` is unset. Surfaces a clear error under |
| 141 |
``python -O``, where an ``assert`` would be stripped. |
| 142 |
""" |
| 143 |
if self.session_id is None: |
| 144 |
msg = "Session must have a session_id to refresh" |
| 145 |
raise ValueError(msg) |
| 146 |
return super()._refresh( |
| 147 |
obj_key="session_id", |
| 148 |
obj_id=self.session_id, |
| 149 |
list_cmd="list-sessions", |
| 150 |
) |
| 151 |
|
| 152 |
@classmethod |
| 153 |
def from_session_id(cls, server: Server, session_id: str) -> Session: |
| 154 |
"""Create Session from existing session_id.""" |
| 155 |
session = fetch_obj( |
| 156 |
obj_key="session_id", |
| 157 |
obj_id=session_id, |
| 158 |
list_cmd="list-sessions", |
| 159 |
server=server, |
| 160 |
) |
| 161 |
return cls(server=server, **session) |
| 162 |
|
| 163 |
|
| 164 |
|
| 165 |
|
| 166 |
@property |
| 167 |
def windows(self) -> QueryList[Window]: |
| 168 |
"""Windows contained by session. |
| 169 |
|
| 170 |
Can be accessed via |
| 171 |
:meth:`.windows.get() <libtmux._internal.query_list.QueryList.get()>` and |
| 172 |
:meth:`.windows.filter() <libtmux._internal.query_list.QueryList.filter()>` |
| 173 |
""" |
| 174 |
windows: list[Window] = [ |
| 175 |
Window(server=self.server, **obj) |
| 176 |
for obj in fetch_objs( |
| 177 |
list_cmd="list-windows", |
| 178 |
list_extra_args=["-t", str(self.session_id)], |
| 179 |
server=self.server, |
| 180 |
) |
| 181 |
if obj.get("session_id") == self.session_id |
| 182 |
] |
| 183 |
|
| 184 |
return QueryList(windows) |
| 185 |
|
| 186 |
@property |
| 187 |
def panes(self) -> QueryList[Pane]: |
| 188 |
"""Panes contained by session's windows. |
| 189 |
|
| 190 |
Can be accessed via |
| 191 |
:meth:`.panes.get() <libtmux._internal.query_list.QueryList.get()>` and |
| 192 |
:meth:`.panes.filter() <libtmux._internal.query_list.QueryList.filter()>` |
| 193 |
""" |
| 194 |
panes: list[Pane] = [ |
| 195 |
Pane(server=self.server, **obj) |
| 196 |
for obj in fetch_objs( |
| 197 |
list_cmd="list-panes", |
| 198 |
list_extra_args=["-s", "-t", str(self.session_id)], |
| 199 |
server=self.server, |
| 200 |
) |
| 201 |
if obj.get("session_id") == self.session_id |
| 202 |
] |
| 203 |
|
| 204 |
return QueryList(panes) |
| 205 |
|
| 206 |
def search_windows( |
| 207 |
self, |
| 208 |
*, |
| 209 |
filter: str | None = None, |
| 210 |
) -> QueryList[Window]: |
| 211 |
"""Windows in this session, optionally filtered by tmux. |
| 212 |
|
| 213 |
Like :attr:`Session.windows` but with a ``filter`` kwarg passed to |
| 214 |
``$ tmux list-windows -t <session> -f <filter>``. |
| 215 |
|
| 216 |
Parameters |
| 217 |
---------- |
| 218 |
filter : str, optional |
| 219 |
tmux format expression (``-f`` flag). |
| 220 |
|
| 221 |
.. warning:: |
| 222 |
|
| 223 |
tmux silently expands a malformed filter (unclosed |
| 224 |
``#{...}``, unknown format token) to empty, which the |
| 225 |
filter treats as false — every row is suppressed and no |
| 226 |
stderr is emitted. A bad filter is |
| 227 |
indistinguishable from "filter matched nothing"; verify |
| 228 |
filter syntax against the FORMATS section of ``tmux(1)``. |
| 229 |
|
| 230 |
.. versionadded:: 0.57 |
| 231 |
|
| 232 |
See Also |
| 233 |
-------- |
| 234 |
:attr:`Session.windows` : unfiltered :class:`QueryList` of every |
| 235 |
window in this session (Python-side ``.filter()`` runs |
| 236 |
against this). |
| 237 |
:ref:`native-filtering` : when to pick ``search_*`` over |
| 238 |
``QueryList.filter()``. |
| 239 |
|
| 240 |
Examples |
| 241 |
-------- |
| 242 |
>>> _ = session.new_window(window_name='gap7s_target') |
| 243 |
>>> _ = session.new_window(window_name='other_window') |
| 244 |
>>> matches = session.search_windows(filter='#{m:gap7s_*,#{window_name}}') |
| 245 |
>>> [w.window_name for w in matches] |
| 246 |
['gap7s_target'] |
| 247 |
""" |
| 248 |
windows: list[Window] = [ |
| 249 |
Window(server=self.server, **obj) |
| 250 |
for obj in fetch_objs( |
| 251 |
list_cmd="list-windows", |
| 252 |
list_extra_args=["-t", str(self.session_id)], |
| 253 |
server=self.server, |
| 254 |
filter=filter, |
| 255 |
) |
| 256 |
if obj.get("session_id") == self.session_id |
| 257 |
] |
| 258 |
|
| 259 |
return QueryList(windows) |
| 260 |
|
| 261 |
def search_panes( |
| 262 |
self, |
| 263 |
*, |
| 264 |
filter: str | None = None, |
| 265 |
) -> QueryList[Pane]: |
| 266 |
"""Panes in this session, optionally filtered by tmux. |
| 267 |
|
| 268 |
Like :attr:`Session.panes` but with a ``filter`` kwarg passed to |
| 269 |
``$ tmux list-panes -s -t <session> -f <filter>``. |
| 270 |
|
| 271 |
Parameters |
| 272 |
---------- |
| 273 |
filter : str, optional |
| 274 |
tmux format expression (``-f`` flag). |
| 275 |
|
| 276 |
.. warning:: |
| 277 |
|
| 278 |
tmux silently expands a malformed filter (unclosed |
| 279 |
``#{...}``, unknown format token) to empty, which the |
| 280 |
filter treats as false — every row is suppressed and no |
| 281 |
stderr is emitted. A bad filter is |
| 282 |
indistinguishable from "filter matched nothing"; verify |
| 283 |
filter syntax against the FORMATS section of ``tmux(1)``. |
| 284 |
|
| 285 |
.. versionadded:: 0.57 |
| 286 |
|
| 287 |
See Also |
| 288 |
-------- |
| 289 |
:attr:`Session.panes` : unfiltered :class:`QueryList` of every |
| 290 |
pane in this session (Python-side ``.filter()`` runs against |
| 291 |
this). |
| 292 |
:ref:`native-filtering` : when to pick ``search_*`` over |
| 293 |
``QueryList.filter()``. |
| 294 |
|
| 295 |
Examples |
| 296 |
-------- |
| 297 |
>>> target_pane = session.active_window.split() |
| 298 |
>>> matches = session.search_panes( |
| 299 |
... filter=f'#{{m:{target_pane.pane_id},#{{pane_id}}}}' |
| 300 |
... ) |
| 301 |
>>> [p.pane_id for p in matches] == [target_pane.pane_id] |
| 302 |
True |
| 303 |
""" |
| 304 |
panes: list[Pane] = [ |
| 305 |
Pane(server=self.server, **obj) |
| 306 |
for obj in fetch_objs( |
| 307 |
list_cmd="list-panes", |
| 308 |
list_extra_args=["-s", "-t", str(self.session_id)], |
| 309 |
server=self.server, |
| 310 |
filter=filter, |
| 311 |
) |
| 312 |
if obj.get("session_id") == self.session_id |
| 313 |
] |
| 314 |
|
| 315 |
return QueryList(panes) |
| 316 |
|
| 317 |
|
| 318 |
|
| 319 |
|
| 320 |
def cmd( |
| 321 |
self, |
| 322 |
cmd: str, |
| 323 |
*args: t.Any, |
| 324 |
target: str | int | None = None, |
| 325 |
) -> tmux_cmd: |
| 326 |
"""Execute tmux subcommand within session context. |
| 327 |
|
| 328 |
Automatically binds target by adding ``-t`` for object's session ID to the |
| 329 |
command. Pass ``target`` to keyword arguments to override. |
| 330 |
|
| 331 |
Examples |
| 332 |
-------- |
| 333 |
>>> session.cmd('new-window', '-P').stdout[0] |
| 334 |
'libtmux...:....0' |
| 335 |
|
| 336 |
From raw output to an enriched `Window` object: |
| 337 |
|
| 338 |
>>> Window.from_window_id(window_id=session.cmd( |
| 339 |
... 'new-window', '-P', '-F#{window_id}').stdout[0], server=session.server) |
| 340 |
Window(@... ...:..., Session($1 libtmux_...)) |
| 341 |
|
| 342 |
Parameters |
| 343 |
---------- |
| 344 |
target : str, optional |
| 345 |
Optional custom target override. By default, the target is the session ID. |
| 346 |
|
| 347 |
Returns |
| 348 |
------- |
| 349 |
:meth:`server.cmd` |
| 350 |
|
| 351 |
Notes |
| 352 |
----- |
| 353 |
.. versionchanged:: 0.34 |
| 354 |
|
| 355 |
Passing target by ``-t`` is ignored. Use ``target`` keyword argument instead. |
| 356 |
|
| 357 |
.. versionchanged:: 0.8 |
| 358 |
|
| 359 |
Renamed from ``.tmux`` to ``.cmd``. |
| 360 |
""" |
| 361 |
if target is None: |
| 362 |
target = self.session_id |
| 363 |
return self.server.cmd(cmd, *args, target=target) |
| 364 |
|
| 365 |
""" |
| 366 |
Commands (tmux-like) |
| 367 |
""" |
| 368 |
|
| 369 |
def lock_session(self) -> None: |
| 370 |
"""Lock this session via ``$ tmux lock-session``. |
| 371 |
|
| 372 |
>>> session.lock_session() |
| 373 |
""" |
| 374 |
proc = self.cmd("lock-session") |
| 375 |
|
| 376 |
raise_if_stderr(proc, "lock-session") |
| 377 |
|
| 378 |
def detach_client( |
| 379 |
self, |
| 380 |
*, |
| 381 |
shell_command: str | None = None, |
| 382 |
) -> None: |
| 383 |
"""Detach every client attached to this session. |
| 384 |
|
| 385 |
Maps to ``$ tmux detach-client -s <session_id>`` — the only |
| 386 |
``detach-client`` flag group that is genuinely session-scoped. |
| 387 |
|
| 388 |
Parameters |
| 389 |
---------- |
| 390 |
shell_command : str, optional |
| 391 |
Run a shell command on the detached client(s) after detach |
| 392 |
(``-E`` flag). |
| 393 |
|
| 394 |
See Also |
| 395 |
-------- |
| 396 |
:meth:`Server.detach_client` : detach a specific client by name |
| 397 |
(``-t`` flag) — server-wide client lookup, not session-scoped. |
| 398 |
:meth:`Server.detach_all_clients` : detach every client on the |
| 399 |
server (``-a`` flag). |
| 400 |
|
| 401 |
Examples |
| 402 |
-------- |
| 403 |
>>> with control_mode() as ctl: |
| 404 |
... session.detach_client() |
| 405 |
""" |
| 406 |
tmux_args: tuple[str, ...] = () |
| 407 |
|
| 408 |
if shell_command is not None: |
| 409 |
tmux_args += ("-E", shell_command) |
| 410 |
|
| 411 |
tmux_args += ("-s", str(self.session_id)) |
| 412 |
|
| 413 |
proc = self.server.cmd("detach-client", *tmux_args) |
| 414 |
|
| 415 |
raise_if_stderr(proc, "detach-client") |
| 416 |
|
| 417 |
def last_window(self) -> Window: |
| 418 |
"""Select the last (previously selected) window. |
| 419 |
|
| 420 |
Wraps ``$ tmux last-window``. |
| 421 |
|
| 422 |
Returns |
| 423 |
------- |
| 424 |
:class:`Window` |
| 425 |
The newly active window. |
| 426 |
|
| 427 |
Examples |
| 428 |
-------- |
| 429 |
>>> w1 = session.new_window(window_name='lw_a') |
| 430 |
>>> w2 = session.new_window(window_name='lw_b', attach=True) |
| 431 |
>>> session.last_window() |
| 432 |
Window(...) |
| 433 |
""" |
| 434 |
proc = self.cmd("last-window") |
| 435 |
|
| 436 |
raise_if_stderr(proc, "last-window") |
| 437 |
|
| 438 |
return self.active_window |
| 439 |
|
| 440 |
def next_window(self) -> Window: |
| 441 |
"""Select the next window. |
| 442 |
|
| 443 |
Wraps ``$ tmux next-window``. |
| 444 |
|
| 445 |
Returns |
| 446 |
------- |
| 447 |
:class:`Window` |
| 448 |
The newly active window. |
| 449 |
|
| 450 |
Examples |
| 451 |
-------- |
| 452 |
>>> w = session.new_window(window_name='nw_test') |
| 453 |
>>> session.next_window() |
| 454 |
Window(...) |
| 455 |
""" |
| 456 |
proc = self.cmd("next-window") |
| 457 |
|
| 458 |
raise_if_stderr(proc, "next-window") |
| 459 |
|
| 460 |
return self.active_window |
| 461 |
|
| 462 |
def previous_window(self) -> Window: |
| 463 |
"""Select the previous window. |
| 464 |
|
| 465 |
Wraps ``$ tmux previous-window``. |
| 466 |
|
| 467 |
Returns |
| 468 |
------- |
| 469 |
:class:`Window` |
| 470 |
The newly active window. |
| 471 |
|
| 472 |
Examples |
| 473 |
-------- |
| 474 |
>>> w = session.new_window(window_name='pw_test') |
| 475 |
>>> session.previous_window() |
| 476 |
Window(...) |
| 477 |
""" |
| 478 |
proc = self.cmd("previous-window") |
| 479 |
|
| 480 |
raise_if_stderr(proc, "previous-window") |
| 481 |
|
| 482 |
return self.active_window |
| 483 |
|
| 484 |
def select_window(self, target_window: str | int) -> Window: |
| 485 |
"""Select window and return the selected window. |
| 486 |
|
| 487 |
Parameters |
| 488 |
---------- |
| 489 |
window : str |
| 490 |
``target_window`` can also be 'last-window' (``-l``), 'next-window' |
| 491 |
(``-n``), or 'previous-window' (``-p``) |
| 492 |
|
| 493 |
Returns |
| 494 |
------- |
| 495 |
:class:`Window` |
| 496 |
|
| 497 |
Notes |
| 498 |
----- |
| 499 |
.. todo:: |
| 500 |
|
| 501 |
assure ``-l``, ``-n``, ``-p`` work. |
| 502 |
""" |
| 503 |
|
| 504 |
|
| 505 |
|
| 506 |
target = f"{self.session_id}:{target_window}" |
| 507 |
|
| 508 |
proc = self.cmd("select-window", target=target) |
| 509 |
|
| 510 |
raise_if_stderr(proc, "select-window") |
| 511 |
|
| 512 |
return self.active_window |
| 513 |
|
| 514 |
|
| 515 |
|
| 516 |
|
| 517 |
@property |
| 518 |
def active_pane(self) -> Pane | None: |
| 519 |
"""Return the active :class:`Pane` object.""" |
| 520 |
return self.active_window.active_pane |
| 521 |
|
| 522 |
@property |
| 523 |
def active_window(self) -> Window: |
| 524 |
"""Return the active :class:`Window` object.""" |
| 525 |
active_windows = self.windows.filter(window_active="1") |
| 526 |
|
| 527 |
if len(active_windows) == 1: |
| 528 |
return next(iter(active_windows)) |
| 529 |
if len(active_windows) == 0: |
| 530 |
raise exc.NoActiveWindow |
| 531 |
raise exc.MultipleActiveWindows(count=len(active_windows)) |
| 532 |
|
| 533 |
if len(self._windows) == 0: |
| 534 |
raise exc.NoWindowsExist |
| 535 |
return None |
| 536 |
|
| 537 |
def attach( |
| 538 |
self, |
| 539 |
exit_: bool | None = None, |
| 540 |
flags_: list[str] | None = None, |
| 541 |
) -> Session: |
| 542 |
"""Return ``$ tmux attach-session`` aka alias: ``$ tmux attach``. |
| 543 |
|
| 544 |
Examples |
| 545 |
-------- |
| 546 |
>>> session = server.new_session() |
| 547 |
|
| 548 |
>>> session not in server.attached_sessions |
| 549 |
True |
| 550 |
""" |
| 551 |
flags: tuple[str, ...] = () |
| 552 |
|
| 553 |
if exit_ is not None and exit_: |
| 554 |
flags += ("-x",) |
| 555 |
|
| 556 |
if flags_ is not None and isinstance(flags_, list): |
| 557 |
flags += tuple(f"{','.join(flags_)}") |
| 558 |
|
| 559 |
proc = self.cmd( |
| 560 |
"attach-session", |
| 561 |
*flags, |
| 562 |
) |
| 563 |
|
| 564 |
raise_if_stderr(proc, "attach-session") |
| 565 |
|
| 566 |
return self |
| 567 |
|
| 568 |
def kill( |
| 569 |
self, |
| 570 |
all_except: bool | None = None, |
| 571 |
clear: bool | None = None, |
| 572 |
group: bool | None = None, |
| 573 |
) -> None: |
| 574 |
"""Kill :class:`Session`, closes linked windows and detach all clients. |
| 575 |
|
| 576 |
``$ tmux kill-session``. |
| 577 |
|
| 578 |
Parameters |
| 579 |
---------- |
| 580 |
all_except : bool, optional |
| 581 |
Kill all sessions in server except this one. |
| 582 |
clear : bool, optional |
| 583 |
Clear alerts (bell, activity, or silence) in all windows. |
| 584 |
group : bool, optional |
| 585 |
Kill all sessions in this session's group (``-g`` flag). |
| 586 |
Requires tmux 3.7+. If used with tmux < 3.7, a warning is issued |
| 587 |
and the flag is ignored. |
| 588 |
|
| 589 |
Examples |
| 590 |
-------- |
| 591 |
Kill a session: |
| 592 |
|
| 593 |
>>> session_1 = server.new_session() |
| 594 |
|
| 595 |
>>> session_1 in server.sessions |
| 596 |
True |
| 597 |
|
| 598 |
>>> session_1.kill() |
| 599 |
|
| 600 |
>>> session_1 not in server.sessions |
| 601 |
True |
| 602 |
|
| 603 |
Kill all sessions except the current one: |
| 604 |
|
| 605 |
>>> one_session_to_rule_them_all = server.new_session() |
| 606 |
|
| 607 |
>>> other_sessions = server.new_session( |
| 608 |
... ), server.new_session() |
| 609 |
|
| 610 |
>>> all([w in server.sessions for w in other_sessions]) |
| 611 |
True |
| 612 |
|
| 613 |
>>> one_session_to_rule_them_all.kill(all_except=True) |
| 614 |
|
| 615 |
>>> all([w not in server.sessions for w in other_sessions]) |
| 616 |
True |
| 617 |
|
| 618 |
>>> one_session_to_rule_them_all in server.sessions |
| 619 |
True |
| 620 |
""" |
| 621 |
flags: tuple[str, ...] = () |
| 622 |
|
| 623 |
if all_except: |
| 624 |
flags += ("-a",) |
| 625 |
|
| 626 |
if clear: |
| 627 |
flags += ("-C",) |
| 628 |
|
| 629 |
if group: |
| 630 |
if has_gte_version("3.7", tmux_bin=self.server.tmux_bin): |
| 631 |
flags += ("-g",) |
| 632 |
else: |
| 633 |
warnings.warn( |
| 634 |
"group requires tmux 3.7+, ignoring", |
| 635 |
stacklevel=2, |
| 636 |
) |
| 637 |
|
| 638 |
proc = self.cmd( |
| 639 |
"kill-session", |
| 640 |
*flags, |
| 641 |
) |
| 642 |
|
| 643 |
raise_if_stderr(proc, "kill-session") |
| 644 |
|
| 645 |
msg = "other sessions killed" if all_except else "session killed" |
| 646 |
extra: dict[str, str] = { |
| 647 |
"tmux_subcommand": "kill-session", |
| 648 |
} |
| 649 |
if self.session_name is not None: |
| 650 |
extra["tmux_session"] = str(self.session_name) |
| 651 |
if self.session_id is not None: |
| 652 |
extra["tmux_target"] = str(self.session_id) |
| 653 |
logger.info(msg, extra=extra) |
| 654 |
|
| 655 |
def switch_client(self) -> Session: |
| 656 |
"""Switch client to session. |
| 657 |
|
| 658 |
Raises |
| 659 |
------ |
| 660 |
:exc:`exc.LibTmuxException` |
| 661 |
""" |
| 662 |
proc = self.cmd("switch-client") |
| 663 |
|
| 664 |
raise_if_stderr(proc, "switch-client") |
| 665 |
|
| 666 |
return self |
| 667 |
|
| 668 |
def rename_session(self, new_name: str) -> Session: |
| 669 |
"""Rename session and return new :class:`Session` object. |
| 670 |
|
| 671 |
Parameters |
| 672 |
---------- |
| 673 |
new_name : str |
| 674 |
new session name |
| 675 |
|
| 676 |
Raises |
| 677 |
------ |
| 678 |
:exc:`exc.BadSessionName` |
| 679 |
""" |
| 680 |
session_check_name(new_name) |
| 681 |
|
| 682 |
proc = self.cmd("rename-session", new_name) |
| 683 |
|
| 684 |
raise_if_stderr(proc, "rename-session") |
| 685 |
|
| 686 |
self.refresh() |
| 687 |
|
| 688 |
extra: dict[str, str] = { |
| 689 |
"tmux_subcommand": "rename-session", |
| 690 |
"tmux_session": new_name, |
| 691 |
} |
| 692 |
if self.session_id is not None: |
| 693 |
extra["tmux_target"] = str(self.session_id) |
| 694 |
logger.info("session renamed", extra=extra) |
| 695 |
|
| 696 |
return self |
| 697 |
|
| 698 |
def new_window( |
| 699 |
self, |
| 700 |
window_name: str | None = None, |
| 701 |
*, |
| 702 |
start_directory: StrPath | None = None, |
| 703 |
attach: bool = False, |
| 704 |
window_index: str = "", |
| 705 |
window_shell: str | None = None, |
| 706 |
environment: dict[str, str] | None = None, |
| 707 |
direction: WindowDirection | None = None, |
| 708 |
target_window: str | None = None, |
| 709 |
kill_existing: bool | None = None, |
| 710 |
select_existing: bool | None = None, |
| 711 |
) -> Window: |
| 712 |
"""Create new window, returns new :class:`Window`. |
| 713 |
|
| 714 |
By default, this will make the window active. For the new window |
| 715 |
to be created and not set to current, pass in ``attach=False``. |
| 716 |
|
| 717 |
Parameters |
| 718 |
---------- |
| 719 |
window_name : str, optional |
| 720 |
start_directory : str, optional |
| 721 |
working directory in which the new window is created. |
| 722 |
attach : bool, optional |
| 723 |
make new window the current window after creating it, default True. |
| 724 |
window_index : str |
| 725 |
create the new window at the given index position. Default is empty |
| 726 |
string which will create the window in the next available position. |
| 727 |
window_shell : str, optional |
| 728 |
execute a command on starting the window. The window will close |
| 729 |
when the command exits. |
| 730 |
|
| 731 |
.. note:: |
| 732 |
When this command exits the window will close. This feature is |
| 733 |
useful for long-running processes where the closing of the |
| 734 |
window upon completion is desired. |
| 735 |
|
| 736 |
direction : WindowDirection, optional |
| 737 |
Insert window before or after target window. |
| 738 |
|
| 739 |
target_window : str, optional |
| 740 |
Used by :meth:`Window.new_window` to specify the target window. |
| 741 |
kill_existing : bool, optional |
| 742 |
Destroy the window at the target index if it already exists |
| 743 |
(``-k`` flag). |
| 744 |
|
| 745 |
.. versionadded:: 0.56 |
| 746 |
select_existing : bool, optional |
| 747 |
If a window with the given name already exists, select it instead |
| 748 |
of creating a new one (``-S`` flag). |
| 749 |
|
| 750 |
.. versionadded:: 0.56 |
| 751 |
|
| 752 |
.. versionchanged:: 0.28.0 |
| 753 |
|
| 754 |
``attach`` default changed from ``True`` to ``False``. |
| 755 |
|
| 756 |
See Also |
| 757 |
-------- |
| 758 |
:meth:`Window.new_window()` |
| 759 |
|
| 760 |
Examples |
| 761 |
-------- |
| 762 |
>>> window_initial = session.new_window(window_name='Example') |
| 763 |
>>> window_initial |
| 764 |
Window(@... 2:Example, Session($1 libtmux_...)) |
| 765 |
>>> window_initial.window_index |
| 766 |
'2' |
| 767 |
|
| 768 |
>>> window_before = session.new_window( |
| 769 |
... window_name='Window before', direction=WindowDirection.Before) |
| 770 |
>>> window_initial.refresh() |
| 771 |
>>> window_before |
| 772 |
Window(@... 1:Window before, Session($1 libtmux_...)) |
| 773 |
>>> window_initial |
| 774 |
Window(@... 3:Example, Session($1 libtmux_...)) |
| 775 |
|
| 776 |
>>> window_after = session.new_window( |
| 777 |
... window_name='Window after', direction=WindowDirection.After) |
| 778 |
>>> window_initial.refresh() |
| 779 |
>>> window_after.refresh() |
| 780 |
>>> window_after |
| 781 |
Window(@... 3:Window after, Session($1 libtmux_...)) |
| 782 |
>>> window_initial |
| 783 |
Window(@... 4:Example, Session($1 libtmux_...)) |
| 784 |
>>> window_before |
| 785 |
Window(@... 1:Window before, Session($1 libtmux_...)) |
| 786 |
|
| 787 |
Returns |
| 788 |
------- |
| 789 |
:class:`Window` |
| 790 |
The newly created window. |
| 791 |
""" |
| 792 |
window_args: tuple[str, ...] = () |
| 793 |
|
| 794 |
if not attach: |
| 795 |
window_args += ("-d",) |
| 796 |
|
| 797 |
window_args += ("-P",) |
| 798 |
|
| 799 |
|
| 800 |
if start_directory: |
| 801 |
start_directory = pathlib.Path(start_directory).expanduser() |
| 802 |
window_args += (f"-c{start_directory}",) |
| 803 |
|
| 804 |
window_args += ("-F#{window_id}",) |
| 805 |
if window_name is not None and isinstance(window_name, str): |
| 806 |
window_args += ("-n", window_name) |
| 807 |
|
| 808 |
if environment: |
| 809 |
for k, v in environment.items(): |
| 810 |
window_args += (f"-e{k}={v}",) |
| 811 |
|
| 812 |
if direction is not None: |
| 813 |
window_args += (WINDOW_DIRECTION_FLAG_MAP[direction],) |
| 814 |
|
| 815 |
if kill_existing: |
| 816 |
window_args += ("-k",) |
| 817 |
|
| 818 |
if select_existing: |
| 819 |
window_args += ("-S",) |
| 820 |
|
| 821 |
target: str | None = None |
| 822 |
if window_index is not None: |
| 823 |
|
| 824 |
target = f"{self.session_id}:{window_index}" |
| 825 |
if target_window: |
| 826 |
target = target_window |
| 827 |
elif window_index is not None: |
| 828 |
|
| 829 |
window_args += (f"-t{self.session_id}:{window_index}",) |
| 830 |
|
| 831 |
if window_shell: |
| 832 |
window_args += (window_shell,) |
| 833 |
|
| 834 |
cmd = self.cmd("new-window", *window_args, target=target) |
| 835 |
|
| 836 |
raise_if_stderr(cmd, "new-window") |
| 837 |
|
| 838 |
window_output = cmd.stdout[0] |
| 839 |
|
| 840 |
window_formatters = dict( |
| 841 |
zip(["window_id"], window_output.split(FORMAT_SEPARATOR), strict=False), |
| 842 |
) |
| 843 |
|
| 844 |
window = Window.from_window_id( |
| 845 |
server=self.server, |
| 846 |
window_id=window_formatters["window_id"], |
| 847 |
) |
| 848 |
|
| 849 |
extra: dict[str, str] = { |
| 850 |
"tmux_subcommand": "new-window", |
| 851 |
} |
| 852 |
if self.session_name is not None: |
| 853 |
extra["tmux_session"] = str(self.session_name) |
| 854 |
if window.window_name is not None: |
| 855 |
extra["tmux_window"] = str(window.window_name) |
| 856 |
if target is not None: |
| 857 |
extra["tmux_target"] = str(target) |
| 858 |
|
| 859 |
logger.info("window created", extra=extra) |
| 860 |
|
| 861 |
return window |
| 862 |
|
| 863 |
def kill_window(self, target_window: str | int | None = None) -> None: |
| 864 |
"""Close a tmux window, and all panes inside it, ``$ tmux kill-window``. |
| 865 |
|
| 866 |
Kill the current window or the window at ``target-window``. removing it |
| 867 |
from any sessions to which it is linked. |
| 868 |
|
| 869 |
Parameters |
| 870 |
---------- |
| 871 |
target_window : str | int, optional |
| 872 |
Window to kill. |
| 873 |
|
| 874 |
Raises |
| 875 |
------ |
| 876 |
:exc:`libtmux.exc.LibTmuxException` |
| 877 |
If tmux returns an error. |
| 878 |
""" |
| 879 |
target: str | int | None = target_window |
| 880 |
if target_window is not None: |
| 881 |
if isinstance(target_window, int): |
| 882 |
target = f"{self.session_name}:{target_window}" |
| 883 |
else: |
| 884 |
target = f"{target_window}" |
| 885 |
|
| 886 |
proc = self.cmd("kill-window", target=target) |
| 887 |
|
| 888 |
raise_if_stderr(proc, "kill-window") |
| 889 |
|
| 890 |
extra: dict[str, str] = { |
| 891 |
"tmux_subcommand": "kill-window", |
| 892 |
} |
| 893 |
if self.session_name is not None: |
| 894 |
extra["tmux_session"] = str(self.session_name) |
| 895 |
if target is not None: |
| 896 |
extra["tmux_target"] = str(target) |
| 897 |
logger.info("window killed", extra=extra) |
| 898 |
|
| 899 |
|
| 900 |
|
| 901 |
|
| 902 |
def __eq__(self, other: object) -> bool: |
| 903 |
"""Equal operator for :class:`Session` object.""" |
| 904 |
if isinstance(other, Session): |
| 905 |
return self.session_id == other.session_id |
| 906 |
return False |
| 907 |
|
| 908 |
def __repr__(self) -> str: |
| 909 |
"""Representation of :class:`Session` object.""" |
| 910 |
return f"{self.__class__.__name__}({self.session_id} {self.session_name})" |
| 911 |
|
| 912 |
|
| 913 |
|
| 914 |
|
| 915 |
@property |
| 916 |
def id(self) -> str | None: |
| 917 |
"""Alias of :attr:`Session.session_id`. |
| 918 |
|
| 919 |
>>> session.id |
| 920 |
'$1' |
| 921 |
|
| 922 |
>>> session.id == session.session_id |
| 923 |
True |
| 924 |
""" |
| 925 |
return self.session_id |
| 926 |
|
| 927 |
@property |
| 928 |
def name(self) -> str | None: |
| 929 |
"""Alias of :attr:`Session.session_name`. |
| 930 |
|
| 931 |
>>> session.name |
| 932 |
'libtmux_...' |
| 933 |
|
| 934 |
>>> session.name == session.session_name |
| 935 |
True |
| 936 |
""" |
| 937 |
return self.session_name |
| 938 |
|
| 939 |
|
| 940 |
|
| 941 |
|
| 942 |
@property |
| 943 |
def attached_pane(self) -> Pane | None: |
| 944 |
"""Return the active :class:`Pane` object. |
| 945 |
|
| 946 |
Notes |
| 947 |
----- |
| 948 |
.. deprecated:: 0.31 |
| 949 |
|
| 950 |
Deprecated in favor of :meth:`.active_pane`. |
| 951 |
""" |
| 952 |
raise exc.DeprecatedError( |
| 953 |
deprecated="Session.attached_pane", |
| 954 |
replacement="Session.active_pane", |
| 955 |
version="0.31.0", |
| 956 |
) |
| 957 |
|
| 958 |
@property |
| 959 |
def attached_window(self) -> Window: |
| 960 |
"""Return the active :class:`Window` object. |
| 961 |
|
| 962 |
Notes |
| 963 |
----- |
| 964 |
.. deprecated:: 0.31 |
| 965 |
|
| 966 |
Deprecated in favor of :meth:`.active_window`. |
| 967 |
""" |
| 968 |
raise exc.DeprecatedError( |
| 969 |
deprecated="Session.attached_window", |
| 970 |
replacement="Session.active_window", |
| 971 |
version="0.31.0", |
| 972 |
) |
| 973 |
|
| 974 |
def attach_session(self) -> Session: |
| 975 |
"""Return ``$ tmux attach-session`` aka alias: ``$ tmux attach``. |
| 976 |
|
| 977 |
Notes |
| 978 |
----- |
| 979 |
.. deprecated:: 0.30 |
| 980 |
|
| 981 |
Deprecated in favor of :meth:`.attach()`. |
| 982 |
""" |
| 983 |
raise exc.DeprecatedError( |
| 984 |
deprecated="Session.attach_session()", |
| 985 |
replacement="Session.attach()", |
| 986 |
version="0.30.0", |
| 987 |
) |
| 988 |
|
| 989 |
def kill_session(self) -> None: |
| 990 |
"""Destroy session. |
| 991 |
|
| 992 |
Notes |
| 993 |
----- |
| 994 |
.. deprecated:: 0.30 |
| 995 |
|
| 996 |
Deprecated in favor of :meth:`.kill()`. |
| 997 |
""" |
| 998 |
raise exc.DeprecatedError( |
| 999 |
deprecated="Session.kill_session()", |
| 1000 |
replacement="Session.kill()", |
| 1001 |
version="0.30.0", |
| 1002 |
) |
| 1003 |
|
| 1004 |
def get(self, key: str, default: t.Any | None = None) -> t.Any: |
| 1005 |
"""Return key-based lookup. Deprecated by attributes. |
| 1006 |
|
| 1007 |
.. deprecated:: 0.17 |
| 1008 |
|
| 1009 |
Deprecated by attribute lookup.e.g. ``session['session_name']`` is now |
| 1010 |
accessed via ``session.session_name``. |
| 1011 |
|
| 1012 |
""" |
| 1013 |
raise exc.DeprecatedError( |
| 1014 |
deprecated="Session.get()", |
| 1015 |
replacement="direct attribute access (e.g., session.session_name)", |
| 1016 |
version="0.17.0", |
| 1017 |
) |
| 1018 |
|
| 1019 |
def __getitem__(self, key: str) -> t.Any: |
| 1020 |
"""Return item lookup by key. Deprecated in favor of attributes. |
| 1021 |
|
| 1022 |
.. deprecated:: 0.17 |
| 1023 |
|
| 1024 |
Deprecated in favor of attributes. e.g. ``session['session_name']`` is now |
| 1025 |
accessed via ``session.session_name``. |
| 1026 |
|
| 1027 |
""" |
| 1028 |
raise exc.DeprecatedError( |
| 1029 |
deprecated="Session[key] lookup", |
| 1030 |
replacement="direct attribute access (e.g., session.session_name)", |
| 1031 |
version="0.17.0", |
| 1032 |
) |
| 1033 |
|
| 1034 |
def get_by_id(self, session_id: str) -> Window | None: |
| 1035 |
"""Return window by id. Deprecated in favor of :meth:`.windows.get()`. |
| 1036 |
|
| 1037 |
.. deprecated:: 0.16 |
| 1038 |
|
| 1039 |
Deprecated by :meth:`.windows.get()`. |
| 1040 |
|
| 1041 |
""" |
| 1042 |
raise exc.DeprecatedError( |
| 1043 |
deprecated="Session.get_by_id()", |
| 1044 |
replacement="Session.windows.get(window_id=..., default=None)", |
| 1045 |
version="0.16.0", |
| 1046 |
) |
| 1047 |
|
| 1048 |
def where(self, kwargs: dict[str, t.Any]) -> list[Window]: |
| 1049 |
"""Filter through windows, return list of :class:`Window`. |
| 1050 |
|
| 1051 |
.. deprecated:: 0.17 |
| 1052 |
|
| 1053 |
Deprecated by :meth:`.windows.filter()`. |
| 1054 |
|
| 1055 |
""" |
| 1056 |
raise exc.DeprecatedError( |
| 1057 |
deprecated="Session.where()", |
| 1058 |
replacement="Session.windows.filter()", |
| 1059 |
version="0.17.0", |
| 1060 |
) |
| 1061 |
|
| 1062 |
def find_where(self, kwargs: dict[str, t.Any]) -> Window | None: |
| 1063 |
"""Filter through windows, return first :class:`Window`. |
| 1064 |
|
| 1065 |
.. deprecated:: 0.17 |
| 1066 |
|
| 1067 |
Slated to be removed in favor of :meth:`.windows.get()`. |
| 1068 |
|
| 1069 |
""" |
| 1070 |
raise exc.DeprecatedError( |
| 1071 |
deprecated="Session.find_where()", |
| 1072 |
replacement="Session.windows.get(default=None, **kwargs)", |
| 1073 |
version="0.17.0", |
| 1074 |
) |
| 1075 |
|
| 1076 |
def _list_windows(self) -> list[WindowDict]: |
| 1077 |
"""Return list of windows (deprecated in favor of :attr:`.windows`). |
| 1078 |
|
| 1079 |
.. deprecated:: 0.17 |
| 1080 |
|
| 1081 |
Slated to be removed in favor of :attr:`.windows`. |
| 1082 |
|
| 1083 |
""" |
| 1084 |
raise exc.DeprecatedError( |
| 1085 |
deprecated="Session._list_windows()", |
| 1086 |
replacement="Session.windows property", |
| 1087 |
version="0.17.0", |
| 1088 |
) |
| 1089 |
|
| 1090 |
@property |
| 1091 |
def _windows(self) -> list[WindowDict]: |
| 1092 |
"""Property / alias to return :meth:`Session._list_windows`. |
| 1093 |
|
| 1094 |
.. deprecated:: 0.17 |
| 1095 |
|
| 1096 |
Slated to be removed in favor of :attr:`.windows`. |
| 1097 |
|
| 1098 |
""" |
| 1099 |
raise exc.DeprecatedError( |
| 1100 |
deprecated="Session._windows", |
| 1101 |
replacement="Session.windows property", |
| 1102 |
version="0.17.0", |
| 1103 |
) |
| 1104 |
|
| 1105 |
def list_windows(self) -> list[Window]: |
| 1106 |
"""Return a list of :class:`Window` from the ``tmux(1)`` session. |
| 1107 |
|
| 1108 |
.. deprecated:: 0.17 |
| 1109 |
|
| 1110 |
Slated to be removed in favor of :attr:`.windows`. |
| 1111 |
|
| 1112 |
""" |
| 1113 |
raise exc.DeprecatedError( |
| 1114 |
deprecated="Session.list_windows()", |
| 1115 |
replacement="Session.windows property", |
| 1116 |
version="0.17.0", |
| 1117 |
) |
| 1118 |
|
| 1119 |
@property |
| 1120 |
def children(self) -> QueryList[Window]: |
| 1121 |
"""Was used by TmuxRelationalObject (but that's longer used in this class). |
| 1122 |
|
| 1123 |
.. deprecated:: 0.17 |
| 1124 |
|
| 1125 |
Slated to be removed in favor of :attr:`.windows`. |
| 1126 |
|
| 1127 |
""" |
| 1128 |
raise exc.DeprecatedError( |
| 1129 |
deprecated="Session.children", |
| 1130 |
replacement="Session.windows property", |
| 1131 |
version="0.17.0", |
| 1132 |
) |