Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 20 additions & 0 deletions MIGRATION
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,26 @@ sections below for detailed migration examples and code samples.
_Detailed migration steps for the next version will be posted here._
<!-- END PLACEHOLDER - ADD NEW MIGRATION ENTRIES BELOW THIS LINE -->

### 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`,
Expand Down
29 changes: 26 additions & 3 deletions docs/topics/options_and_hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
162 changes: 139 additions & 23 deletions src/libtmux/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
-----------------
Expand Down Expand Up @@ -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)

Expand All @@ -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):
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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).

Expand All @@ -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
------
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading