API Reference#

See also

See libtmux’s API and Quickstart to see how you can control tmux via python API calls.

Internals#

Warning

Be careful with these! Internal APIs are not covered by version policies. They can break or be removed between minor versions.

If you need an internal API stabilized please file an issue.

util.run_before_script(cwd=None)[source]#

Function to wrap try/except for subprocess.check_call().

Return type:

int

util.oh_my_zsh_auto_title()[source]#

Give warning and offer to fix DISABLE_AUTO_TITLE.

See: https://github.com/robbyrussell/oh-my-zsh/pull/257

Return type:

None

util.get_current_pane()[source]#

Return Pane if one found in env

Return type:

Optional[Pane]

util.get_session(session_name=None, current_pane=None)[source]#
Return type:

Session

util.get_window(window_name=None, current_pane=None)[source]#
Return type:

Window

util.get_pane(current_pane=None)[source]#
Return type:

Pane

CLI#

import_config.get_teamocil_dir()[source]#

Return teamocil configuration directory.

Return type:

str

Returns:

absolute path to teamocil config directory

Return type:

str

See also

tmuxp.workspace.importers.teamocil.import_teamocil()

import_config.get_tmuxinator_dir()[source]#

Return tmuxinator configuration directory.

Checks for TMUXINATOR_CONFIG environmental variable.

Return type:

str

Returns:

absolute path to tmuxinator config directory

Return type:

str

See also

tmuxp.workspace.importers.tmuxinator.import_tmuxinator()

load.load_workspace(socket_name=None, socket_path=None, tmux_config_file=None, new_session_name=None, colors=None, detached=False, answer_yes=False, append=False)[source]#

Load a tmux “workspace” session via tmuxp file.

Return type:

Optional[Session]

Parameters:
  • workspace_file (list of str) – paths or session names to workspace files

  • socket_name (str, optional) – tmux -L <socket-name>

  • socket_path (str, optional) – tmux -S <socket-path>

  • new_session_name (str, options) – tmux new -s <new_session_name>

  • colors (str, optional) –

    ‘-2’

    Force tmux to support 256 colors

  • detached (bool) – Force detached state. default False.

  • answer_yes (bool) – Assume yes when given prompt to attach in new session. Default False.

  • append (bool) – Assume current when given prompt to append windows in same session. Default False.

Notes

tmuxp will check and load a workspace file. The file will use ConfigReader to load a JSON/YAML into a dict. Then loader.expand() and loader.trickle() will be used to expand any shorthands, template variables, or file paths relative to where the config/script is executed from.

loader.expand() accepts the directory of the config file, so the user’s workspace can resolve absolute paths relative to where the workspace file is. In otherwords, if a workspace file at /var/moo/hi.yaml has ./ in its workspaces, we want to be sure any file path with ./ is relative to /var/moo, not the user’s PWD.

A libtmux.Server object is created. No tmux server is started yet, just the object.

The prepared workspace and its server object is passed into an instance of WorkspaceBuilder.

A sanity check against libtmux.common.which() is ran. It will raise an exception if tmux isn’t found.

If a tmux session under the same name as session_name in the tmuxp workspace exists, tmuxp offers to attach the session. Currently, tmuxp does not allow appending a workspace / incremental building on top of a current session (pull requests are welcome!).

build() will build the session in the background via using tmux’s detached state (-d).

After the session (workspace) is built, unless the user decided to load the session in the background via tmuxp -d (which is in the spirit of tmux’s -d), we need to prompt the user to attach the session.

If the user is already inside a tmux client, which we detect via the TMUX environment variable bring present, we will prompt the user to switch their current client to it.

If they’re outside of tmux client - in a plain-old PTY - we will automatically attach.

If an exception is raised during the building of the workspace, tmuxp will prompt to cleanup ($ tmux kill-session) the session on the user’s behalf. An exception raised during this process means it’s not easy to predict how broken the session is.

Changed in version tmux: 2.6+

In tmux 2.6, the way layout and proportion’s work when interfacing with tmux in a detached state (outside of a client) changed. Since tmuxp builds workspaces in a detached state, the WorkspaceBuilder isn’t able to rely on functionality requiring awarness of session geometry, e.g. set-layout.

Thankfully, tmux is able to defer commands to run after the user performs certain actions, such as loading a client via attach-session or switch-client.

Upon client switch, client-session-changed is triggered [1]_.

References

load._reattach()[source]#

Reattach session (depending on env being inside tmux already or not)

Parameters:

builder (workspace.builder.WorkspaceBuilder) –

Notes

If TMUX environmental variable exists in the environment this script is running, that means we’re in a tmux client. So tmux switch-client will load the session.

If not, tmux attach-session loads the client to the target session.

Workspace files#

Finding#

finders.is_workspace_file(extensions=['.yml', '.yaml', '.json'])[source]#

Return True if file has a valid workspace file type.

Return type:

bool

Parameters:
  • filename (str) – filename to check (e.g. mysession.json).

  • extensions (str or list) – filetypes to check (e.g. ['.yaml', '.json']).

Return type:

bool

finders.in_dir(extensions=['.yml', '.yaml', '.json'])[source]#

Return a list of workspace_files in workspace_dir.

Return type:

List[str]

Parameters:
  • workspace_dir (str) – directory to search

  • extensions (list) – filetypes to check (e.g. ['.yaml', '.json']).

Return type:

list

finders.in_cwd()[source]#

Return list of workspace_files in current working directory.

If filename is .tmuxp.py, .tmuxp.json, .tmuxp.yaml.

Return type:

List[str]

Returns:

workspace_files in current working directory

Return type:

list

Examples

>>> sorted(in_cwd())
['.tmuxp.json', '.tmuxp.yaml']
finders.get_workspace_dir()[source]#

Return tmuxp workspace directory.

TMUXP_CONFIGDIR environmental variable has precedence if set. We also evaluate XDG default directory from XDG_CONFIG_HOME environmental variable if set or its default. Then the old default ~/.tmuxp is returned for compatibility.

Return type:

str

Returns:

absolute path to tmuxp config directory

Return type:

str

Validation#

tmuxp.workspace.validation.validate_schema(workspace_dict)[source]#

Return True if workspace schema is correct.

Return type:

bool

Parameters:

workspace_dict (dict) – tmuxp workspace data

Return type:

bool

Processing#

loader.expandshell()[source]#

Return expanded path based on user’s $HOME and env.

os.path.expanduser() and os.path.expandvars().

Parameters:

path (str) – path to expand

Returns:

path with shell variables expanded

Return type:

str

loader.expand(cwd=None, parent=None)[source]#

Return workspace with shorthand and inline properties expanded.

This is necessary to keep the code in the WorkspaceBuilder clean and also allow for neat, short-hand “sugarified” syntax.

As a simple example, internally, tmuxp expects that workspace options like shell_command are a list (array):

'shell_command': ['htop']

tmuxp workspace allow for it to be simply a string:

'shell_command': 'htop'

ConfigReader will load JSON/YAML files into python dicts for you.

Parameters:
  • workspace_dict (dict) – the tmuxp workspace for the session

  • cwd (str) – directory to expand relative paths against. should be the dir of the workspace directory.

  • parent (str) – (used on recursive entries) start_directory of parent window or session object.

Return type:

dict

loader.trickle()[source]#

Return a dict with “trickled down” / inherited workspace values.

This will only work if workspace has been expanded to full form with loader.expand().

tmuxp allows certain commands to be default at the session, window level. shell_command_before trickles down and prepends the shell_command for the pane.

Parameters:

workspace_dict (dict) – the tmuxp workspace.

Return type:

dict

Workspace importers#

importers.import_teamocil()[source]#

Return tmuxp workspace from a `teamocil`_ yaml workspace. :rtype: Dict[str, Any]

Parameters:

workspace_dict (dict) – python dict for tmuxp workspace

Notes

Todos:

  • change ‘root’ to a cd or start_directory

  • width in pane -> main-pain-width

  • with_env_var

  • clear

  • cmd_separator

importers.import_tmuxinator()[source]#

Return tmuxp workspace from a `tmuxinator`_ yaml workspace. :rtype: Dict[str, Any]

Parameters:

workspace_dict (dict) – python dict for tmuxp workspace.

Return type:

dict

Configuration reader#

class tmuxp.config_reader.ConfigReader(content)[source]#

Bases: object

Parse string data (YAML and JSON) into a dictionary.

>>> cfg = ConfigReader({ "session_name": "my session" })
>>> cfg.dump("yaml")
'session_name: my session\n'
>>> cfg.dump("json")
'{\n  "session_name": "my session"\n}'
static _load(format, content)[source]#

Load raw config data and directly return it.

Return type:

Dict[str, Any]

>>> ConfigReader._load("json", '{ "session_name": "my session" }')
{'session_name': 'my session'}
>>> ConfigReader._load("yaml", 'session_name: my session')
{'session_name': 'my session'}
classmethod load(format, content)[source]#

Load raw config data into a ConfigReader instance (to dump later).

>>> cfg = ConfigReader.load("json", '{ "session_name": "my session" }')
>>> cfg
<tmuxp.config_reader.ConfigReader object at ...>
:rtype: ConfigReader
>>> cfg.content
{'session_name': 'my session'}
>>> cfg = ConfigReader.load("yaml", 'session_name: my session')
>>> cfg
<tmuxp.config_reader.ConfigReader object at ...>
>>> cfg.content
{'session_name': 'my session'}
classmethod _from_file(path)[source]#

Load data from file path directly to dictionary.

YAML file

For demonstration only, create a YAML file:

>>> yaml_file = tmp_path / 'my_config.yaml'
:rtype: :py:class:`~typing.Dict`\[:py:class:`str`, :py:data:`~typing.Any`]
>>> yaml_file.write_text('session_name: my session', encoding='utf-8')
24

Read YAML file:

>>> ConfigReader._from_file(yaml_file)
{'session_name': 'my session'}

JSON file

For demonstration only, create a JSON file:

>>> json_file = tmp_path / 'my_config.json'
>>> json_file.write_text('{"session_name": "my session"}', encoding='utf-8')
30

Read JSON file:

>>> ConfigReader._from_file(json_file)
{'session_name': 'my session'}
classmethod from_file(path)[source]#

Load data from file path

YAML file

For demonstration only, create a YAML file:

>>> yaml_file = tmp_path / 'my_config.yaml'
:rtype: :py:class:`~tmuxp.config_reader.ConfigReader`
>>> yaml_file.write_text('session_name: my session', encoding='utf-8')
24

Read YAML file:

>>> cfg = ConfigReader.from_file(yaml_file)
>>> cfg
<tmuxp.config_reader.ConfigReader object at ...>
>>> cfg.content
{'session_name': 'my session'}

JSON file

For demonstration only, create a JSON file:

>>> json_file = tmp_path / 'my_config.json'
>>> json_file.write_text('{"session_name": "my session"}', encoding='utf-8')
30

Read JSON file:

>>> cfg = ConfigReader.from_file(json_file)
>>> cfg
<tmuxp.config_reader.ConfigReader object at ...>
>>> cfg.content
{'session_name': 'my session'}
static _dump(format, content, indent=2, **kwargs)[source]#

Dump directly.

Return type:

str

>>> ConfigReader._dump("yaml", { "session_name": "my session" })
'session_name: my session\n'
>>> ConfigReader._dump("json", { "session_name": "my session" })
'{\n  "session_name": "my session"\n}'
dump(format, indent=2, **kwargs)[source]#

Dump via ConfigReader instance.

>>> cfg = ConfigReader({ "session_name": "my session" })
>>> cfg.dump("yaml")
'session_name: my session\n'
:rtype: :py:class:`str`
>>> cfg.dump("json")
'{\n  "session_name": "my session"\n}'

Workspace Builder#

class tmuxp.workspace.builder.WorkspaceBuilder(session_config, server, plugins=[])[source]#

Bases: object

Load workspace from workspace dict object.

Build tmux workspace from a configuration. Creates and names windows, sets options, splits windows into panes.

Examples

>>> import yaml
>>> session_config = yaml.load('''
...     session_name: sample workspace
...     start_directory: '~'
...     windows:
...     - window_name: editor
...       layout: main-vertical
...       panes:
...       - shell_command:
...         - cmd: vim
...       - shell_command:
...         - cmd: echo "hey"
...
...     - window_name: logging
...       panes:
...       - shell_command:
...         - cmd: tail | echo 'hi'
...
...     - window_name: test
...       panes:
...       - shell_command:
...         - cmd: htop
... ''', Loader=yaml.Loader)
>>> builder = WorkspaceBuilder(session_config=session_config, server=server)

New session:

>>> builder.build()
>>> new_session = builder.session
>>> new_session.name == 'sample workspace'
True
>>> len(new_session.windows)
3
>>> sorted([window.name for window in new_session.windows])
['editor', 'logging', 'test']

Existing session:

>>> len(session.windows)
1
>>> builder.build(session=session)

_Caveat:_ Preserves old session name:

>>> session.name == 'sample workspace'
False
>>> len(session.windows)
3
>>> sorted([window.name for window in session.windows])
['editor', 'logging', 'test']

The normal phase of loading is:

  1. Load JSON / YAML file via via pathlib.Path:

    from tmuxp import config_reader
    session_config = config_reader.ConfigReader._load(raw_yaml)
    

    The reader automatically detects the file type from pathlib.suffix.

    We can also parse raw file:

    import pathlib
    from tmuxp import config_reader
    
    session_config = config_reader.ConfigReader._from_file(
        pathlib.Path('path/to/config.yaml')
    )
    
  2. config.expand() session_config inline shorthand:

    from tmuxp import config
    session_config = config.expand(session_config)
    
  3. config.trickle() passes down default values from session -> window -> pane if applicable:

    session_config = config.trickle(session_config)
    
  4. (You are here) We will create a libtmux.Session (a real tmux(1) session) and iterate through the list of windows, and their panes, returning full libtmux.Window and libtmux.Pane objects each step of the way:

    workspace = WorkspaceBuilder(session_config=session_config, server=server)
    

It handles the magic of cases where the user may want to start a session inside tmux (when $TMUX is in the env variables).

session_name: str#
server: Server#
_session: Optional[Session]#
property session#
session_exists(session_name)[source]#
Return type:

bool

build(session=None, append=False)[source]#

Build tmux workspace in session.

Optionally accepts session to build with only session object.

Without session, it will use libmtux.Server at self.server passed in on initialization to create a new Session object.

Return type:

None

Parameters:
  • session (libtmux.Session) – session to build workspace in

  • append (bool) – append windows in current active session

iter_create_windows(session, append=False)[source]#

Return libtmux.Window iterating through session config dict.

Generator yielding libtmux.Window by iterating through session_config['windows'].

Applies window_options to window.

Return type:

Iterator[Any]

Parameters:
  • session (libtmux.Session) – session to create windows in

  • append (bool) – append windows in current active session

Returns:

Newly created window, and the section from the tmuxp configuration that was used to create the window.

Return type:

tuple of (libtmux.Window, window_config)

iter_create_panes(window, window_config)[source]#

Return libtmux.Pane iterating through window config dict.

Run shell_command with $ tmux send-keys.

Return type:

Iterator[Any]

Parameters:
  • window (libtmux.Window) – window to create panes for

  • window_config (dict) – config section for window

Returns:

Newly created pane, and the section from the tmuxp configuration that was used to create the pane.

Return type:

tuple of (libtmux.Pane, pane_config)

config_after_window(window, window_config)[source]#

Actions to apply to window after window and pane finished.

When building a tmux session, sometimes its easier to postpone things like setting options until after things are already structurally prepared.

Return type:

None

Parameters:
  • window (libtmux.Window) – window to create panes for

  • window_config (dict) – config section for window

find_current_attached_session()[source]#
Return type:

Session

first_window_pass(i, session, append)[source]#
Return type:

bool

Workspace Freezer#

freezer.freeze()[source]#

Freeze live tmux session into a tmuxp workspacee.

Return type:

Dict[str, Any]

Parameters:

session (libtmux.Session) – session object

Returns:

tmuxp compatible workspace

Return type:

dict

freezer.inline()[source]#

Return workspace with inlined shorthands. Opposite of loader.expand().

Parameters:

workspace_dict (dict) –

Returns:

workspace with shorthands inlined.

Return type:

dict

Exceptions#

exception tmuxp.exc.EmptyWorkspaceException[source]#

Bases: WorkspaceError

Workspace file is empty.

exception tmuxp.exc.WorkspaceError[source]#

Bases: TmuxpException

Error parsing tmuxp workspace data.

exception tmuxp.exc.BeforeLoadScriptError(returncode, cmd, output=None)[source]#

Bases: Exception

Exception replacing subprocess.CalledProcessError for tmuxp.util.run_before_script().

exception tmuxp.exc.BeforeLoadScriptNotExists(*args, **kwargs)[source]#

Bases: OSError