Server
A cloneable handle to one captured tmux server endpoint.
Source and package
-
Description#
Equality and hashing use only the captured
ServerIdentity. Clones share capability detection, request IDs, and executor shutdown state. Dropping a handle is nonblocking and does not stop the tmux daemon. Runtime owners should awaitServer::shutdown()before tearing down Tokio when deterministic client-child cleanup is required.What is on here
A tmux server does a great many things, so this type has a great many methods. They fall into a few groups:
- Connecting
- Reach the server tmux picks, one that
LIBTMUX_SOCKET_PATHorLIBTMUX_SOCKETnames, one you name, or the server this process is already inside, fromTMUXor from a value you pass; ask whether anything is listening. A socket path does not identify a daemon, sogeneration()captures the one answering, andrequire_generation()fails once a different one has taken the endpoint. With thecontrol-modefeature, which is off by default, run a handle's commands over an open control connection. Shutting down stops accepting clients and waits for the active ones; it never stops the daemon. - Reading how a handle was built
- Read back the endpoint identity, the socket by path and by name, the config file, the color mode, the tmux executable, and the timeout each command gets.
- Asking which tmux this is
- Detect what the configured tmux executable supports, which also describes one below the supported daemon minimum, and retry after a failed detection. Read the version of the daemon this handle reaches, which has passed the supported-minimum check and runs no user hook. Report where the configured tmux resolves.
- Finding one thing
- Look up a session or client by name, or a session, window or pane by tmux ID. Each reports
Ok(None)when tmux does not have it. - Listing everything
- List every session, window, pane or client; each keeps the reason it failed, so an outage does not read as an empty server. Or gather the whole tree in three tmux commands rather than one per object.
- Querying things and getting around
- Ask whether a session exists and which ones a client is attached to. Narrow a listing with
.iter()and a predicate built from the typed fieldsFilterableprovides, then take exactly one or one-or-none, or search one branch; thequeryfeature supplies this and is on by default. TheSessionTreeandWindowTreethathierarchy()returns hold their children as fields, so walking them costs no further tmux command. Moving up re-reads tmux and reportsOk(None)when the parent has gone. - Narrow
- Changing things
- Create a session, kill the server, lock every client, or start a server without creating a session. A body can also run in a session that is killed afterwards: a failure to create it, to run the body or to kill it comes back as a
ScopeError, and a cleanup failure carriesError::AfterEffect. If the future is dropped, the session is still killed while the Tokio runtime is alive. - Options and hooks
- Read the options set on the server itself, as names or decoded by their declared kind, or read one by name; the session and window defaults that sessions inherit have a global read and write of their own. A typed write checks the value against tmux's option table before anything is sent, and an unchecked write sends text and leaves tmux to refuse it. An option that holds a numbered set, such as
command-alias, has its own reads and writes. Hooks can be set, written whole, removed, and read back, either every hook that holds something or one by name.OptionValuesays how the reads and writes fit together. - Unchecked writeRemove
- Everything else tmux keeps
- Paste buffers, including moving one through a file; key bindings, also as typed fields on tmux 3.7 and later; the global environment; format expansion, configuration, and layout validation, which checks each layout and its pane count before any command applies it; shell commands; wait-for channels, including a lock held for the length of a body, which is released when the body returns, fails or panics, or when the scope is dropped; the history of each kind of prompt, which clearing forgets for every kind at once; and the access list, whose owner is always present and writable, so a caller cannot lock itself out.
- Formats and configShell
- Things that need a terminal
- Draw a popup, menu, prompt, chooser, window finder or pane numbers on an attached client. Popups, menus and prompts fail without one; tmux accepts the chooser with no client, and pane numbers from tmux 3.8, because each opens as a mode in a pane.
Anything tmux can do that is not here is reachable through
cmd(), which runs an arbitrary command and hands back its result, orchain(), which dispatches several as one invocation that stops at the first failure and cannot say which one failed.Examples#
use libtmux::test::TestServer;// In your own code this is `libtmux::Server::new()?`; the fixture keeps// the example off whichever tmux you are actually using.let guard = TestServer::new().await?;let server = guard.server();server.new_session("work").await?;assert_eq!(server.sessions().await?.len(), 1);guard.shutdown().await?;Construct a private server. Construct a handle without starting tmux, then create a session on its own socket. Use Rust 1.85 or newer with Cargo, and tmux 3.3a or newer, on a Unix system. In an empty directory, create a project and add the published crates:
Terminal window $ cargo init --name libtmux-api-example &&cargo add libtmux@0.1.2 tempfile@3.20 &&cargo add tokio@1.40 --features macros,rt,timeReplace
src/main.rswith this complete program. It owns a private tmux socket, applies a ten-second task deadline, and reports both task and cleanup errors.Server::kill()stops its daemon;Server::shutdown()closes its client executor. Successful cleanup removes the temporary directory even when the task fails. View source//! Construct a server handle, then start its private daemon.use std::error::Error;use std::time::Duration;use libtmux::{NewSessionOptions, Server};type ExampleError = Box<dyn Error>;fn check(condition: bool, message: &str) -> Result<(), ExampleError> {if condition {Ok(())} else {Err(message.into())}}async fn demonstrate(server: &Server) -> Result<(), ExampleError> {check(!server.is_alive().await, "construction started a daemon")?;check(server.config_file() == Some(std::path::Path::new("/dev/null")),"wrong config path",)?;let session = server.new_session(NewSessionOptions::new("work").command("cat")).await?;check(server.is_alive().await,"new_session did not start a daemon",)?;check(session.name().as_bytes() == b"work", "wrong session name")?;println!("construction: private daemon started by new_session");Ok(())}#[tokio::main(flavor = "current_thread")]async fn main() -> Result<(), ExampleError> {let root = std::path::Path::new("/tmp/libtmux-rs-dev");std::fs::create_dir_all(root)?;let directory = tempfile::Builder::new().prefix("api-construction-").tempdir_in(root)?;std::fs::write(directory.path().join("owner"),std::process::id().to_string(),)?;let server = Server::builder().socket_path(directory.path().join("tmux.sock")).config_file("/dev/null").default_timeout(Duration::from_secs(5)).build()?;let outcome = tokio::time::timeout(Duration::from_secs(10), demonstrate(&server)).await;// Stop the owned daemon before closing the client executor.let killed = server.kill().await;let closed = server.shutdown().await;let cleanup_failed = killed.is_err() || closed.is_err();let mut failures = Vec::new();match outcome {Ok(Ok(())) => {}Ok(Err(error)) => failures.push(format!("example failed: {error}")),Err(error) => failures.push(format!("example deadline: {error}")),}if let Err(error) = killed {failures.push(format!("daemon cleanup: {error}"));}if let Err(error) = closed {failures.push(format!("executor cleanup: {error}"));}if cleanup_failed {let retained = directory.keep();failures.push(format!("inspect retained directory {}", retained.display()));} else if let Err(error) = directory.close() {failures.push(format!("directory cleanup: {error}"));}if failures.is_empty() {Ok(())} else {Err(failures.join("; ").into())}}Run the consumer. Success exits with status 0; setup, operation, deadline or cleanup failures exit unsuccessfully and print diagnostics to stderr:
Terminal window $ cargo run --quietExpected output:
construction: private daemon started by new_session
Members97#
Collections and queries6#
- sessions method List every session on the server, preserving any failure.
- windows method List every window on the server, preserving any failure.
- panes method List every pane on the server, preserving any failure.
- clients method List every client attached to the server, preserving any failure.
- buffer_names method List the paste buffer names.
- hierarchy method Fetch the whole hierarchy in three commands.
Common operations65#
- new_session method Create a detached session and return it.
- kill method Stop the tmux daemon at this endpoint.
- hooks method Read every hook set at this server.
- source_file method Load a tmux configuration file into this server.
- options method Read every option set at this server, decoded by its declared kind.
- buffer method Read a paste buffer's exact bytes.
- set_buffer method Store data in a tmux paste buffer.
- delete_buffer method Delete one paste buffer.
- cmd method Execute one raw logical tmux command.
- set_option method Set one server option to text, unchecked.
- environment method Read one variable from the server's environment.
- set_environment method Set a variable in the server's own environment.
- unset_environment method Remove a variable from the server's environment.
- wait_for_channel method Wait for a
wait-forchannel to be signalled. - is_alive method Report whether a tmux daemon is answering at this endpoint.
- unset_option method Remove one server option.
- run_shell method Run a shell command through tmux and collect its output.
- session method Find the session with this exact name.
- window_by_id method Find the window with this id, preferring an active link then the lowest index.
- pane_by_id method Find the pane with this id.
- typed_option method Read one server option, decoded according to its declared kind.
- set_hook method Set one global hook.
- has_session method Report whether a session with this exact name exists.
- bind_key method Bind a key in one key table.
- unbind_key method Remove a key binding from one key table.
- unset_hook method Remove one global hook.
- start method Start a tmux server without creating a session.
- prompt_history method The entries tmux remembers for one kind of prompt.
- clear_prompt_history method Forget the entries tmux remembers for prompts.
- lock_all method Lock every client on the server.
- set_global_option method Set one global session option to text, unchecked.
- command_prompt method Open a command prompt on a client.
- chain method Dispatch several commands as one
tmux a \; binvocation. - from_env method Build a server from the
TMUXvariable tmux exports into every pane. - config_file method Return the captured config path, if configured.
- socket_path method Return the captured absolute socket path used for identity and dispatch.
- attached_sessions method List the sessions that have at least one client attached.
- display_menu method Show a menu over a client.
- colors method Return the configured tmux color mode.
- socket_name method Return the socket name tmux is given as
-L, if any. - over_control_mode method Return a handle whose commands run over an open control connection.
- builder method Start a consuming server builder.
- check_alive method Require a tmux daemon to be answering at this endpoint.
- environment_all method Read the server's whole environment.
- new method Construct a server whose socket is chosen as
ServerBuilder::build()describes: fromLIBTMUX_SOCKET_PATHorLIBTMUX_SOCKET, else left to tmux. - shutdown method Stop accepting clients and wait for every active client process.
- signal_channel method Signal a
wait-forchannel, releasing anything waiting on it. - access_rules method The users on this server's access list.
- array_option method Read every value an array option holds, by index.
- capabilities method Detect and share capabilities for the configured tmux executable.
- daemon_version method Return the version of the daemon this handle reaches.
- default_timeout method Return the captured per-command timeout.
- generation method Which tmux daemon is answering on this endpoint.
- hook method Read one hook's commands, or
Nonewhen it holds nothing. - identity method Return the captured structural endpoint identity.
- owns_control_client method Report whether this process itself opened the control client with this pid, and it is still running.
- resolved_tmux_executable method Resolve the configured tmux executable from the captured launch context.
- set_hooks method Write a whole hook at once.
- set_typed_global_option method Set one global session option to a typed value, checked before it is sent.
- set_typed_global_window_option method Set one global window option to a typed value, checked before it is sent.
- set_typed_option method Set one server option to a typed value, checked before it is sent.
- tmux_executable method Return the captured tmux executable value.
- typed_global_window_option method Read one global window option, decoded according to its declared kind.
- validate_layouts method Validate every planned layout before scripts or tmux mutations.
- with_channel_lock method Hold a
wait-forchannel for the length of an operation.
Other members26#
- append_array_option method Extend the value already at one index of an array option.
- choose method Open one of tmux's interactive choosers on a client.
- client method Find the client attached to this terminal.
- display_panes method Briefly show each pane's number on a client.
- display_popup method Show a popup over a client, running a command inside it.
- find_window method Open tmux's window finder for a search string.
- format method Expand a tmux format string and return the result.
- from_env_value method Build a server from an explicit
TMUXvalue. - grant_access method Let a user attach to this server.
- hide_environment method Hide a variable from processes tmux starts.
- key_bindings method List key bindings as tmux prints them.
- load_buffer method Fill a paste buffer from a file, letting tmux read it.
- lock_channel method Lock a
wait-forchannel, blocking later lock attempts on it. - option_names method List the server option names.
- require_generation method Fail unless the daemon answering is still the one that was captured.
- revoke_access method Stop a user attaching to this server.
- save_buffer method Write a paste buffer to a file, letting tmux do the writing.
- session_by_id method Find the session with this id.
- set_array_option method Write one index of an array option, leaving the others alone.
- set_global_window_option method Set one global window option to text, unchecked.
- spawn_shell method Run a shell command in the background and return immediately.
- typed_global_option method Read one global session option, decoded according to its declared kind.
- typed_key_bindings method List key bindings as fields: table, key, command, note and repeat.
- unlock_channel method Unlock a
wait-forchannel. - unset_array_option method Remove one index of an array option, leaving a gap where it was.
- with_session method Create a session, run an operation with it, then kill it.
Guides#
Pages that discuss Server.
In other ports#
A tmux server
| Language | Equivalent |
|---|---|
| Python | libtmux |
| Ruby | Lib |
| Lua | libtmux |
| PowerShell | Lib This cmdlet constructs a shared .NET LibTmux.Server handle without contacting tmux. |
| Julia | Lib Server describes an endpoint without contacting tmux. Read its hierarchy with snapshot. |
| Erlang | tmux open/1 observes an existing daemon and starts an endpoint owner. Domain rows remain immutable values. |
| Elixir | Lib Server describes an existing server by executable and socket. It neither connects nor reserves the server’s identity. |
| Haskell | No public Haskell equivalent is implemented; the current modules expose scalar values and version parsing. |
| TypeScript | server |
| Go | tmux |
| Java | io |
| Clojure | libtmux Opens a closeable Java server client for an explicit endpoint. Acquisitions return persistent maps with explicit Java references for effects. |
| Kotlin | io |
| Scala | io |
| C# | Lib |
| F# | Lib This F# module provides functions over the shared .NET LibTmux.Server type. |
| C++ | libtmux:: |
| Swift | Server |
| OCaml | Libtmux A client is a live, generation-bound server connection. Endpoint describes a socket without connecting; closing a client releases its resources. |
| Perl | Lib Construction records connection settings without tmux I/O. Optional LibTmux::Async::Server returns standard Future results for operations. |
No equivalent is recorded in Common Lisp.