diff --git a/CHANGES b/CHANGES index 60ba16680..1d1bb773b 100644 --- a/CHANGES +++ b/CHANGES @@ -47,6 +47,26 @@ _Notes on the upcoming release will go here._ ### Breaking changes +#### User options are returned as strings (#826) + +{meth}`~libtmux.options.OptionsMixin.show_option` and +{meth}`~libtmux.options.OptionsMixin.show_options` return the value of an `@` +user option as the string tmux stores. `"123"`, `"on"` and `"off"` previously +came back as an integer or a boolean. Built-in options are converted as before. +See {ref}`options-and-hooks` and {ref}`migration`. + +Before, numeric and `on`/`off` user options were coerced (`3`, `True`, `False`): + +```python +retries = session.show_option("@retries") +``` + +After, convert explicitly when your application wants an integer or boolean: + +```python +retries = int(session.show_option("@retries")) +``` + #### Empty tmux fields read as `""` (#900) A field tmux reports as empty, such as a cleared diff --git a/MIGRATION b/MIGRATION index 75ce49c64..590bcd49c 100644 --- a/MIGRATION +++ b/MIGRATION @@ -116,6 +116,26 @@ sections below for detailed migration examples and code samples. _Detailed migration steps for the next version will be posted here._ +### User-option values remain strings (#759, #826) + +{meth}`~libtmux.options.OptionsMixin.show_option` and +{meth}`~libtmux.options.OptionsMixin.show_options` now preserve the strings +stored in tmux user options, whose names begin with `@`. Previously, `"123"` +became `123`, `"on"` became `True`, and `"off"` became `False`. Empty strings +remain empty strings. Built-in option conversions are unchanged. + +If your code needs a number or boolean from a user option, convert it +explicitly according to the values your application stores: + +```python +>>> _ = session.set_option('@count', '123') +>>> int(session.show_option('@count')) +123 +>>> _ = session.set_option('@enabled', 'off') +>>> session.show_option('@enabled') == 'on' +False +``` + ### Empty tmux fields read as `""` (#900) Fields that tmux reports as empty on {class}`~libtmux.Session`, diff --git a/docs/topics/options_and_hooks.md b/docs/topics/options_and_hooks.md index bc96727c4..f20c172ab 100644 --- a/docs/topics/options_and_hooks.md +++ b/docs/topics/options_and_hooks.md @@ -80,15 +80,38 @@ different level than the object in hand. Pass the `scope` parameter, drawn from ### Global options -Each scope also has a global layer — the fallback tmux uses when an object -hasn't set its own value. Reach it with `global_=True` when you want the -server-wide default rather than what one session or window happens to override: +Sessions and windows have global defaults. Use `global_=True` to read or set +those defaults. Server options are already shared by the server; panes have +no separate global layer. ```python >>> server.show_option('buffer-limit', global_=True) 50 ``` +### User options + +Names beginning with `@` are user options. Both +{meth}`~libtmux.options.OptionsMixin.show_option` and +{meth}`~libtmux.options.OptionsMixin.show_options` return their values as +strings, including `"123"`, `"on"`, `"off"`, and `""`: + +```python +>>> _ = session.set_option('@count', '123') +>>> session.show_option('@count') +'123' +>>> session.show_options()['@count'] +'123' +``` + +This applies to server, session, window, and pane user options, including +global session and window defaults. To read a global `@` default through a +child session, window, or pane, pass `include_inherited=True` to +{meth}`~libtmux.options.OptionsMixin.show_option` by name (tmux omits +inherited `@` options from bulk `show-options -A`). Built-in options keep +their existing conversions: `buffer-limit` returns an integer and +`automatic-rename` returns a boolean. + ## Hooks Hooks let you attach tmux commands to events, so something runs automatically diff --git a/src/libtmux/options.py b/src/libtmux/options.py index b330be7ec..e914599b5 100644 --- a/src/libtmux/options.py +++ b/src/libtmux/options.py @@ -39,15 +39,10 @@ User options ------------ -There are also custom user options, preceded with @, which exist are stored to -`Options.context.user_options` as a dictionary. - -> tmux set-option -w my-custom-variable my-value -invalid option: my-custom-option - -> tmux set-option -w @my-custom-option my-value -> tmux show-option -w -@my-custom-optione my-value +User options have names beginning with ``@``. Read and write them through +:meth:`OptionsMixin.show_option`, :meth:`OptionsMixin.show_options`, and +:meth:`OptionsMixin.set_option`. Their values remain strings, including +``"123"``, ``"on"``, ``"off"``, and the empty string. Inherited options ----------------- @@ -212,10 +207,116 @@ def convert_value( return value +_C_ESCAPES: dict[str, str] = { + "a": "\a", + "b": "\b", + "e": "\x1b", + "f": "\f", + "n": "\n", + "r": "\r", + "s": " ", + "t": "\t", + "v": "\v", +} + + +def _is_tmux_var_start(ch: str) -> bool: + """Match C-locale ``isalpha((u_char)c) || c == '_' || c == '{'`` in tmux ``vis``.""" + return ("A" <= ch <= "Z") or ("a" <= ch <= "z") or ch in ("_", "{") + + +def _unescape_user_option_value(raw: str) -> str: + r"""Decode a user-option value formatted by tmux ``args_escape`` (``#{q/a:...}``). + + tmux formats string options in ``show-options`` through ``args_escape`` + (``arguments.c``), which encodes tabs, newlines, backslashes, and control + bytes with ``utf8_strvis`` even when no outer quotes are added. Passing + unquoted ``a\nb`` to :func:`shlex.split` would strip the backslash and + return ``"anb"``. + + In ``args_escape``, ``$`` is in ``dquoted``, so any multi-character value + containing ``$`` sets ``VIS_DQ`` and emits ``2k + 1`` (odd) backslashes + before ``$[A-Za-z_{]``. tmux 3.4's ``server_client_print`` omits ``VIS_DQ`` + and adds one more backslash there (``2k + 2``, nonzero even); dropping one + backslash on an even run of length ``>= 2`` before ``$[A-Za-z_{]`` decodes + both losslessly. + + Examples + -------- + >>> _unescape_user_option_value("''") + '' + >>> _unescape_user_option_value(r"a\nb") + 'a\nb' + >>> _unescape_user_option_value('"both\\"and\'"') + 'both"and\'' + >>> _unescape_user_option_value(r'"\$HOME"') + '$HOME' + >>> _unescape_user_option_value(r'"\\$HOME"') + '$HOME' + >>> _unescape_user_option_value(r'"\\\$HOME"') + '\\$HOME' + >>> _unescape_user_option_value(r'"\\\\$HOME"') + '\\$HOME' + """ + if len(raw) >= 2 and raw[0] == raw[-1] and raw[0] in ("'", '"'): + raw = raw[1:-1] + out: list[str] = [] + i = 0 + n = len(raw) + while i < n: + ch = raw[i] + if ch != "\\": + out.append(ch) + i += 1 + continue + j = i + while j < n and raw[j] == "\\": + j += 1 + m = j - i + if j + 1 < n and raw[j] == "$" and _is_tmux_var_start(raw[j + 1]): + if m >= 2 and m % 2 == 0: + m -= 1 + if m > 1: + out.append("\\" * ((m - 1) // 2)) + out.append("$") + i = j + 1 + continue + if m >= 2: + out.append("\\" * (m // 2)) + if m % 2 == 0: + i = j + continue + if j >= n: + out.append("\\") + i = j + continue + nxt = raw[j] + if ( + nxt in "0123" + and j + 2 < n + and raw[j + 1] in "01234567" + and raw[j + 2] in "01234567" + ): + out.append(chr(int(raw[j : j + 3], 8))) + i = j + 3 + elif nxt in _C_ESCAPES: + out.append(_C_ESCAPES[nxt]) + i = j + 1 + else: + out.append(nxt) + i = j + 1 + return "".join(out) + + +def _is_user_option(name: object) -> bool: + """Identify user options, including tmux's inherited ``*`` marker.""" + return isinstance(name, str) and name.startswith("@") + + def convert_values( value: _V | None, ) -> ConvertedValues | _V | None: - """Recursively convert values to python types via :func:`convert_value`. + """Convert values via :func:`convert_value`, preserving user-option strings. >>> convert_values(None) @@ -234,13 +335,16 @@ def convert_values( >>> convert_values({"visual-bell": "on"}) {'visual-bell': True} + + >>> convert_values({"@count": "123", "@enabled*": "on"}) + {'@count': '123', '@enabled*': 'on'} """ if value is None: return None if isinstance(value, dict): # Note: SparseArray inherits from dict, so this branch handles both for k, v in value.items(): - value[k] = convert_value(v) + value[k] = v if _is_user_option(k) else convert_value(v) return value if isinstance(value, list): for idx, v in enumerate(value): @@ -312,19 +416,23 @@ def parse_options_to_dict( val: ConvertedValue | None = None for item in stdout.readlines(): - if " " in item: - try: - key, val = shlex.split(item) - except ValueError: - key, val = item.split(" ", maxsplit=1) + stripped = item.lstrip(" ") + if " " in stripped: + head, raw_val = stripped.removesuffix("\n").split(" ", maxsplit=1) + key = head.strip() + if _is_user_option(key): + val = _unescape_user_option_value(raw_val) + else: + try: + key, val = shlex.split(item) + except ValueError: + key, val = item.split(" ", maxsplit=1) + val = val.rstrip("\n") + key = key.strip() else: - key, val = item, None - key = key.strip() + key, val = item.strip(), None if key: - if isinstance(val, str) and val.endswith("\n"): - val = val.rstrip("\n") - output[key] = val return output @@ -1021,7 +1129,9 @@ def show_options( include_hooks : bool, optional Include hook options (``-H`` flag). include_inherited : bool, optional - Include inherited options (``-A`` flag). + Include inherited built-in options (``-A`` flag). tmux omits + inherited ``@`` user options from bulk ``show-options -A``; query + them by name with :meth:`show_option` and ``include_inherited=True``. quiet : bool, optional Suppress errors silently (``-q`` flag). @@ -1030,7 +1140,8 @@ def show_options( Returns ------- ExplodedComplexUntypedOptionsDict - Dictionary with all options, arrays exploded and values converted. + Dictionary with all options, arrays exploded and built-in values + converted. User options (names beginning with ``@``) remain strings. Raises ------ @@ -1225,6 +1336,8 @@ def _show_option( # Direct lookup for indexed queries (e.g., "status-format[0]") # tmux returns only that index's value, so we handle it before exploding if option_key in output_raw: + if _is_user_option(option_key): + return output_raw[option_key] return convert_value(output_raw[option_key]) # For base name queries, explode arrays and return structured data @@ -1262,6 +1375,9 @@ def show_option( ) -> t.Any | None: """Return option value for the target. + User options (names beginning with ``@``) remain strings. Built-in options + retain their numeric, boolean, or structured conversions. + Parameters ---------- option : str diff --git a/tests/test_options.py b/tests/test_options.py index add215aee..c4057ba38 100644 --- a/tests/test_options.py +++ b/tests/test_options.py @@ -3,6 +3,7 @@ from __future__ import annotations import dataclasses +import io import textwrap import typing as t @@ -19,7 +20,14 @@ from libtmux._internal.sparse_array import SparseArray from libtmux.common import has_gte_version from libtmux.constants import OptionScope -from libtmux.options import TerminalOverrides, convert_values, explode_arrays +from libtmux.options import ( + OptionsMixin, + TerminalOverrides, + _unescape_user_option_value, + convert_values, + explode_arrays, + parse_options_to_dict, +) from libtmux.pane import Pane if t.TYPE_CHECKING: @@ -225,13 +233,201 @@ def test_options_grid(server: Server) -> None: assert objglobal__options.pane_base_index == 0 +USER_OPTION_ROUNDTRIP_VALUES: tuple[str, ...] = ( + "123", + "007", + "on", + "off", + "", + " ", + "hello world", + "a\nb", + r"a\nb", + "\n", + "hello\n\n", + "a\tb", + r"a\tb", + "\r", + "a\rb", + "a\r\nb", + "\x010", + "\x1b", + "\x7f", + "quote\"and'both", + '~has"double', + "back\\slash", + "$", + "$HOME", + "\\$HOME", + "\\\\$HOME", + "${USER}", + "$_priv", + "$HOME/$USER", + "$1", + "$é", + "\\$é", + "~literal", + "\\~literal", + "abc;", + "-g", + "café ☕", +) + + +@pytest.mark.parametrize( + ("scope", "global_"), + [ + (OptionScope.Server, False), + (OptionScope.Session, False), + (OptionScope.Session, True), + (OptionScope.Window, False), + (OptionScope.Window, True), + (OptionScope.Pane, False), + ], +) def test_custom_options( - server: Server, + session: Session, + scope: OptionScope, + global_: bool, ) -> None: - """Test tmux's user (custom) options.""" - session = server.new_session(session_name="test") - session.set_option("@custom-option", "test") - assert session._show_option("@custom-option") == "test" + """Preserve user-option strings in both read methods and inherited values.""" + window = session.active_window + pane = window.active_pane + assert pane is not None + obj = { + OptionScope.Server: session.server, + OptionScope.Session: session, + OptionScope.Window: window, + OptionScope.Pane: pane, + }[scope] + assert obj is not None + with pytest.raises(exc.InvalidOption): + obj.show_option("@unset-custom-option", global_=global_) + assert ( + obj.show_option( + "@unset-custom-option", + global_=global_, + ignore_errors=True, + ) + is None + ) + for value in USER_OPTION_ROUNDTRIP_VALUES: + obj.set_option("@custom-option", value, global_=global_) + assert obj.show_option("@custom-option", global_=global_) == value + assert ( + obj.show_option( + "@custom-option", + global_=global_, + ignore_errors=True, + ) + == value + ) + assert obj.show_options(global_=global_)["@custom-option"] == value + if global_: + assert obj.show_option("@custom-option", include_inherited=True) == value + if scope == OptionScope.Window: + assert pane.show_option("@custom-option", include_inherited=True) == value + + +def test_custom_options_standalone_mixin(server: Server) -> None: + """Decode user options on a standalone ``OptionsMixin`` without ``.server``.""" + from libtmux.common import tmux_cmd + + class StandaloneOptions(OptionsMixin): + default_option_scope = OptionScope.Server + + def cmd(self, cmd: str, *args: object) -> tmux_cmd: + cmd_args: list[str | int] = ["-f/dev/null", cmd] + if server.socket_name: + cmd_args.insert(0, f"-L{server.socket_name}") + return tmux_cmd(*cmd_args, *args) + + server.new_session(session_name="standalone-opt", detach=True) + standalone = StandaloneOptions() + standalone.set_option("@custom-var", "$HOME") + assert standalone.show_option("@custom-var") == "$HOME" + assert standalone.show_options()["@custom-var"] == "$HOME" + + +@pytest.mark.parametrize( + ("raw", "expected"), + [ + ("123", "123"), + ("007", "007"), + ("on", "on"), + ("off", "off"), + ("''", ""), + ('" "', " "), + ('"hello world"', "hello world"), + (r"a\nb", "a\nb"), + (r"\n", "\n"), + (r"hello\n\n", "hello\n\n"), + (r"a\tb", "a\tb"), + ('"quote\\"and\'both"', "quote\"and'both"), + ("'~has\"double'", '~has"double'), + (r"back\\slash", "back\\slash"), + (r"\$", "$"), + # tmux 3.3a and 3.5+: 2k + 1 (odd) backslashes before $[A-Za-z_{] + (r'"\$HOME"', "$HOME"), + (r'"\\\$HOME"', "\\$HOME"), + (r'"\\\\\$HOME"', "\\\\$HOME"), + (r'"\${USER}"', "${USER}"), + (r'"\$_priv"', "$_priv"), + (r'"\$HOME/\$USER"', "$HOME/$USER"), + # tmux 3.4 server_client_print quirk: 2k + 2 (nonzero even) backslashes + (r'"\\$HOME"', "$HOME"), + (r'"\\\\$HOME"', "\\$HOME"), + (r'"\\\\\\$HOME"', "\\\\$HOME"), + (r'"\\${USER}"', "${USER}"), + (r'"\\$_priv"', "$_priv"), + (r'"\\$HOME/\\$USER"', "$HOME/$USER"), + # Non-variable $ (digit, end, or non-ASCII after $): C-locale isalpha only + ('"$1"', "$1"), + (r'"\\$1"', "\\$1"), + ('"$é"', "$é"), + (r'"\\$é"', "\\$é"), + (r'"\\\\$é"', "\\\\$é"), + (r'"\\$"', "\\$"), + # Tilde, semicolon, flags, UTF-8, octal and C escapes + (r"\~literal", "~literal"), + (r"\\~literal", "\\~literal"), + ('"abc;"', "abc;"), + ("-g", "-g"), + ('"café ☕"', "café ☕"), + (r"\007\033\e\s", "\a\x1b\x1b "), + ("\\", "\\"), + ], +) +def test_unescape_user_option_value(raw: str, expected: str) -> None: + """Decode tmux ``args_escape`` user-option tokens across all supported versions.""" + assert _unescape_user_option_value(raw) == expected + + +def test_parse_options_to_dict_preserves_trailing_newlines_and_escapes() -> None: + """Preserve decoded trailing newlines while stripping raw fallback line endings.""" + raw = io.StringIO( + "@nl \\n\n" + "@two_nl hello\\n\\n\n" + '@space " "\n' + "@empty ''\n" + '@tmux34* "\\\\$HOME"\n' + '@nonascii "\\\\$é"\n' + 'command-alias[0] "choose-session=choose-tree -s"\n' + "session-renamed[0] display-message 'renamed'\n" + 'malformed "unclosed\n' + ) + parsed = parse_options_to_dict(raw) + assert parsed == { + "@nl": "\n", + "@two_nl": "hello\n\n", + "@space": " ", + "@empty": "", + "@tmux34*": "$HOME", + "@nonascii": "\\$é", + "command-alias[0]": "choose-session=choose-tree -s", + "session-renamed[0]": "display-message 'renamed'", + "malformed": '"unclosed', + } MOCKED_GLOBAL_OPTIONS: list[LiteralString] = """