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-ts latest

Server

One tmux server, addressed by the socket it listens on.

Source and package
Qualified name
Server
Module
server
Package
libtmux
Source
packages/libtmux/src/server.ts
Other languages
Perlclass Erlangmodule PowerShellcmdlet Juliastruct Elixirstruct Haskell Common Lisp PythonRubyLuaRustGoJavaC#C++SwiftKotlinScalaOCamltypealias F#module Clojurefunction
class server.Server

Description#

Constructing this starts no process. tmux spawns the daemon on the first command that needs one, and a daemon already listening on that socket is used rather than replaced, so two Server values built from the same options address the same tmux.

Every command runs only on a daemon of tmux 3.3a or newer, judged by the daemon's own version rather than the client's. A daemon of an earlier release, or an executable that would start one, is refused with VersionTooLowError before the command has any effect, and a daemon that is replaced after the version check is refused with TmuxServerRestartedError.

Sessions, windows and panes are reached from here and carry the server with them. Handles taken from one daemon do not survive its restart: the replacement numbers panes from %0 again — see DaemonIdentity.

What is on here. A tmux server does a great many things, so this class has a great many members. They fall into a few groups:

Connecting
new Server() passes tmux no socket unless LIBTMUX_SOCKET_PATH or LIBTMUX_SOCKET is set, and ServerOptions names another with socketName() or socketPath(), which the variables never override. One liveness check answers false when nothing is listening, where the other rejects with tmux's reason. A restart on the same socket puts a different daemon there, which the daemon identity tells apart. The control-mode methods need tmux 3.7, each shows up in tmux as an attached client while it is open, and each refuses a server built with an engine.
Compare
Describe
Finding one thing
The existence check takes an exact name and answers false when no server is running. To get the object, read a Selection and ask it for one: one throws NoMatchError or MultipleMatchesError unless exactly one member matches, oneOrUndefined() answers undefined when none does and still throws MultipleMatchesError for several, and first answers undefined for no match and takes the head of several.
Exists
Listing everything
Each listing resolves to a Selection, reads tmux afresh, and rejects when the server cannot be reached, so an outage does not read as an empty server. Calling several in a row describes several different instants; a snapshot reads all of them at one instant, which is cheaper and consistent.
At one instant
Querying things and getting around
A Selection answers synchronously and issues no tmux command; it describes the instant it was read. Its where throws VersionTooLowError when a criterion names a field the running tmux lacks. Moving between levels reads nothing either: each step resolves against the snapshot its handle came from, and the way up and across answers undefined when nothing is there.
By index
Changing things
A new session is detached and resolves to its handle, and a kill terminates the server and every session on it. A batch runs mutations planned through a handle's plan, such as Session.plan(), in order and resolves each to what it made, all from one final snapshot. It is not atomic: tmux stops at the first failure and leaves everything before it applied. A command tmux refuses rejects with TmuxCommandError, which carries tmux's own stderr.
Running a program
A program gets a pane of its own with a real terminal, and no shell parses its argv. One method resolves with what the program printed once it ends; the other returns the running Program, which owns its pane and ends and removes it on await using or Program.kill(). Both need tmux 3.8 and reject with VersionTooLowError below it.
Options and hooks
Reads cover the server's own options, with the values it inherits added on request. The defaults that sessions and windows inherit take a "session" or "window" scope, and unsetting falls back to tmux's built-in value. Hooks read as a map from name to commands, and setting one replaces its commands unless append is set. getEnvironment() answers undefined when tmux carries no entry, and where unsetEnvironment() drops an entry, removeEnvironment() keeps it and marks it for removal from the processes tmux starts.
Everything else tmux keeps
A paste buffer reads as lines or as untouched bytes, is stored from a string, is fed through stdin when the data is large or binary, or is written by tmux to a file. A shell command returns the lines it printed, and a condition runs a tmux command when a shell test succeeds. Planned window layouts are checked before anything is created.
Things that need a terminal
Popups, menus, and choosers draw on an attached client, so they live on the pane they open over rather than on the server. With no client attached, the popup and the menu reject because tmux has no current client, while the chooser and search modes do nothing and report success.

Anything tmux can do that is not here is reachable through Server.cmd(), which runs one command and resolves to the lines it printed, or Server.pipeline(), which runs several in order and is not atomic.

Save this complete program as server.ts. With Bun 1.4.2 or newer, tmux 3.3a or newer, and libtmux installed, run bun run server.ts. It creates and stops a private tmux server. A failed operation or cleanup exits with an error; a cleanup error names the retained socket directory.

Examples#

import { strict as assert } from "node:assert";
import { mkdtemp, readdir, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { Server } from "libtmux";
const directory = await mkdtemp(join(tmpdir(), "ltx-example-"));
const server = new Server({
socketPath: join(directory, "tmux.sock"),
configFile: "/dev/null",
timeoutMs: 5_000,
});
const failures: unknown[] = [];
try {
assert.equal(await server.hasSession("work"), false);
const session = await server.newSession({
name: "work",
windowName: "editor",
shellCommand: "cat",
});
assert.equal(await server.hasSession("work"), true);
const snapshot = await server.snapshot();
assert.equal(snapshot.sessions.one({ name: "work" }).id, session.id);
assert.equal(snapshot.windows.count(), 1);
assert.equal(snapshot.panes.count(), 1);
console.log("work: 1 session, 1 window, 1 pane");
} catch (error) {
failures.push(error);
} finally {
try {
if ((await readdir(directory)).includes("tmux.sock")) await server.kill();
await rm(directory, { recursive: true });
} catch (error) {
failures.push(new Error(`Cleanup failed; inspect ${directory}`, { cause: error }));
}
}
if (failures.length > 0) throw new AggregateError(failures, "Example failed");

Members58#

Collections and queries7#

  • sessions method Every session on the server, read now.
  • windows method Every window on the server, including each placement of a linked window.
  • panes method Every pane on the server.
  • clients method Every client attached to the server.
  • listBuffers method Every buffer name this server holds.
  • listCommands method Every command name the running tmux understands.
  • snapshot method Acquire an immutable view of the server at this instant.

Common operations48#

  • newSession method Create a detached session and resolve it as a handle.
  • kill method Terminate the tmux server and every session on it.
  • showHooks method Every global hook tmux currently reports.
  • sourceFile method Run a tmux config file against this server.
  • showOptions method Every server-scope option tmux currently reports.
  • showBuffer method Read a named paste buffer's contents.
  • setBuffer method Put a string into a named paste buffer.
  • deleteBuffer method Discard a named paste buffer.
  • cmd method Run a tmux command this package does not model.
  • setOption method Set a server-scope option.
  • showEnvironment method Every variable in the server's global environment.
  • setEnvironment method Set a variable in the server's global environment.
  • unsetEnvironment method Drop a variable from the server's global environment entirely.
  • isAlive method Whether the tmux server is reachable.
  • unsetOption method Remove a server-scope option.
  • runShell method Run a shell command through tmux and return whatever it printed.
  • setHook method Bind a tmux command to a global hook.
  • loadBuffer method Fill a paste buffer from data fed through tmux's stdin.
  • hasSession method Whether a session with this name exists.
  • version method The tmux version this server is running.
  • unsetHook method Remove a global hook.
  • removeEnvironment method Mark a variable in the server's global environment for removal from the environment of processes tmux starts, leaving the entry in place.
  • saveBuffer method Write a paste buffer to a file instead of reading it back.
  • ifShell method Run one command or another depending on a condition.
  • raiseIfDead method Assert the server is reachable, raising with tmux's reason if not.
  • setGlobalOption method Set a default every session or window inherits.
  • configFile method The configuration file this server was pointed at, if any.
  • socketPath method The socket path this server addresses, if it was given one.
  • getEnvironment method One variable from the server's global environment, or undefined when tmux carries no entry.
  • showGlobalOptions method Read the defaults every session or window inherits.
  • colors method The terminal color override; undefined leaves detection to tmux.
  • socketName method The socket name this server addresses, if it was named rather than pathed.
  • batch method Run planned mutations in order, resolving each to what it made.
  • connect method Bind this server to one control-mode connection and return it.
  • pipeline method Run several tmux commands in order.
  • watch method Stream tmux's control-mode notifications until the stream is disposed.
  • checkAlive method Assert the server is reachable, raising with tmux's reason if not.
  • daemonIdentity method Which daemon is answering on this socket right now.
  • equals method Whether other is a handle addressing the same tmux server.
  • run method Run a program to completion in a pane of its own and return what it printed.
  • showBufferBytes method Read a named paste buffer without decoding or splitting its bytes.
  • showResolvedOptions method The option values that govern this server, own and inherited together.
  • spawn method Start a program in a pane of its own and return it running.
  • tmuxBin method The tmux executable this server runs.
  • unsetGlobalOption method Remove a default, so tmux falls back to its own built-in value.
  • validateLayouts method Check every planned window layout before setup scripts or mutations.
  • versionAtLeast method Whether this server is at least minimum, written the way tmux writes it.
  • withConnection method Run body against a connected server, closing it afterwards.

Other members3#

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.
Rust server.Server
Go tmux.Server
Java io.github.libtmux.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