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:
- 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:
CLI#
- import_config.get_teamocil_dir()[source]#
Return teamocil configuration directory.
See also
tmuxp.workspace.importers.teamocil.import_teamocil()
- import_config.get_tmuxinator_dir()[source]#
Return tmuxinator configuration directory.
Checks for
TMUXINATOR_CONFIG
environmental variable.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:
- 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
. Thenloader.expand()
andloader.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
orswitch-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. Sotmux 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.
- finders.in_dir(extensions=['.yml', '.yaml', '.json'])[source]#
Return a list of workspace_files in
workspace_dir
.
- finders.in_cwd()[source]#
Return list of workspace_files in current working directory.
If filename is
.tmuxp.py
,.tmuxp.json
,.tmuxp.yaml
.Examples
>>> sorted(in_cwd()) ['.tmuxp.json', '.tmuxp.yaml']
Validation#
Processing#
- 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.
- 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.
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
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.
>>> 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'}
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:
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') )
config.expand()
session_config inline shorthand:from tmuxp import config session_config = config.expand(session_config)
config.trickle()
passes down default values from session -> window -> pane if applicable:session_config = config.trickle(session_config)
(You are here) We will create a
libtmux.Session
(a realtmux(1)
session) and iterate through the list of windows, and their panes, returning fulllibtmux.Window
andlibtmux.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).
- property session#
- build(session=None, append=False)[source]#
Build tmux workspace in session.
Optionally accepts
session
to build with only session object.Without
session
, it will uselibmtux.Server
atself.server
passed in on initialization to create a new Session object.- Return type:
- Parameters:
session (
libtmux.Session
) – session to build workspace inappend (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 throughsession_config['windows']
.Applies
window_options
to window.- Return type:
- Parameters:
session (
libtmux.Session
) – session to create windows inappend (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:
- Parameters:
window (
libtmux.Window
) – window to create panes forwindow_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:
- Parameters:
window (
libtmux.Window
) – window to create panes forwindow_config (dict) – config section for window
Workspace Freezer#
- freezer.freeze()[source]#
Freeze live tmux session into a tmuxp workspacee.
- Return type:
- Parameters:
session (
libtmux.Session
) – session object- Returns:
tmuxp compatible workspace
- Return type:
- freezer.inline()[source]#
Return workspace with inlined shorthands. Opposite of
loader.expand()
.
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
fortmuxp.util.run_before_script()
.