Core Library0.xAPI Reference

Choose documentation 3

latest

Current version

latest
English

Early release libtmux is released, and its APIs may still change between releases. This site's structure and URLs may change too.

class libtmux-java latest

Server

Manages sessions, windows, and panes on a tmux server.

Source and package
Qualified name
io.github.libtmux.Server
Package
io.github.libtmux
Distribution
io.github.libtmux:libtmux
Source
libtmux/src/main/java/io/github/libtmux/Server.java
Other languages
Perlclass Erlangmodule PowerShellcmdlet Juliastruct Elixirstruct Haskell Common Lisp PythonRubyLuaTypeScriptRustGoC#C++SwiftKotlinScalaOCamltypealias F#module Clojurefunction
class io.github.libtmux.Server

Description#

Use #open() with a ServerConfig to select a server by socket name or path. A config that names none reads LIBTMUX_SOCKET_PATH and LIBTMUX_SOCKET, and with neither set leaves the choice to tmux. From this object, create sessions or query the server's existing sessions, windows, and panes. Each Session contains windows, and each Window contains panes.

Ownership is decided at construction and never inferred. #open() creates a transport this server closes exactly once; #using() borrows one the caller keeps, so several servers can share a transport and closing one leaves the others working.

Closing this object releases its owned transport. The tmux server and its sessions keep running. Call #killServer() to stop the tmux server.

Close it anyway. A server that owns its transport holds the threads that drain tmux's output, and those are not daemons, so that a reply being read when a program ends is finished rather than truncated. They do let go once they have been idle, so forgetting to close delays a JVM's exit by seconds instead of preventing it — but only closing releases them at once.

Threads. Share one freely. A server holds nothing a call changes, its transport is thread-safe by contract, and the record of what was typed into each pane is concurrent; calls from several threads run side by side, bounded by the transport's own admission. The same goes for every Session, Window and Pane it hands out: each is an immutable view of one capture, and a method that changes tmux changes tmux rather than the handle. Close it once, after the last call on any thread.

What is on here

A tmux server does a great many things, so this class has a great many methods. They fall into a few groups:

Connecting
Open a server over a transport it owns or one the caller keeps; closing releases only what it owns, and never kills tmux. A Builder configures either, and a built server starts a new builder from its own choices. A derived server bounds every command by a deadline of the caller's choosing, and a control client attaches through a session this server captured.
Derive and attach
Release
Checking the server
Ask whether the server answers, or require it and get a ServerUnavailableException when no daemon is running. The boolean form answers false when tmux refuses the probe, though a transport failure still throws, and a probe can take a deadline of its own. Report which tmux the running server is, or require a compatible tmux, which starts no daemon.
Finding one thing
Look up a session by name, id, or filter, a pane by id or filter, and a window by filter or by its WindowContext. Each returns an Optional that is empty when tmux does not have it; a name is matched exactly, and a filter that matches several throws. A session can also be checked for by name without fetching it.
Listing everything
List every session, window, pane, or client, or only the sessions a client is attached to, each captured now and in tmux's order. A failed read throws, so an outage does not read as an empty server. Listing windows by window id returns every link of a window shared between sessions, and a snapshot captures the whole tree as a ServerSnapshot with one listing per kind of object rather than one command per object.
Querying things and getting around
Hand a listing method, or a finder that returns one match, a filter built from the typed fields of Session_, Window_, and Pane_, and tmux does the filtering through -f when it can. io.github.libtmux.query.Selections takes exactly one, or one-or-none, from a list, and throws when several match. Moving between levels is a pure read of the capture, so none of it asks tmux again.
Changing things
Create a detached session from a name, from a callback that fills in a builder, or from a SessionSpec that can be reused across servers, and get back exactly the one tmux made. Killing a session matches its name exactly, where tmux would take a prefix, and throws when no session carries it. Killing the server ends every session on it, which closing deliberately does not, and a lock reaches every attached client.
Options, hooks, and environment
These return a handle on what tmux keeps for the whole server: the options it keeps once per server, the session options every session inherits unless it sets its own, the hooks every session inherits, and the environment every new process is given. Setting the environment changes what a pane opened later sees; a pane already running has its own copy.
Everything else tmux keeps
Paste buffers, key bindings, the command list, the message log, and the command prompt's history each have a handle of their own, as do the shell commands tmux runs and its wait-for channels. A file of tmux commands can be run as a configuration file would be. A format expands against the server, whether as one expression, as named variables in one expansion, or as chosen fields of every pane from one listing.
Shell and channels
Configuration
Running a command
Anything tmux can do that is not above is reachable by running a command directly. Run one command and get its result back, with a nonzero exit as data, or run one that is expected to work and get an exception on a nonzero exit. Several commands can be collected to run in one tmux invocation, each with its own outcome, or chained so each acts on what the last one made.

Examples#

Connect to a private tmux server. Use JDK 25, Gradle 9 or newer, and tmux 3.3a or newer on Linux, with /bin/cat and /bin/sh available. In an empty directory, save this consumer setup as settings.gradle.kts:

rootProject.name = "api-example"

Save this consumer setup as build.gradle.kts. It depends on the 0.1.2 release from Maven Central:

plugins {
application
}
repositories { mavenCentral() }
dependencies {
implementation("io.github.libtmux:libtmux:0.1.2")
}
java { toolchain { languageVersion.set(JavaLanguageVersion.of(25)) } }
application { mainClass.set(providers.gradleProperty("exampleMain")) }

Save this consumer setup as gradle.properties: View source

org.gradle.jvmargs=-Xmx2g -XX:MaxMetaspaceSize=768m -Dfile.encoding=UTF-8
kotlin.daemon.jvmargs=-Xmx2g
org.gradle.workers.max=2

Save this launcher as run.sh. It creates and stops a private tmux server, including after program failure. A shutdown failure retains its socket directory and exits unsuccessfully. View source

#!/bin/sh
set -eu
if [ "$#" -eq 0 ]; then
printf 'Usage: sh run.sh program [arguments...]\n' >&2
exit 2
fi
binary=$(command -v "${TMUX_BIN:-tmux}")
root=${API_RUN_ROOT:-/tmp/libtmux-java-dev}
# A client that names no socket follows TMUX or LIBTMUX_SOCKET*, and otherwise lands on the default
# socket under TMUX_TMPDIR. The program gets none of them, and a TMUX_TMPDIR of its own below.
unset TMUX TMUX_PANE
for name in $(env | sed -n 's/^\(LIBTMUX_SOCKET[A-Za-z0-9_]*\)=.*/\1/p'); do
unset "$name"
done
mkdir -p "$root"
directory=$(mktemp -d "$root/api.XXXXXX")
tmpdir=$(mktemp -d "$root/tmpdir.XXXXXX")
socket="$directory/tmux.sock"
config="$directory/tmux.conf"
serves() {
"$binary" -S "$1" display-message -p '#{pid}' >/dev/null 2>&1
}
# Stops the server on the socket, then waits for it to stop answering.
stop() {
"$binary" -S "$1" kill-server || return 1
attempts=0
while serves "$1" && [ "$attempts" -lt 60 ]; do
sleep 0.05
attempts=$((attempts + 1))
done
! serves "$1"
}
cleanup() {
status=$?
trap - 0 HUP INT TERM PIPE
# A closed output must not end the cleanup, whose messages are the only thing left to write.
trap '' PIPE
set +e
stuck=
left=
if [ -S "$socket" ] && serves "$socket" && ! stop "$socket"; then
stuck="$stuck tmux.sock"
fi
# Every socket anywhere under either directory, without following links. Only one a server answers
# on is a leak; the runner's own is expected to be there.
old_ifs=$IFS
IFS='
'
set -f
for candidate in $(find "$tmpdir" "$directory" -type s 2>/dev/null); do
[ "$candidate" = "$socket" ] && continue
serves "$candidate" || continue
case "$candidate" in
"$tmpdir"/*) name=${candidate#"$tmpdir"/} ;;
*) name=${candidate#"$directory"/} ;;
esac
left="$left $name"
stop "$candidate" || stuck="$stuck $name"
done
set +f
IFS=$old_ifs
if [ -n "$stuck" ]; then
printf 'tmux still answers on%s after kill-server; kept %s and %s under the runner root\n' \
"$stuck" "${directory##*/}" "${tmpdir##*/}" >&2
exit 1
fi
rm -rf "$directory" "$tmpdir" || exit 1
if [ -n "$left" ]; then
printf 'The program left a tmux server running:%s\n' "$left" >&2
exit 1
fi
exit "$status"
}
trap cleanup 0
trap 'exit 1' HUP INT TERM PIPE
# A default socket path longer than this does not fit in sun_path.
default_socket="$tmpdir/tmux-$(id -u)/default"
if [ "$(printf '%s' "$default_socket" | wc -c)" -gt 100 ]; then
printf 'API_RUN_ROOT is too long for a tmux socket\n' >&2
exit 1
fi
TMUX_TMPDIR=$tmpdir
export TMUX_TMPDIR
printf 'set-option -g default-shell /bin/sh\n' > "$config"
"$binary" -S "$socket" -f "$config" new-session -d -s work-one -n editor /bin/cat
"$binary" -S "$socket" split-window -h -t '=work-one:editor' /bin/cat
"$binary" -S "$socket" new-window -d -t '=work-one' -n logs /bin/cat
"$binary" -S "$socket" new-session -d -s work-two -n editor /bin/cat
"$@" "$binary" "$socket" "$config"
"$binary" -S "$socket" has-session -t '=work-one'
"$binary" -S "$socket" has-session -t '=work-two'

Save this complete program as src/main/java/Connect.java. It opens an ordinary client for the launcher's server; closing the client releases its transport. View source

package io.github.libtmux.examples.api.java;
import io.github.libtmux.Server;
import io.github.libtmux.ServerConfig;
import io.github.libtmux.ServerEndpoint;
import java.nio.file.Path;
/** Connect to a private tmux server. */
public final class Connect {
private Connect() {}
public static void main(String[] args) {
try {
if (args.length != 3) {
throw new IllegalArgumentException("expected: tmux-binary socket-path config-file");
}
var config = ServerConfig.builder()
.binary(args[0])
.endpoint(ServerEndpoint.socketPath(Path.of(args[1])))
.configFile(Path.of(args[2]))
.build();
try (Server server = Server.open(config)) {
System.out.println("connected=" + server.isAlive());
}
} catch (Exception error) {
if (error instanceof InterruptedException) Thread.currentThread().interrupt();
System.err.println("Example failed: " + error.getMessage());
System.exit(1);
}
}
}

Build the minimal consumer with Gradle and run the saved program with the private fixture. An operation or cleanup error makes the command exit unsuccessfully:

Terminal window
$ gradle --console=plain --quiet installDist -PexampleMain=io.github.libtmux.examples.api.java.Connect && \
sh run.sh build/install/api-example/bin/api-example

Expected output:

connected=true

Members65#

Collections and queries6#

  • sessions method The sessions this expression matches, captured now.
  • windows method Captures every winlink, preserving each session and index placement.
  • panes method Captures every pane on the server.
  • clients method Captures every attached client.
  • buffers method The server's paste buffers, which every session shares.
  • snapshot method Captures the whole hierarchy in at most four listings, retrying once if the server is replaced.

Common operations20#

  • newSession method Creates a detached session and returns that exact session.
  • killServer method Ends the tmux server and every session on it.
  • hooks method The global hooks every session inherits.
  • sourceFile method Runs a file of tmux commands, as a configuration file would be run.
  • options method The server-wide options, the ones tmux keeps once per server.
  • cmd method Runs one tmux command against this server.
  • isAlive method Whether the server is running and answering.
  • hasSession method Whether a session with this name exists.
  • version method Which tmux this server is running.
  • lock method Locks every client attached to this server.
  • requireAlive method Requires a running tmux daemon that answers the liveness probe.
  • killSession method Ends the session with this name, and everything in it.
  • chain method Starts a chain of commands where each one acts on what the last one made.
  • attachedSessions method Captures every session a client is attached to.
  • globalOptions method The global session options every session inherits unless it sets its own.
  • channel method One of this server's wait-for channels, which is where a signal is sent and waited for.
  • close method Releases an owned transport. Idempotent, and never kills tmux.
  • open method A server over a transport it owns and closes.
  • paneFields method Chosen fields for every pane on the server, from one listing.
  • within method This server, with every command bounded by a deadline of the caller's choosing.

Other members39#

  • admissionBound method How many tmux commands this server's transport runs at once, from ServerConfig#maxConcurrentCommands() for a server #open()ed here.
  • awaitChannel method
  • batch method Collects several commands to run in one tmux invocation.
  • batchReservingCapacity method Collects a group that may wait for a release through this server's transport.
  • builder method A builder holding the documented defaults.
  • Builder class Collects configuration and the ownership choice, then builds a server.
  • capture method How this server's own hierarchy is read back, for helpers that need one listing directly.
  • captureServer method Captures metadata and entity handles from one observed hierarchy.
  • chainReservingCapacity method Starts an implicit-target chain while reserving transport capacity for its release.
  • commands method The commands this tmux knows.
  • config method How this server was configured.
  • control method Attaches a control client to this session's server, and only to the process this capture named.
  • echo method What this library last typed into each of this server's panes.
  • environment method The server's environment, which every session inherits and every new process is given.
  • expand method Expands a tmux format against the server, and answers with what it came to.
  • failed method One sentence for a tmux command that did not succeed.
  • failure method
  • identity method Which server this is. Every handle taken from it is scoped by this.
  • keys method The server's key bindings: prefix when binding, every table when listing.
  • messageLog method The server's message log.
  • pane method The one pane this expression matches, captured now, or empty when none does.
  • printed method Runs one read with the server's version printed first in the same invocation, and answers with its output as tmux held the text, and without that version line. Line breaks at the end of the output are kept.
  • prompt method The command prompt's history.
  • refresh method
  • requireCompatibleTmux method Requires a compatible daemon, or a compatible executable when this endpoint is unused.
  • requireSameIncarnation method
  • requireSameServer method
  • run method Runs a command that is expected to work, and raises when it did not.
  • runBreak method
  • runTogether method Runs several commands in one invocation, so nothing of this caller's happens between them.
  • serverAbsent method Whether a failed command's stderr says the daemon itself is gone, rather than refusing the request.
  • session method The one session this expression matches, captured now, or empty when none does.
  • shell method Shell commands run by tmux, and tmux commands chosen by a shell exit status.
  • toBuilder method A builder holding every configuration and ownership choice this server made.
  • using method A server over a transport the caller owns. Closing this server never closes it.
  • variables method Reads only validated tmux variable names, never caller-authored format syntax.
  • versionForCreation method
  • window method The one window link this expression matches, captured now, or empty when none does.
  • withoutStartingServer method Runs a read that tmux would otherwise answer by starting a daemon.

Guides#

Pages that discuss Server.

In other ports#

A tmux server

Equivalents of A tmux server in other languages
Language Equivalent
Python libtmux.Server
Ruby LibTmux::Server
Lua libtmux.Server
PowerShell LibTmux\New-TmuxServer This cmdlet constructs a shared .NET LibTmux.Server handle without contacting tmux.
Julia LibTmux.Server Server describes an endpoint without contacting tmux. Read its hierarchy with snapshot.
Erlang tmux_server open/1 observes an existing daemon and starts an endpoint owner. Domain rows remain immutable values.
Elixir LibTmux.Server 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.Server
Rust server.Server
Go tmux.Server
Clojure libtmux.core/open! Opens a closeable Java server client for an explicit endpoint. Acquisitions return persistent maps with explicit Java references for effects.
Kotlin io.github.libtmux.kotlin.Server
Scala io.github.libtmux.scaladsl.Server
C# LibTmux.Server
F# LibTmux.FSharp.Server This F# module provides functions over the shared .NET LibTmux.Server type.
C++ libtmux::Server
Swift Server
OCaml Libtmux_unix.Client.t A client is a live, generation-bound server connection. Endpoint describes a socket without connecting; closing a client releases its resources.
Perl LibTmux::Server 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.

Esc

Type to search.

Reference previewOpen reference