Debian Codegraph @

src/libtmux/options.py

raw symbols SCIP
1 # ruff: noqa: E501
2 """Helpers for tmux options.
3
4 Option parsing function trade testability and clarity for performance.
5
6 Tmux options
7 ------------
8
9 Options in tmux consist of empty values, strings, integers, arrays, and complex shapes.
10
11 Marshalling types from text:
12
13 Integers: ``buffer-limit 50`` to ``{'buffer-limit': 50}``
14 Booleans: ``exit-unattached on`` to ``{'exit-unattached': True}``
15
16 Exploding arrays:
17
18 ``command-alias[1] split-pane=split-window`` to
19 ``{'command-alias[1]': {'split-pane=split-window'}}``
20
21 However, there is no equivalent to the above type of object in Python (a sparse array),
22 so a SparseArray is used.
23
24 Exploding complex shapes:
25
26 ``"choose-session=choose-tree -s"`` to ``{'choose-session': 'choose-tree -s'}``
27
28 Finally, we need to convert hyphenated keys to underscored attribute names and assign
29 values, as python does not allow hyphens in attribute names.
30
31 ``command-alias`` is ``command_alias`` in python.
32
33 Options object
34 --------------
35 Dataclasses are used to provide typed access to tmux' option shape.
36
37 Extra data gleaned from the options, such as user options (custom data) and an option
38 being inherited,
39
40 User options
41 ------------
42 There are also custom user options, preceded with @, which exist are stored to
43 `Options.context.user_options` as a dictionary.
44
45 > tmux set-option -w my-custom-variable my-value
46 invalid option: my-custom-option
47
48 > tmux set-option -w @my-custom-option my-value
49 > tmux show-option -w
50 @my-custom-optione my-value
51
52 Inherited options
53 -----------------
54
55 ``tmux show-options`` -A can include inherited options. The raw output of an inherited
56 option is detected by the key having a ``*``::
57
58 visual-activity* on
59 visual-bell* off
60
61 A list of options that are inherited is kept at ``Options.context._inherited_options`` and
62 ``Options.context.inherited_options``.
63
64 They are mixed with the normal options,
65 to differentiate them, run ``show_options()`` without ``include_inherited=True``.
66 """
67
68 from __future__ import annotations
69
70 import io
71 import logging
72 import re
73 import shlex
74 import typing as t
75 import warnings
76
77 from libtmux._internal.sparse_array import SparseArray
78 from libtmux.common import CmdMixin
79 from libtmux.constants import (
80 DEFAULT_OPTION_SCOPE,
81 OPTION_SCOPE_FLAG_MAP,
82 OptionScope,
83 _DefaultOptionScope,
84 )
85
86 from . import exc
87
88 if t.TYPE_CHECKING:
89 from typing import TypeAlias
90
91 from typing_extensions import Self
92
93 from libtmux._internal.constants import TerminalFeatures
94 from libtmux.common import tmux_cmd
95
96
97 TerminalOverride = dict[str, str | None]
98 TerminalOverrides = dict[str, TerminalOverride]
99 CommandAliases = dict[str, str]
100
101 OptionDict: TypeAlias = dict[str, t.Any]
102 UntypedOptionsDict: TypeAlias = dict[str, str | None]
103 ExplodedUntypedOptionsDict: TypeAlias = dict[
104 str,
105 str | int | list[str] | dict[str, list[str]],
106 ]
107 ExplodedComplexUntypedOptionsDict: TypeAlias = dict[
108 str,
109 str
110 | int
111 | list[str | int]
112 | dict[str, list[str | int]]
113 | SparseArray[str | int]
114 | None,
115 ]
116
117 logger = logging.getLogger(__name__)
118
119
120 def handle_option_error(error: str) -> type[exc.OptionError]:
121 """Raise exception if error in option command found.
122
123 In tmux 3.0, show-option and show-window-option return invalid option instead of
124 unknown option. See https://github.com/tmux/tmux/blob/3.0/cmd-show-options.c.
125
126 In tmux >2.4, there are 3 different types of option errors:
127
128 - unknown option
129 - invalid option
130 - ambiguous option
131
132 In tmux <2.4, unknown option was the only option.
133
134 All errors raised will have the base error of :exc:`exc.OptionError`. So to
135 catch any option error, use ``except exc.OptionError``.
136
137 Parameters
138 ----------
139 error : str
140 Error response from subprocess call.
141
142 Raises
143 ------
144 :exc:`exc.OptionError`, :exc:`exc.UnknownOption`, :exc:`exc.InvalidOption`,
145 :exc:`exc.AmbiguousOption`
146
147 Examples
148 --------
149 >>> result = server.cmd(
150 ... 'set-option',
151 ... 'unknown-option-name',
152 ... )
153
154 >>> bool(isinstance(result.stderr, list) and len(result.stderr))
155 True
156
157 >>> import pytest
158 >>> from libtmux import exc
159
160 >>> with pytest.raises(exc.OptionError):
161 ... handle_option_error(result.stderr[0])
162 """
163 if "unknown option" in error:
164 raise exc.UnknownOption(error)
165 if "invalid option" in error:
166 raise exc.InvalidOption(error)
167 if "ambiguous option" in error:
168 raise exc.AmbiguousOption(error)
169 raise exc.OptionError(error) # Raise generic option error
170
171
172 _V = t.TypeVar("_V")
173 ConvertedValue: TypeAlias = str | int | bool | None
174 ConvertedValues: TypeAlias = (
175 ConvertedValue
176 | list[ConvertedValue]
177 | dict[str, ConvertedValue]
178 | SparseArray[ConvertedValue]
179 )
180
181
182 def convert_value(
183 value: _V | None,
184 ) -> ConvertedValue | _V | None:
185 """Convert raw option strings to python types.
186
187 Examples
188 --------
189 >>> convert_value("on")
190 True
191 >>> convert_value("off")
192 False
193
194 >>> convert_value("1")
195 1
196 >>> convert_value("50")
197 50
198
199 >>> convert_value("%50")
200 '%50'
201 """
202 if not isinstance(value, str):
203 return value
204
205 if value.isdigit():
206 return int(value)
207
208 if value == "on":
209 return True
210
211 if value == "off":
212 return False
213
214 return value
215
216
217 def convert_values(
218 value: _V | None,
219 ) -> ConvertedValues | _V | None:
220 """Recursively convert values to python types via :func:`convert_value`.
221
222 >>> convert_values(None)
223
224 >>> convert_values("on")
225 True
226 >>> convert_values("off")
227 False
228
229 >>> convert_values(["on"])
230 [True]
231 >>> convert_values(["off"])
232 [False]
233
234 >>> convert_values({"window_index": "1"})
235 {'window_index': 1}
236
237 >>> convert_values({"visual-bell": "on"})
238 {'visual-bell': True}
239 """
240 if value is None:
241 return None
242 if isinstance(value, dict):
243 # Note: SparseArray inherits from dict, so this branch handles both
244 for k, v in value.items():
245 value[k] = convert_value(v)
246 return value
247 if isinstance(value, list):
248 for idx, v in enumerate(value):
249 value[idx] = convert_value(v)
250 return value
251 return convert_value(value)
252
253
254 def parse_options_to_dict(
255 stdout: t.IO[str],
256 ) -> UntypedOptionsDict:
257 r"""Process subprocess.stdout options or hook output to flat, naive, untyped dict.
258
259 Does not explode arrays or deep values.
260
261 Examples
262 --------
263 >>> import io
264
265 >>> raw_options = io.StringIO("status-keys vi")
266 >>> parse_options_to_dict(raw_options) == {"status-keys": "vi"}
267 True
268
269 >>> int_options = io.StringIO("message-limit 50")
270 >>> parse_options_to_dict(int_options) == {"message-limit": "50"}
271 True
272
273 >>> empty_option = io.StringIO("user-keys")
274 >>> parse_options_to_dict(empty_option) == {"user-keys": None}
275 True
276
277 >>> array_option = io.StringIO("command-alias[0] split-pane=split-window")
278 >>> parse_options_to_dict(array_option) == {
279 ... "command-alias[0]": "split-pane=split-window"}
280 True
281
282 >>> array_option = io.StringIO("command-alias[40] split-pane=split-window")
283 >>> parse_options_to_dict(array_option) == {
284 ... "command-alias[40]": "split-pane=split-window"}
285 True
286
287 >>> many_options = io.StringIO(r'''status-keys
288 ... command-alias[0] split-pane=split-window
289 ... ''')
290 >>> parse_options_to_dict(many_options) == {
291 ... "command-alias[0]": "split-pane=split-window",
292 ... "status-keys": None,}
293 True
294
295 >>> many_more_options = io.StringIO(r'''
296 ... terminal-features[0] xterm*:clipboard:ccolour:cstyle:focus
297 ... terminal-features[1] screen*:title
298 ... ''')
299 >>> parse_options_to_dict(many_more_options) == {
300 ... "terminal-features[0]": "xterm*:clipboard:ccolour:cstyle:focus",
301 ... "terminal-features[1]": "screen*:title",}
302 True
303
304 >>> quoted_option = io.StringIO(r'''
305 ... command-alias[0] "choose-session=choose-tree -s"
306 ... ''')
307 >>> parse_options_to_dict(quoted_option) == {
308 ... "command-alias[0]": "choose-session=choose-tree -s",
309 ... }
310 True
311 """
312 output: UntypedOptionsDict = {}
313
314 val: ConvertedValue | None = None
315
316 for item in stdout.readlines():
317 if " " in item:
318 try:
319 key, val = shlex.split(item)
320 except ValueError:
321 key, val = item.split(" ", maxsplit=1)
322 else:
323 key, val = item, None
324 key = key.strip()
325
326 if key:
327 if isinstance(val, str) and val.endswith("\n"):
328 val = val.rstrip("\n")
329
330 output[key] = val
331 return output
332
333
334 def explode_arrays(
335 _dict: UntypedOptionsDict,
336 force_array: bool = False,
337 ) -> ExplodedUntypedOptionsDict:
338 """Explode flat, naive options dict's option arrays.
339
340 Examples
341 --------
342 >>> import io
343
344 >>> many_more_options = io.StringIO(r'''
345 ... terminal-features[0] xterm*:clipboard:ccolour:cstyle:focus
346 ... terminal-features[1] screen*:title
347 ... ''')
348 >>> many_more_flat_dict = parse_options_to_dict(many_more_options)
349 >>> many_more_flat_dict == {
350 ... "terminal-features[0]": "xterm*:clipboard:ccolour:cstyle:focus",
351 ... "terminal-features[1]": "screen*:title",}
352 True
353 >>> explode_arrays(many_more_flat_dict) == {
354 ... "terminal-features": {0: "xterm*:clipboard:ccolour:cstyle:focus",
355 ... 1: "screen*:title"}}
356 True
357
358 tmux arrays allow non-sequential indexes, so we need to support that:
359
360 >>> explode_arrays(parse_options_to_dict(io.StringIO(r'''
361 ... terminal-features[0] xterm*:clipboard:ccolour:cstyle:focus
362 ... terminal-features[5] screen*:title
363 ... '''))) == {
364 ... "terminal-features": {0: "xterm*:clipboard:ccolour:cstyle:focus",
365 ... 5: "screen*:title"}}
366 True
367
368 Use ``force_array=True`` for hooks, which always use array format:
369
370 >>> from libtmux._internal.sparse_array import SparseArray
371
372 >>> hooks_output = io.StringIO(r'''
373 ... session-renamed[0] display-message 'renamed'
374 ... session-renamed[5] refresh-client
375 ... pane-focus-in[0] run-shell 'echo focus'
376 ... ''')
377 >>> hooks_exploded = explode_arrays(
378 ... parse_options_to_dict(hooks_output),
379 ... force_array=True,
380 ... )
381
382 Each hook becomes a SparseArray preserving indices:
383
384 >>> isinstance(hooks_exploded["session-renamed"], SparseArray)
385 True
386 >>> hooks_exploded["session-renamed"][0]
387 "display-message 'renamed'"
388 >>> hooks_exploded["session-renamed"][5]
389 'refresh-client'
390 >>> sorted(hooks_exploded["session-renamed"].keys())
391 [0, 5]
392 """
393 options: dict[str, t.Any] = {}
394 for key, val in _dict.items():
395 Default: type[dict[t.Any, t.Any] | SparseArray[str | int | bool | None]] = (
396 dict if isinstance(key, str) and key == "terminal-features" else SparseArray
397 )
398 if "[" not in key:
399 if force_array:
400 options[key] = Default()
401 if val is not None:
402 options[key][0] = val
403 else:
404 options[key] = val
405 continue
406
407 try:
408 matchgroup = re.match(
409 r"(?P<option>[\w-]+)(\[(?P<index>\d+)\])?(?P<inherited>\*)?",
410 key,
411 )
412 if matchgroup is not None:
413 match = matchgroup.groupdict()
414 if match.get("option") and match.get("index"):
415 # Preserve inherited marker (*) if present
416 base_key = match["option"]
417 if match.get("inherited"):
418 base_key += "*"
419 key = base_key
420 index = int(match["index"])
421
422 if options.get(key) is None:
423 options[key] = Default()
424 options[key][index] = val
425 except Exception:
426 if force_array and val:
427 options[key] = Default()
428 if isinstance(options[key], SparseArray):
429 options[key][0] = val
430 else:
431 options[key] = val
432 logger.warning(
433 "tmux options parse failed",
434 extra={"tmux_option_key": key},
435 )
436 return options
437
438
439 def explode_complex(
440 _dict: ExplodedUntypedOptionsDict,
441 ) -> ExplodedComplexUntypedOptionsDict:
442 r"""Explode arrayed option's complex values.
443
444 Examples
445 --------
446 >>> import io
447
448 >>> explode_complex(explode_arrays(parse_options_to_dict(io.StringIO(r'''
449 ... terminal-features[0] xterm*:clipboard:ccolour:cstyle:focus
450 ... terminal-features[5] screen*:title
451 ... '''))))
452 {'terminal-features': {'xterm*': ['clipboard', 'ccolour', 'cstyle', 'focus'], 'screen*': ['title']}}
453
454 >>> explode_complex(explode_arrays(parse_options_to_dict(io.StringIO(r'''
455 ... terminal-features[0] xterm*:clipboard:ccolour:cstyle:focus
456 ... terminal-features[5] screen*:title
457 ... ''')))) == {
458 ... "terminal-features": {"xterm*": ["clipboard", "ccolour", "cstyle", "focus"],
459 ... "screen*": ["title"]}}
460 True
461
462 >>> explode_complex(explode_arrays(parse_options_to_dict(io.StringIO(r'''
463 ... command-alias[0] split-pane=split-window
464 ... command-alias[1] splitp=split-window
465 ... command-alias[2] "server-info=show-messages -JT"
466 ... ''')))) == {
467 ... "command-alias": {"split-pane": "split-window",
468 ... "splitp": "split-window",
469 ... "server-info": "show-messages -JT"}}
470 True
471
472 >>> explode_complex(explode_arrays({"terminal-features": {0: "xterm*:clipboard:ccolour:cstyle:focus",
473 ... 1: "screen*:title"}}))
474 {'terminal-features': {0: 'xterm*:clipboard:ccolour:cstyle:focus', 1: 'screen*:title'}}
475
476 >>> explode_complex(explode_arrays({"terminal-features": {0: "xterm*:clipboard:ccolour:cstyle:focus",
477 ... 8: "screen*:title"}})) == SparseArray({'terminal-features': {0:
478 ... 'xterm*:clipboard:ccolour:cstyle:focus', 8: 'screen*:title'}})
479 True
480
481 >>> explode_complex(explode_arrays(parse_options_to_dict(io.StringIO(r'''
482 ... terminal-overrides[0] xterm-256color:Tc
483 ... terminal-overrides[1] *:U8=0
484 ... ''')))) == {
485 ... "terminal-overrides": {"xterm-256color": {"Tc": None},
486 ... "*": {"U8": 0}}}
487 True
488
489 >>> explode_complex(explode_arrays(parse_options_to_dict(io.StringIO(r'''
490 ... user-keys[100] "\e[test"
491 ... user-keys[6] "\e\n"
492 ... user-keys[0] "\e[5;30012~"
493 ... ''')))) == {
494 ... "user-keys": {0: "\\e[5;30012~",
495 ... 6: "\\e\\n",
496 ... 100: "\\e[test"}}
497 True
498
499 >>> explode_complex(explode_arrays(parse_options_to_dict(io.StringIO(r'''
500 ... status-format[0] "#[align=left range=left #{E:status-left-style}]#[push-default]#{T;=/#{status-left-length}:status-left}#[pop-default]#[norange default]#[list=on align=#{status-justify}]#[list=left-marker]<#[list=right-marker]>#[list=on]#{W:#[range=window|#{window_index} #{E:window-status-style}#{?#{&&:#{window_last_flag},#{!=:#{E:window-status-last-style},default}}, #{E:window-status-last-style},}#{?#{&&:#{window_bell_flag},#{!=:#{E:window-status-bell-style},default}}, #{E:window-status-bell-style},#{?#{&&:#{||:#{window_activity_flag},#{window_silence_flag}},#{!=:#{E:window-status-activity-style},default}}, #{E:window-status-activity-style},}}]#[push-default]#{T:window-status-format}#[pop-default]#[norange default]#{?window_end_flag,,#{window-status-separator}},#[range=window|#{window_index} list=focus #{?#{!=:#{E:window-status-current-style},default},#{E:window-status-current-style},#{E:window-status-style}}#{?#{&&:#{window_last_flag},#{!=:#{E:window-status-last-style},default}}, #{E:window-status-last-style},}#{?#{&&:#{window_bell_flag},#{!=:#{E:window-status-bell-style},default}}, #{E:window-status-bell-style},#{?#{&&:#{||:#{window_activity_flag},#{window_silence_flag}},#{!=:#{E:window-status-activity-style},default}}, #{E:window-status-activity-style},}}]#[push-default]#{T:window-status-current-format}#[pop-default]#[norange list=on default]#{?window_end_flag,,#{window-status-separator}}}#[nolist align=right range=right #{E:status-right-style}]#[push-default]#{T;=/#{status-right-length}:status-right}#[pop-default]#[norange default]"
501 ... status-format[1] "#[align=centre]#{P:#{?pane_active,#[reverse],}#{pane_index}[#{pane_width}x#{pane_height}]#[default] }"
502 ... ''')))) == {
503 ... "status-format": {0: "#[align=left range=left #{E:status-left-style}]#[push-default]#{T;=/#{status-left-length}:status-left}#[pop-default]#[norange default]#[list=on align=#{status-justify}]#[list=left-marker]<#[list=right-marker]>#[list=on]#{W:#[range=window|#{window_index} #{E:window-status-style}#{?#{&&:#{window_last_flag},#{!=:#{E:window-status-last-style},default}}, #{E:window-status-last-style},}#{?#{&&:#{window_bell_flag},#{!=:#{E:window-status-bell-style},default}}, #{E:window-status-bell-style},#{?#{&&:#{||:#{window_activity_flag},#{window_silence_flag}},#{!=:#{E:window-status-activity-style},default}}, #{E:window-status-activity-style},}}]#[push-default]#{T:window-status-format}#[pop-default]#[norange default]#{?window_end_flag,,#{window-status-separator}},#[range=window|#{window_index} list=focus #{?#{!=:#{E:window-status-current-style},default},#{E:window-status-current-style},#{E:window-status-style}}#{?#{&&:#{window_last_flag},#{!=:#{E:window-status-last-style},default}}, #{E:window-status-last-style},}#{?#{&&:#{window_bell_flag},#{!=:#{E:window-status-bell-style},default}}, #{E:window-status-bell-style},#{?#{&&:#{||:#{window_activity_flag},#{window_silence_flag}},#{!=:#{E:window-status-activity-style},default}}, #{E:window-status-activity-style},}}]#[push-default]#{T:window-status-current-format}#[pop-default]#[norange list=on default]#{?window_end_flag,,#{window-status-separator}}}#[nolist align=right range=right #{E:status-right-style}]#[push-default]#{T;=/#{status-right-length}:status-right}#[pop-default]#[norange default]",
504 ... 1: "#[align=centre]#{P:#{?pane_active,#[reverse],}#{pane_index}[#{pane_width}x#{pane_height}]#[default] }",
505 ... }}
506 True
507 """
508 options: dict[str, t.Any] = {}
509 for key, val in _dict.items():
510 try:
511 if isinstance(val, SparseArray) and key == "terminal-features":
512 new_val: TerminalFeatures = {}
513
514 for item in val.iter_values():
515 try:
516 term, features = item.split(":", maxsplit=1)
517 new_val[term] = features.split(":")
518 except Exception: # NOQA: PERF203
519 logger.warning(
520 "tmux options parse failed",
521 extra={"tmux_option_key": key},
522 )
523 options[key] = new_val
524 continue
525 if isinstance(val, SparseArray) and key == "terminal-overrides":
526 new_overrides: TerminalOverrides = {}
527
528 for item in val.iter_values():
529 try:
530 # Split on all colons: first part is terminal pattern,
531 # remaining parts are individual features/capabilities
532 parts = item.split(":")
533 term = parts[0]
534 features = parts[1:]
535
536 if term not in new_overrides:
537 new_overrides[term] = {}
538
539 for feature in features:
540 if feature and "=" in feature:
541 k, v = feature.split("=", 1)
542 new_overrides[term][k] = int(v) if v.isdigit() else v
543 elif feature:
544 new_overrides[term][feature] = None
545 except Exception: # NOQA: PERF203
546 logger.warning(
547 "tmux options parse failed",
548 extra={"tmux_option_key": key},
549 )
550 options[key] = new_overrides
551 continue
552 if isinstance(val, SparseArray) and key == "command-alias":
553 new_aliases: CommandAliases = {}
554
555 for item in val.iter_values():
556 try:
557 alias, command = item.split("=", maxsplit=1)
558 if options.get(key) is None or not isinstance(
559 options.get(key),
560 dict,
561 ):
562 options[key] = {}
563 new_aliases[alias] = command
564 except Exception: # NOQA: PERF203
565 logger.warning(
566 "tmux options parse failed",
567 extra={"tmux_option_key": key},
568 )
569 options[key] = new_aliases
570 continue
571 options[key] = val
572 continue
573
574 except Exception:
575 options[key] = val
576 logger.warning(
577 "tmux options parse failed",
578 extra={"tmux_option_key": key},
579 )
580 return options
581
582
583 class OptionsMixin(CmdMixin):
584 """Mixin for managing tmux options based on scope."""
585
586 default_option_scope: OptionScope | None
587
588 def __init__(self, default_option_scope: OptionScope | None = None) -> None:
589 """When not a user (custom) option, scope can be implied."""
590 if default_option_scope is not None:
591 self.default_option_scope = default_option_scope
592
593 def set_option(
594 self,
595 option: str,
596 value: int | str,
597 _format: bool | None = None,
598 prevent_overwrite: bool | None = None,
599 ignore_errors: bool | None = None,
600 suppress_warnings: bool | None = None,
601 append: bool | None = None,
602 g: bool | None = None,
603 global_: bool | None = None,
604 scope: OptionScope | _DefaultOptionScope | None = DEFAULT_OPTION_SCOPE,
605 ) -> Self:
606 """Set option for tmux target.
607
608 Wraps ``$ tmux set-option <option> <value>``.
609
610 Parameters
611 ----------
612 option : str
613 option to set, e.g. 'aggressive-resize'
614 value : str
615 option value. True/False will turn in 'on' and 'off',
616 also accepts string of 'on' or 'off' directly.
617
618 .. deprecated:: 0.28
619
620 Deprecated by ``g`` for global, use ``global_`` instead.
621
622 Raises
623 ------
624 :exc:`exc.OptionError`, :exc:`exc.UnknownOption`,
625 :exc:`exc.InvalidOption`, :exc:`exc.AmbiguousOption`
626
627 Examples
628 --------
629 >>> import typing as t
630 >>> from libtmux.common import tmux_cmd
631 >>> from libtmux.constants import OptionScope
632 >>> from libtmux._internal.sparse_array import SparseArray
633
634 >>> class MyServer(OptionsMixin):
635 ... socket_name = server.socket_name
636 ... def cmd(self, cmd: str, *args: object):
637 ... cmd_args: t.List[t.Union[str, int]] = [cmd]
638 ... if self.socket_name:
639 ... cmd_args.insert(0, f"-L{self.socket_name}")
640 ... cmd_args.insert(0, "-f/dev/null")
641 ... return tmux_cmd(*cmd_args, *args)
642 ...
643 ... default_option_scope = OptionScope.Server
644
645 >>> MyServer().set_option('escape-time', 1250)
646 <libtmux.options.MyServer object at ...>
647
648 >>> MyServer()._show_option('escape-time')
649 1250
650
651 >>> MyServer().set_option('escape-time', 495)
652 <libtmux.options.MyServer object at ...>
653
654 >>> MyServer()._show_option('escape-time')
655 495
656 """
657 if scope is DEFAULT_OPTION_SCOPE:
658 scope = self.default_option_scope
659
660 flags: list[str] = []
661 if isinstance(value, bool) and value:
662 value = "on"
663 elif isinstance(value, bool) and not value:
664 value = "off"
665
666 if _format is not None and _format:
667 assert isinstance(_format, bool)
668 flags.append("-F")
669
670 if prevent_overwrite is not None and prevent_overwrite:
671 assert isinstance(prevent_overwrite, bool)
672 flags.append("-o")
673
674 if ignore_errors is not None and ignore_errors:
675 assert isinstance(ignore_errors, bool)
676 flags.append("-q")
677
678 if suppress_warnings is not None and suppress_warnings:
679 assert isinstance(suppress_warnings, bool)
680 flags.append("-q")
681
682 if append is not None and append:
683 assert isinstance(append, bool)
684 flags.append("-a")
685
686 if g is not None:
687 warnings.warn(
688 "g argument is deprecated in favor of global_",
689 category=DeprecationWarning,
690 stacklevel=2,
691 )
692 global_ = g
693
694 if global_ is not None and global_:
695 assert isinstance(global_, bool)
696 flags.append("-g")
697
698 if scope is not None and not isinstance(scope, _DefaultOptionScope):
699 assert scope in OPTION_SCOPE_FLAG_MAP
700 scope_flag = OPTION_SCOPE_FLAG_MAP[scope]
701 if scope_flag: # Session scope has empty string, skip it
702 flags.append(scope_flag)
703
704 cmd = self.cmd(
705 "set-option",
706 *flags,
707 option,
708 value,
709 )
710
711 if isinstance(cmd.stderr, list) and len(cmd.stderr):
712 handle_option_error(cmd.stderr[0])
713
714 return self
715
716 def unset_option(
717 self,
718 option: str,
719 unset_panes: bool | None = None,
720 global_: bool | None = None,
721 ignore_errors: bool | None = None,
722 scope: OptionScope | _DefaultOptionScope | None = DEFAULT_OPTION_SCOPE,
723 ) -> Self:
724 """Unset option for tmux target.
725
726 Wraps ``$ tmux set-option -u <option>`` / ``$ tmux set-option -U <option>``
727
728 Parameters
729 ----------
730 option : str
731 option to unset, e.g. 'aggressive-resize'
732
733 Raises
734 ------
735 :exc:`exc.OptionError`, :exc:`exc.UnknownOption`,
736 :exc:`exc.InvalidOption`, :exc:`exc.AmbiguousOption`
737
738 Examples
739 --------
740 >>> import typing as t
741 >>> from libtmux.common import tmux_cmd
742 >>> from libtmux.constants import OptionScope
743
744 >>> class MyServer(OptionsMixin):
745 ... socket_name = server.socket_name
746 ... def cmd(self, cmd: str, *args: object):
747 ... cmd_args: t.List[t.Union[str, int]] = [cmd]
748 ... if self.socket_name:
749 ... cmd_args.insert(0, f"-L{self.socket_name}")
750 ... cmd_args.insert(0, "-f/dev/null")
751 ... return tmux_cmd(*cmd_args, *args)
752 ...
753 ... default_option_scope = OptionScope.Server
754
755 >>> MyServer().set_option('escape-time', 1250)
756 <libtmux.options.MyServer object at ...>
757
758 >>> MyServer()._show_option('escape-time')
759 1250
760
761 >>> MyServer().unset_option('escape-time')
762 <libtmux.options.MyServer object at ...>
763
764 >>> isinstance(MyServer()._show_option('escape-time'), int)
765 True
766 """
767 if scope is DEFAULT_OPTION_SCOPE:
768 scope = self.default_option_scope
769
770 flags: list[str] = []
771
772 if unset_panes is not None and unset_panes:
773 assert isinstance(unset_panes, bool)
774 flags.append("-U")
775 else:
776 flags.append("-u")
777
778 if ignore_errors is not None and ignore_errors:
779 assert isinstance(ignore_errors, bool)
780 flags.append("-q")
781
782 if global_ is not None and global_:
783 assert isinstance(global_, bool)
784 flags.append("-g")
785
786 if scope is not None and not isinstance(scope, _DefaultOptionScope):
787 assert scope in OPTION_SCOPE_FLAG_MAP
788 scope_flag = OPTION_SCOPE_FLAG_MAP[scope]
789 if scope_flag: # Session scope has empty string, skip it
790 flags.append(scope_flag)
791
792 cmd = self.cmd(
793 "set-option",
794 *flags,
795 option,
796 )
797
798 if isinstance(cmd.stderr, list) and len(cmd.stderr):
799 handle_option_error(cmd.stderr[0])
800
801 return self
802
803 def _show_options_raw(
804 self,
805 g: bool | None = False,
806 global_: bool | None = False,
807 scope: OptionScope | _DefaultOptionScope | None = DEFAULT_OPTION_SCOPE,
808 include_hooks: bool | None = None,
809 include_inherited: bool | None = None,
810 quiet: bool | None = None,
811 values_only: bool | None = None,
812 ) -> tmux_cmd:
813 """Return a dict of options for the target.
814
815 Parameters
816 ----------
817 g : bool, optional
818 .. deprecated:: 0.50.0
819 Use ``global_`` instead.
820 quiet : bool, optional
821 Suppress errors silently (``-q`` flag).
822
823 .. versionadded:: 0.56
824 values_only : bool, optional
825 Return only option values without names (``-v`` flag).
826
827 .. versionadded:: 0.56
828
829 Examples
830 --------
831 >>> import typing as t
832 >>> from libtmux.common import tmux_cmd
833 >>> from libtmux.constants import OptionScope
834
835 >>> class MyServer(OptionsMixin):
836 ... socket_name = server.socket_name
837 ... def cmd(self, cmd: str, *args: object):
838 ... cmd_args: t.List[t.Union[str, int]] = [cmd]
839 ... if self.socket_name:
840 ... cmd_args.insert(0, f"-L{self.socket_name}")
841 ... cmd_args.insert(0, "-f/dev/null")
842 ... return tmux_cmd(*cmd_args, *args)
843 ...
844 ... default_option_scope = OptionScope.Server
845
846 >>> MyServer()._show_options_raw()
847 <libtmux.common.tmux_cmd object at ...>
848
849 >>> MyServer()._show_options_raw().stdout
850 [...]
851 """
852 if scope is DEFAULT_OPTION_SCOPE:
853 scope = self.default_option_scope
854
855 flags: tuple[str, ...] = ()
856
857 if g:
858 warnings.warn(
859 "g argument is deprecated in favor of global_",
860 category=DeprecationWarning,
861 stacklevel=2,
862 )
863 global_ = g
864
865 if global_:
866 flags += ("-g",)
867
868 if scope is not None and not isinstance(scope, _DefaultOptionScope):
869 assert scope in OPTION_SCOPE_FLAG_MAP
870 scope_flag = OPTION_SCOPE_FLAG_MAP[scope]
871 if scope_flag: # Session scope has empty string, skip it
872 flags += (scope_flag,)
873
874 if include_inherited is not None and include_inherited:
875 flags += ("-A",)
876
877 if include_hooks is not None and include_hooks:
878 flags += ("-H",)
879
880 if quiet is not None and quiet:
881 flags += ("-q",)
882
883 if values_only is not None and values_only:
884 flags += ("-v",)
885
886 return self.cmd("show-options", *flags)
887
888 def _show_options_dict(
889 self,
890 g: bool | None = False,
891 global_: bool | None = False,
892 scope: OptionScope | _DefaultOptionScope | None = DEFAULT_OPTION_SCOPE,
893 include_hooks: bool | None = None,
894 include_inherited: bool | None = None,
895 quiet: bool | None = None,
896 ) -> UntypedOptionsDict:
897 """Return dict of options for the target.
898
899 Parameters
900 ----------
901 g : bool, optional
902 .. deprecated:: 0.50.0
903 Use ``global_`` instead.
904
905 Examples
906 --------
907 >>> import typing as t
908 >>> from libtmux.common import tmux_cmd
909 >>> from libtmux.constants import OptionScope
910
911 >>> class MyServer(OptionsMixin):
912 ... socket_name = server.socket_name
913 ... def cmd(self, cmd: str, *args: object):
914 ... cmd_args: t.List[t.Union[str, int]] = [cmd]
915 ... if self.socket_name:
916 ... cmd_args.insert(0, f"-L{self.socket_name}")
917 ... cmd_args.insert(0, "-f/dev/null")
918 ... return tmux_cmd(*cmd_args, *args)
919 ...
920 ... default_option_scope = OptionScope.Server
921
922 >>> MyServer()._show_options_dict()
923 {...}
924
925 >>> isinstance(MyServer()._show_options_dict(), dict)
926 True
927 """
928 cmd = self._show_options_raw(
929 global_=global_,
930 scope=scope,
931 include_hooks=include_hooks,
932 include_inherited=include_inherited,
933 quiet=quiet,
934 )
935
936 return parse_options_to_dict(
937 io.StringIO("\n".join(cmd.stdout)),
938 )
939
940 def _show_options(
941 self,
942 g: bool | None = False,
943 global_: bool | None = False,
944 scope: OptionScope | _DefaultOptionScope | None = DEFAULT_OPTION_SCOPE,
945 include_hooks: bool | None = None,
946 include_inherited: bool | None = None,
947 quiet: bool | None = None,
948 ) -> ExplodedComplexUntypedOptionsDict:
949 """Return a dict of options for the target.
950
951 Parameters
952 ----------
953 g : bool, optional
954 .. deprecated:: 0.50.0
955 Use ``global_`` instead.
956
957 Examples
958 --------
959 >>> import typing as t
960 >>> from libtmux.common import tmux_cmd
961 >>> from libtmux.constants import OptionScope
962
963 >>> class MyServer(OptionsMixin):
964 ... socket_name = server.socket_name
965 ... def cmd(self, cmd: str, *args: object):
966 ... cmd_args: t.List[t.Union[str, int]] = [cmd]
967 ... if self.socket_name:
968 ... cmd_args.insert(0, f"-L{self.socket_name}")
969 ... cmd_args.insert(0, "-f/dev/null")
970 ... return tmux_cmd(*cmd_args, *args)
971 ...
972 ... default_option_scope = OptionScope.Server
973
974 >>> MyServer()._show_options()
975 {...}
976 """
977 dict_output = self._show_options_dict(
978 global_=global_,
979 scope=scope,
980 include_hooks=include_hooks,
981 include_inherited=include_inherited,
982 quiet=quiet,
983 )
984
985 output_exploded = convert_values(
986 explode_complex(
987 explode_arrays(dict_output),
988 ),
989 )
990
991 return t.cast("ExplodedComplexUntypedOptionsDict", output_exploded)
992
993 def show_options(
994 self,
995 global_: bool = False,
996 scope: OptionScope | _DefaultOptionScope | None = DEFAULT_OPTION_SCOPE,
997 include_hooks: bool | None = None,
998 include_inherited: bool | None = None,
999 quiet: bool | None = None,
1000 ) -> ExplodedComplexUntypedOptionsDict:
1001 """Return all options for the target.
1002
1003 Parameters
1004 ----------
1005 global_ : bool, optional
1006 Pass ``-g`` flag for global options, default False.
1007 scope : OptionScope | _DefaultOptionScope | None, optional
1008 Option scope (Server/Session/Window/Pane), defaults to object's scope.
1009 include_hooks : bool, optional
1010 Include hook options (``-H`` flag).
1011 include_inherited : bool, optional
1012 Include inherited options (``-A`` flag).
1013 quiet : bool, optional
1014 Suppress errors silently (``-q`` flag).
1015
1016 .. versionadded:: 0.56
1017
1018 Returns
1019 -------
1020 ExplodedComplexUntypedOptionsDict
1021 Dictionary with all options, arrays exploded and values converted.
1022
1023 Raises
1024 ------
1025 :exc:`exc.OptionError`, :exc:`exc.UnknownOption`,
1026 :exc:`exc.InvalidOption`, :exc:`exc.AmbiguousOption`
1027
1028 Examples
1029 --------
1030 >>> options = server.show_options()
1031 >>> isinstance(options, dict)
1032 True
1033
1034 >>> 'buffer-limit' in options
1035 True
1036 """
1037 return self._show_options(
1038 global_=global_,
1039 scope=scope,
1040 include_hooks=include_hooks,
1041 include_inherited=include_inherited,
1042 quiet=quiet,
1043 )
1044
1045 def _show_option_raw(
1046 self,
1047 option: str,
1048 global_: bool = False,
1049 g: bool = False,
1050 scope: OptionScope | _DefaultOptionScope | None = DEFAULT_OPTION_SCOPE,
1051 ignore_errors: bool | None = None,
1052 include_hooks: bool | None = None,
1053 include_inherited: bool | None = None,
1054 ) -> tmux_cmd:
1055 """Return raw option output for target.
1056
1057 Parameters
1058 ----------
1059 option : str
1060 g : bool, optional
1061 .. deprecated:: 0.50.0
1062 Use ``global_`` instead.
1063
1064 Raises
1065 ------
1066 :exc:`exc.OptionError`, :exc:`exc.UnknownOption`,
1067 :exc:`exc.InvalidOption`, :exc:`exc.AmbiguousOption`
1068
1069 Examples
1070 --------
1071 >>> import typing as t
1072 >>> from libtmux.common import tmux_cmd
1073 >>> from libtmux.constants import OptionScope
1074
1075 >>> class MyServer(OptionsMixin):
1076 ... socket_name = server.socket_name
1077 ... def cmd(self, cmd: str, *args: object):
1078 ... cmd_args: t.List[t.Union[str, int]] = [cmd]
1079 ... if self.socket_name:
1080 ... cmd_args.insert(0, f"-L{self.socket_name}")
1081 ... cmd_args.insert(0, "-f/dev/null")
1082 ... return tmux_cmd(*cmd_args, *args)
1083 ...
1084 ... default_option_scope = OptionScope.Server
1085
1086 >>> MyServer().cmd('new-session', '-d')
1087 <libtmux.common.tmux_cmd object at ...>
1088
1089 >>> MyServer()._show_option_raw('exit-unattached', global_=True)
1090 <libtmux.common.tmux_cmd object at ...>
1091
1092 >>> MyServer()._show_option_raw('exit-unattached', global_=True).stdout
1093 ['exit-unattached off']
1094
1095 >>> isinstance(MyServer()._show_option_raw('exit-unattached', global_=True).stdout, list)
1096 True
1097
1098 >>> isinstance(MyServer()._show_option_raw('exit-unattached', global_=True).stdout[0], str)
1099 True
1100 """
1101 if scope is DEFAULT_OPTION_SCOPE:
1102 scope = self.default_option_scope
1103
1104 flags: tuple[str | int, ...] = ()
1105
1106 if g:
1107 warnings.warn(
1108 "g argument is deprecated in favor of global_",
1109 category=DeprecationWarning,
1110 stacklevel=2,
1111 )
1112 global_ = g
1113
1114 if global_:
1115 flags += ("-g",)
1116
1117 if scope is not None and not isinstance(scope, _DefaultOptionScope):
1118 assert scope in OPTION_SCOPE_FLAG_MAP
1119 scope_flag = OPTION_SCOPE_FLAG_MAP[scope]
1120 if scope_flag: # Session scope has empty string, skip it
1121 flags += (scope_flag,)
1122
1123 if ignore_errors is not None and ignore_errors:
1124 flags += ("-q",)
1125
1126 if include_inherited is not None and include_inherited:
1127 flags += ("-A",)
1128
1129 if include_hooks is not None and include_hooks:
1130 flags += ("-H",)
1131
1132 flags += (option,)
1133
1134 return self.cmd("show-options", *flags)
1135
1136 def _show_option(
1137 self,
1138 option: str,
1139 global_: bool = False,
1140 g: bool = False,
1141 scope: OptionScope | _DefaultOptionScope | None = DEFAULT_OPTION_SCOPE,
1142 ignore_errors: bool | None = None,
1143 include_hooks: bool | None = None,
1144 include_inherited: bool | None = None,
1145 ) -> ConvertedValue | None:
1146 """Return option value for the target.
1147
1148 todo: test and return True/False for on/off string
1149
1150 Parameters
1151 ----------
1152 option : str
1153 g : bool, optional
1154 .. deprecated:: 0.50.0
1155 Use ``global_`` instead.
1156
1157 Raises
1158 ------
1159 :exc:`exc.OptionError`, :exc:`exc.UnknownOption`,
1160 :exc:`exc.InvalidOption`, :exc:`exc.AmbiguousOption`
1161
1162 Examples
1163 --------
1164 >>> import typing as t
1165 >>> from libtmux.common import tmux_cmd
1166 >>> from libtmux.constants import OptionScope
1167
1168 >>> class MyServer(OptionsMixin):
1169 ... socket_name = server.socket_name
1170 ... def cmd(self, cmd: str, *args: object):
1171 ... cmd_args: t.List[t.Union[str, int]] = [cmd]
1172 ... if self.socket_name:
1173 ... cmd_args.insert(0, f"-L{self.socket_name}")
1174 ... cmd_args.insert(0, "-f/dev/null")
1175 ... return tmux_cmd(*cmd_args, *args)
1176 ...
1177 ... default_option_scope = OptionScope.Server
1178
1179 >>> MyServer().cmd('new-session', '-d')
1180 <libtmux.common.tmux_cmd object at ...>
1181
1182 >>> MyServer()._show_option('exit-unattached', global_=True)
1183 False
1184 """
1185 cmd = self._show_option_raw(
1186 option=option,
1187 global_=global_,
1188 scope=scope,
1189 ignore_errors=ignore_errors,
1190 include_hooks=include_hooks,
1191 include_inherited=include_inherited,
1192 )
1193
1194 if cmd.stderr is not None and len(cmd.stderr):
1195 handle_option_error(cmd.stderr[0])
1196
1197 options_output = cmd.stdout
1198
1199 if not len(options_output):
1200 return None
1201
1202 # Parse raw output first (preserves indexed keys like "status-format[0]")
1203 output_raw = parse_options_to_dict(io.StringIO("\n".join(cmd.stdout)))
1204
1205 # Handle tmux's inherited option marker: tmux appends "*" to option names
1206 # that are inherited from a parent scope (e.g., "visual-activity*" for an
1207 # option inherited from global scope). We need to check for both the exact
1208 # option name and the name with "*" suffix.
1209 option_key = option
1210 if option not in output_raw and f"{option}*" in output_raw:
1211 option_key = f"{option}*"
1212
1213 # Direct lookup for indexed queries (e.g., "status-format[0]")
1214 # tmux returns only that index's value, so we handle it before exploding
1215 if option_key in output_raw:
1216 return convert_value(output_raw[option_key])
1217
1218 # For base name queries, explode arrays and return structured data
1219 output_exploded = convert_values(explode_complex(explode_arrays(output_raw)))
1220
1221 if not isinstance(output_exploded, (dict, SparseArray)):
1222 return t.cast("ConvertedValue", output_exploded)
1223
1224 # Check for inherited marker in exploded output as well
1225 exploded_key = option
1226 if isinstance(output_exploded, dict):
1227 if option not in output_exploded and f"{option}*" in output_exploded:
1228 exploded_key = f"{option}*"
1229 if exploded_key not in output_exploded:
1230 return None
1231
1232 if isinstance(output_exploded, SparseArray):
1233 try:
1234 index = int(option)
1235 return output_exploded[index]
1236 except (ValueError, KeyError):
1237 return None
1238
1239 return t.cast("ConvertedValue | None", output_exploded[exploded_key])
1240
1241 def show_option(
1242 self,
1243 option: str,
1244 global_: bool = False,
1245 g: bool = False,
1246 scope: OptionScope | _DefaultOptionScope | None = DEFAULT_OPTION_SCOPE,
1247 ignore_errors: bool | None = None,
1248 include_hooks: bool | None = None,
1249 include_inherited: bool | None = None,
1250 ) -> t.Any | None:
1251 """Return option value for the target.
1252
1253 Parameters
1254 ----------
1255 option : str
1256 g : bool, optional
1257 .. deprecated:: 0.50.0
1258 Use ``global_`` instead.
1259
1260 Raises
1261 ------
1262 :exc:`exc.OptionError`, :exc:`exc.UnknownOption`,
1263 :exc:`exc.InvalidOption`, :exc:`exc.AmbiguousOption`
1264
1265 Examples
1266 --------
1267 >>> import typing as t
1268 >>> from libtmux.common import tmux_cmd
1269 >>> from libtmux.constants import OptionScope
1270
1271 >>> class MyServer(OptionsMixin):
1272 ... socket_name = server.socket_name
1273 ... def cmd(self, cmd: str, *args: object):
1274 ... cmd_args: t.List[t.Union[str, int]] = [cmd]
1275 ... if self.socket_name:
1276 ... cmd_args.insert(0, f"-L{self.socket_name}")
1277 ... cmd_args.insert(0, "-f/dev/null")
1278 ... return tmux_cmd(*cmd_args, *args)
1279 ...
1280 ... default_option_scope = OptionScope.Server
1281
1282 >>> MyServer().cmd('new-session', '-d')
1283 <libtmux.common.tmux_cmd object at ...>
1284
1285 >>> MyServer().show_option('exit-unattached', global_=True)
1286 False
1287 """
1288 if g:
1289 warnings.warn(
1290 "g argument is deprecated in favor of global_",
1291 category=DeprecationWarning,
1292 stacklevel=2,
1293 )
1294 global_ = g
1295
1296 return self._show_option(
1297 option=option,
1298 global_=global_,
1299 scope=scope,
1300 ignore_errors=ignore_errors,
1301 include_hooks=include_hooks,
1302 include_inherited=include_inherited,
1303 )