Debian Codegraph @

src/libtmux/hooks.py

raw symbols SCIP
1 """Helpers for tmux hooks.
2
3 tmux Hook Features
4 ------------------
5 Hooks are array options (e.g., ``session-renamed[0]``, ``session-renamed[1]``)
6 with sparse index support (can have gaps: ``[0]``, ``[5]``, ``[10]``).
7
8 All features available in libtmux's minimum supported version (tmux 3.2+):
9
10 - Session, window, and pane-level hooks
11 - Window hooks via ``-w`` flag, pane hooks via ``-p`` flag
12 - Hook scope separation (session vs window vs pane)
13
14 **tmux 3.3+**:
15 - ``client-active`` hook
16 - ``window-resized`` hook
17
18 **tmux 3.5+**:
19 - ``pane-title-changed`` hook
20 - ``client-light-theme`` / ``client-dark-theme`` hooks
21 - ``command-error`` hook
22
23 Bulk Operations API
24 -------------------
25 This module provides bulk operations for managing multiple indexed hooks:
26
27 - :meth:`~HooksMixin.set_hooks` - Set multiple hooks at once
28 """
29
30 from __future__ import annotations
31
32 import logging
33 import re
34 import typing as t
35 import warnings
36
37 from libtmux._internal.constants import (
38 Hooks,
39 )
40 from libtmux._internal.sparse_array import SparseArray
41 from libtmux.common import CmdMixin, has_lt_version
42 from libtmux.constants import (
43 DEFAULT_OPTION_SCOPE,
44 HOOK_SCOPE_FLAG_MAP,
45 OptionScope,
46 _DefaultOptionScope,
47 )
48 from libtmux.options import handle_option_error
49
50 if t.TYPE_CHECKING:
51 from typing_extensions import Self
52
53 HookDict = dict[str, t.Any]
54 HookValues = dict[int, str] | SparseArray[str] | list[str]
55
56 logger = logging.getLogger(__name__)
57
58
59 class HooksMixin(CmdMixin):
60 """Mixin for manager scoped hooks in tmux.
61
62 Requires tmux 3.1+. For older versions, use raw commands.
63 """
64
65 default_hook_scope: OptionScope | None
66 hooks: Hooks
67
68 def __init__(self, default_hook_scope: OptionScope | None) -> None:
69 """When not a user (custom) hook, scope can be implied."""
70 self.default_hook_scope = default_hook_scope
71 self.hooks = Hooks()
72
73 @property
74 def _tmux_bin(self) -> str | None:
75 """Resolve tmux_bin from self (Server) or self.server (Session/Window/Pane)."""
76 return getattr(self, "tmux_bin", None) or getattr(
77 getattr(self, "server", None), "tmux_bin", None
78 )
79
80 def run_hook(
81 self,
82 hook: str,
83 global_: bool | None = None,
84 scope: OptionScope | _DefaultOptionScope | None = DEFAULT_OPTION_SCOPE,
85 ) -> Self:
86 """Run a hook immediately. Useful for testing."""
87 if scope is DEFAULT_OPTION_SCOPE:
88 scope = self.default_hook_scope
89
90 flags: list[str] = ["-R"]
91
92 if global_ is not None and global_:
93 flags.append("-g")
94
95 if scope is not None and not isinstance(scope, _DefaultOptionScope):
96 assert scope in HOOK_SCOPE_FLAG_MAP
97
98 flag = HOOK_SCOPE_FLAG_MAP[scope]
99 if flag in {"-p", "-w"} and has_lt_version("3.2", tmux_bin=self._tmux_bin):
100 warnings.warn(
101 "Scope flag '-w' and '-p' requires tmux 3.2+. Ignoring.",
102 stacklevel=2,
103 )
104 else:
105 flags += (flag,)
106
107 cmd = self.cmd(
108 "set-hook",
109 *flags,
110 hook,
111 )
112
113 if isinstance(cmd.stderr, list) and len(cmd.stderr):
114 handle_option_error(cmd.stderr[0])
115
116 return self
117
118 def set_hook(
119 self,
120 hook: str,
121 value: int | str,
122 unset: bool | None = None,
123 run: bool | None = None,
124 append: bool | None = None,
125 g: bool | None = None,
126 global_: bool | None = None,
127 scope: OptionScope | _DefaultOptionScope | None = DEFAULT_OPTION_SCOPE,
128 ) -> Self:
129 """Set hook for tmux target.
130
131 Wraps ``$ tmux set-hook <hook> <value>``.
132
133 Parameters
134 ----------
135 hook : str
136 hook to set, e.g. 'aggressive-resize'
137 value : int | str
138 hook command.
139
140 Raises
141 ------
142 :exc:`exc.OptionError`, :exc:`exc.UnknownOption`,
143 :exc:`exc.InvalidOption`, :exc:`exc.AmbiguousOption`
144 """
145 if scope is DEFAULT_OPTION_SCOPE:
146 scope = self.default_hook_scope
147
148 if g:
149 warnings.warn(
150 "g argument is deprecated in favor of global_",
151 category=DeprecationWarning,
152 stacklevel=2,
153 )
154 global_ = g
155
156 flags: list[str] = []
157
158 if unset is not None and unset:
159 assert isinstance(unset, bool)
160 flags.append("-u")
161
162 if run is not None and run:
163 assert isinstance(run, bool)
164 flags.append("-R")
165
166 if append is not None and append:
167 assert isinstance(append, bool)
168 flags.append("-a")
169
170 if global_ is not None and global_:
171 assert isinstance(global_, bool)
172 flags.append("-g")
173
174 if scope is not None and not isinstance(scope, _DefaultOptionScope):
175 assert scope in HOOK_SCOPE_FLAG_MAP
176
177 flag = HOOK_SCOPE_FLAG_MAP[scope]
178 if flag in {"-p", "-w"} and has_lt_version("3.2", tmux_bin=self._tmux_bin):
179 warnings.warn(
180 "Scope flag '-w' and '-p' requires tmux 3.2+. Ignoring.",
181 stacklevel=2,
182 )
183 else:
184 flags += (flag,)
185
186 cmd = self.cmd(
187 "set-hook",
188 *flags,
189 hook,
190 value,
191 )
192
193 if isinstance(cmd.stderr, list) and len(cmd.stderr):
194 handle_option_error(cmd.stderr[0])
195
196 return self
197
198 def unset_hook(
199 self,
200 hook: str,
201 global_: bool | None = None,
202 scope: OptionScope | _DefaultOptionScope | None = DEFAULT_OPTION_SCOPE,
203 ) -> Self:
204 """Unset hook for tmux target.
205
206 Wraps ``$ tmux set-hook -u <hook>`` / ``$ tmux set-hook -U <hook>``
207
208 Parameters
209 ----------
210 hook : str
211 hook to unset, e.g. 'after-show-environment'
212
213 Raises
214 ------
215 :exc:`exc.OptionError`, :exc:`exc.UnknownOption`,
216 :exc:`exc.InvalidOption`, :exc:`exc.AmbiguousOption`
217 """
218 if scope is DEFAULT_OPTION_SCOPE:
219 scope = self.default_hook_scope
220
221 flags: list[str] = ["-u"]
222
223 if global_ is not None and global_:
224 assert isinstance(global_, bool)
225 flags.append("-g")
226
227 if scope is not None and not isinstance(scope, _DefaultOptionScope):
228 assert scope in HOOK_SCOPE_FLAG_MAP
229
230 flag = HOOK_SCOPE_FLAG_MAP[scope]
231 if flag in {"-p", "-w"} and has_lt_version("3.2", tmux_bin=self._tmux_bin):
232 warnings.warn(
233 "Scope flag '-w' and '-p' requires tmux 3.2+. Ignoring.",
234 stacklevel=2,
235 )
236 else:
237 flags += (flag,)
238
239 cmd = self.cmd(
240 "set-hook",
241 *flags,
242 hook,
243 )
244
245 if isinstance(cmd.stderr, list) and len(cmd.stderr):
246 handle_option_error(cmd.stderr[0])
247
248 return self
249
250 def show_hooks(
251 self,
252 global_: bool | None = False,
253 scope: OptionScope | _DefaultOptionScope | None = DEFAULT_OPTION_SCOPE,
254 ) -> HookDict:
255 """Return a dict of hooks for the target.
256
257 Parameters
258 ----------
259 global_ : bool, optional
260 Pass ``-g`` flag for global hooks, default False.
261 scope : OptionScope | _DefaultOptionScope | None, optional
262 Hook scope (Server/Session/Window/Pane), defaults to object's scope.
263
264 Returns
265 -------
266 HookDict
267 Dictionary mapping hook names to their values.
268
269 Examples
270 --------
271 >>> session.set_hook('session-renamed[0]', 'display-message "test"')
272 Session($...)
273
274 >>> hooks = session.show_hooks()
275 >>> isinstance(hooks, dict)
276 True
277
278 >>> 'session-renamed[0]' in hooks
279 True
280
281 >>> session.unset_hook('session-renamed')
282 Session($...)
283 """
284 if scope is DEFAULT_OPTION_SCOPE:
285 scope = self.default_hook_scope
286
287 flags: tuple[str, ...] = ()
288
289 if global_:
290 flags += ("-g",)
291
292 if scope is not None and not isinstance(scope, _DefaultOptionScope):
293 assert scope in HOOK_SCOPE_FLAG_MAP
294
295 flag = HOOK_SCOPE_FLAG_MAP[scope]
296 if flag in {"-p", "-w"} and has_lt_version("3.2", tmux_bin=self._tmux_bin):
297 warnings.warn(
298 "Scope flag '-w' and '-p' requires tmux 3.2+. Ignoring.",
299 stacklevel=2,
300 )
301 else:
302 flags += (flag,)
303
304 cmd = self.cmd("show-hooks", *flags)
305 output = cmd.stdout
306 hooks: HookDict = {}
307 for item in output:
308 # Split on first whitespace only to handle multi-word hook values
309 parts = item.split(None, 1)
310 if len(parts) == 2:
311 key, val = parts
312 elif len(parts) == 1:
313 key, val = parts[0], None
314 else:
315 logger.warning("failed to extract hook: %s", item)
316 continue
317
318 if isinstance(val, str) and val.isdigit():
319 hooks[key] = int(val)
320 elif isinstance(val, str):
321 hooks[key] = val
322
323 return hooks
324
325 def _show_hook(
326 self,
327 hook: str,
328 global_: bool = False,
329 scope: OptionScope | _DefaultOptionScope | None = DEFAULT_OPTION_SCOPE,
330 ) -> list[str] | None:
331 """Return value for the hook.
332
333 Parameters
334 ----------
335 hook : str
336
337 Raises
338 ------
339 :exc:`exc.OptionError`, :exc:`exc.UnknownOption`,
340 :exc:`exc.InvalidOption`, :exc:`exc.AmbiguousOption`
341 """
342 if scope is DEFAULT_OPTION_SCOPE:
343 scope = self.default_hook_scope
344
345 flags: tuple[str | int, ...] = ()
346
347 if global_:
348 flags += ("-g",)
349
350 if scope is not None and not isinstance(scope, _DefaultOptionScope):
351 assert scope in HOOK_SCOPE_FLAG_MAP
352
353 flag = HOOK_SCOPE_FLAG_MAP[scope]
354 if flag in {"-p", "-w"} and has_lt_version("3.2", tmux_bin=self._tmux_bin):
355 warnings.warn(
356 "Scope flag '-w' and '-p' requires tmux 3.2+. Ignoring.",
357 stacklevel=2,
358 )
359 else:
360 flags += (flag,)
361
362 flags += (hook,)
363
364 cmd = self.cmd("show-hooks", *flags)
365
366 if len(cmd.stderr):
367 handle_option_error(cmd.stderr[0])
368
369 return cmd.stdout
370
371 def show_hook(
372 self,
373 hook: str,
374 global_: bool = False,
375 scope: OptionScope | _DefaultOptionScope | None = DEFAULT_OPTION_SCOPE,
376 ) -> str | int | SparseArray[str] | None:
377 """Return value for a hook.
378
379 For array hooks (e.g., ``session-renamed``), returns a
380 :class:`~libtmux._internal.sparse_array.SparseArray` with hook values
381 at their original indices. Use ``.keys()`` for indices and ``.values()``
382 for values.
383
384 Parameters
385 ----------
386 hook : str
387 Hook name to query
388
389 Returns
390 -------
391 str | int | SparseArray[str] | None
392 Hook value. For array hooks, returns SparseArray.
393
394 Raises
395 ------
396 :exc:`exc.OptionError`, :exc:`exc.UnknownOption`,
397 :exc:`exc.InvalidOption`, :exc:`exc.AmbiguousOption`
398
399 Examples
400 --------
401 >>> session.set_hook('session-renamed[0]', 'display-message "test"')
402 Session($...)
403
404 >>> hooks = session.show_hook('session-renamed')
405 >>> isinstance(hooks, SparseArray)
406 True
407
408 >>> sorted(hooks.keys())
409 [0]
410
411 >>> session.unset_hook('session-renamed')
412 Session($...)
413 """
414 hooks_output = self._show_hook(
415 hook=hook,
416 global_=global_,
417 scope=scope,
418 )
419 if hooks_output is None:
420 return None
421 hooks = Hooks.from_stdout(hooks_output)
422
423 # Check if this is an indexed query (e.g., "session-renamed[0]")
424 # For indexed queries, return the specific value like _show_option does
425 hook_attr = hook.lstrip("%").replace("-", "_")
426 index_match = re.search(r"\[(\d+)\]$", hook_attr)
427 if index_match:
428 # Strip the index for attribute lookup
429 base_hook_attr = re.sub(r"\[\d+\]$", "", hook_attr)
430 hook_val = getattr(hooks, base_hook_attr, None)
431 if isinstance(hook_val, SparseArray):
432 return hook_val.get(int(index_match.group(1)))
433 return hook_val
434
435 return getattr(hooks, hook_attr, None)
436
437 def set_hooks(
438 self,
439 hook: str,
440 values: HookValues,
441 *,
442 clear_existing: bool = False,
443 global_: bool | None = None,
444 scope: OptionScope | _DefaultOptionScope | None = DEFAULT_OPTION_SCOPE,
445 ) -> Self:
446 """Set multiple indexed hooks at once.
447
448 Parameters
449 ----------
450 hook : str
451 Hook name, e.g. 'session-renamed'
452 values : HookValues
453 Values to set. Can be:
454 - dict[int, str]: {0: 'cmd1', 1: 'cmd2'} - explicit indices
455 - SparseArray[str]: preserves indices from another hook
456 - list[str]: ['cmd1', 'cmd2'] - sequential indices starting at 0
457 clear_existing : bool
458 If True, unset all existing hook values first
459 global_ : bool | None
460 Use global hooks
461 scope : OptionScope | None
462 Scope for the hook
463
464 Returns
465 -------
466 Self
467 Returns self for method chaining.
468
469 Examples
470 --------
471 Set hooks with explicit indices:
472
473 >>> session.set_hooks('session-renamed', {
474 ... 0: 'display-message "hook 0"',
475 ... 1: 'display-message "hook 1"',
476 ... })
477 Session($...)
478
479 >>> hooks = session.show_hook('session-renamed')
480 >>> sorted(hooks.keys())
481 [0, 1]
482
483 >>> session.unset_hook('session-renamed')
484 Session($...)
485
486 Set hooks from a list (sequential indices):
487
488 >>> session.set_hooks('after-new-window', [
489 ... 'select-pane -t 0',
490 ... 'send-keys "clear" Enter',
491 ... ])
492 Session($...)
493
494 >>> hooks = session.show_hook('after-new-window')
495 >>> sorted(hooks.keys())
496 [0, 1]
497
498 Replace all existing hooks with ``clear_existing=True``:
499
500 >>> session.set_hooks(
501 ... 'session-renamed',
502 ... {0: 'display-message "new"'},
503 ... clear_existing=True,
504 ... )
505 Session($...)
506
507 >>> hooks = session.show_hook('session-renamed')
508 >>> sorted(hooks.keys())
509 [0]
510
511 >>> session.unset_hook('session-renamed')
512 Session($...)
513
514 >>> session.unset_hook('after-new-window')
515 Session($...)
516 """
517 if clear_existing:
518 self.unset_hook(hook, global_=global_, scope=scope)
519
520 # Convert list to dict with sequential indices
521 if isinstance(values, list):
522 values = dict(enumerate(values))
523
524 for index, value in values.items():
525 self.set_hook(
526 f"{hook}[{index}]",
527 value,
528 global_=global_,
529 scope=scope,
530 )
531
532 return self