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.

struct libtmux-go latest

Server

Server is an immutable handle to one tmux configuration. Its zero value is invalid. Copying a configured Server preserves its configuration and shares its mutex-guarded version cache and checked daemon identity, so a Server and the values derived from it are safe for concurrent method calls (see the package documentation).

Source and package
Qualified name
tmux.Server
Package
tmux
Distribution
github.com/libtmux/libtmux-go/tmux
Source
tmux/server.go
Other languages
Perlclass Erlangmodule PowerShellcmdlet Juliastruct Elixirstruct Haskell Common Lisp PythonRubyLuaTypeScriptRustJavaC#C++SwiftKotlinScalaOCamltypealias F#module Clojurefunction
struct tmux.Server

Description#

NewServer resolves the executable, socket, and environment once and does not start tmux; creating the first session starts the daemon. A plain Server starts a tmux process for each command it sends, so discarding one leaves the daemon running; Server.Kill stops it. A Server from Connection.Server sends its commands over that connection's control lanes instead. Operations on the zero Server return ErrInvalidServer.

What is on here

Operations on one session, window, or pane live on Session, Window, and Pane, such as Session.NewWindow, Window.SplitPane, Pane.SendKeys, and Pane.Capture. This type holds what belongs to the server as a whole, in the groups below.

Connecting
Build a handle from a ServerOptions or from the TMUX variable; neither starts tmux. Of the two liveness checks, one answers false for an absent server and the other makes an absent server an error. A version minimum fails with ErrVersionTooLow, and a control-mode client, or a session created together with its Connection, needs tmux 3.7.
Identity
Finding one thing
A lookup that finds nothing returns an error matching ErrNotFound, or ErrNoServer when no server is running. The existence check returns a bool instead, and a missing server counts as no session.
Exists
Listing everything
Each listing returns one kind of record, and the window and pane listings cover every window link. Failures, including ErrNoServer, stay errors, so an outage does not read as an empty server. A Snapshot reads the sessions, windows, panes, and clients together, as sequential commands rather than one atomic transaction.
Together
Raw lines
Querying things and getting around
The search methods pass a TmuxFilter to tmux, which drops the rows that do not match before any record exists. To filter in Go instead, apply a SessionFilter, WindowFilter, PaneFilter, or ClientFilter to a slice with tmuxq.Matching, or pass a predicate to tmuxq.Where, tmuxq.First, or tmuxq.ExactlyOne, which fails unless exactly one value matches. Records from a snapshot, and from the listings above, know their neighbors without querying tmux, but a record from a search, a lookup, or Server.NewSession carries no relations and reports false; the Resolve methods read live state for any record.
Changing things
A new session is detached and never changes client focus; the first one starts the daemon. A kill takes everything inside with it: one stops the daemon with all its sessions, windows, panes, and clients, and the other ends the session a tmux target selects, leaving pattern and prefix matching to tmux. Start starts the daemon without a session, so with tmux's exit-empty default it can exit before the next command.
Options and hooks
Options read back as a typed ServerOptionValues, or one raw value by name, and a write by name reaches an option the typed setters do not cover. Each known option has a typed setter that ServerOptionValues pairs with its accessor, and an array option such as command-alias is replaced whole by a setter whose result reports the writes confirmed. The defaults that sessions and windows inherit, and the global hooks, sit on two scope handles rather than on Server itself.
Typed setters, for example
Array setters, for example
Everything else tmux keeps
Paste buffers read as lines or as exact bytes and load from a string, a file, or a stream; the stream forms return ErrConnectionRequiresProcess on a handle bound to a Connection, which loads and saves by path instead. A shell command's captured output needs tmux 3.5, and before tmux 3.8 abandoning a wait-for lock costs its channel one unlock. Layout validation checks each layout and its pane count before any mutation.
Configuration and layouts
Channels
Messages and formats
Commands and access
Things that need a terminal
Menus, prompts, and confirmations draw on an attached client, and tmux refuses them without one. Attaching hands the caller's own terminal to a session and blocks until it detaches. Switching, detaching, locking, suspending, and refreshing a client act on a client, named or tmux's current one, and fail without one. Locking the server instead locks every attached client.
Attach
Every client

Anything tmux can do that is not here is reachable through Server.Cmd, which runs raw tmux arguments and returns a CommandResult; a completed nonzero exit is a result, not an error.

Examples#

Open a private server and create a session on it. Find that session, then read the server once and walk from a pane up to its window and session without another tmux command. A search asks tmux to filter instead. The temporary server is stopped even when an operation fails. Use Go 1.26 or newer and tmux 3.3a or newer on a Unix system, with tmux and cat on PATH. In a new directory, create a module and add the library from the Go module proxy:

Terminal window
$ go mod init example.com/libtmux-api && \
go get github.com/libtmux/libtmux-go@latest

Save this complete example as example_test.go. It creates a private temporary socket and stops its server before removing the directory. Cleanup failure fails the example and retains the socket directory. View source

package tmux_test
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"time"
"github.com/libtmux/libtmux-go/tmux"
)
// Open a private server and create a session on it. Find that session, then
// read the server once and walk from a pane up to its window and session
// without another tmux command. A search asks tmux to filter instead.
// The temporary server is stopped even when an operation fails.
func ExampleServer_complete() {
run := func() (runErr error) {
directory, err := os.MkdirTemp("", "libtmux-go-api-")
if err != nil {
return fmt.Errorf("create socket directory: %w", err)
}
server, err := tmux.NewServer(tmux.ServerOptions{
SocketPath: filepath.Join(directory, "tmux.sock"),
ConfigFile: "/dev/null",
})
if err != nil {
return errors.Join(err, os.RemoveAll(directory))
}
defer func() {
// Cleanup has its own deadline because the operation may have timed out.
cleanup, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Kill(cleanup); err != nil && !errors.Is(err, tmux.ErrNoServer) {
runErr = errors.Join(runErr, fmt.Errorf("stop server at %s: %w", directory, err))
return
}
runErr = errors.Join(runErr, os.RemoveAll(directory))
}()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if _, err = server.NewSession(ctx, tmux.NewSessionRequest{
Name: "work", WindowName: "editor", Command: "cat", Width: 100, Height: 30,
}); err != nil {
return fmt.Errorf("create session: %w", err)
}
found, err := server.HasSession(ctx, tmux.HasSessionRequest{Target: "work"})
if err != nil {
return fmt.Errorf("find session: %w", err)
}
fmt.Println("has work:", found)
_, err = server.SessionByName(ctx, "missing")
fmt.Println("missing is not found:", errors.Is(err, tmux.ErrNotFound))
snapshot, err := server.Snapshot(ctx)
if err != nil {
return fmt.Errorf("snapshot: %w", err)
}
panes := snapshot.Panes()
if len(panes) == 0 {
return errors.New("snapshot holds no panes")
}
window, ok := panes[0].Window()
if !ok {
return errors.New("pane lost its window")
}
session, ok := window.Session()
if !ok {
return errors.New("window lost its session")
}
name, _ := session.Name()
fmt.Println("panes:", len(panes), "session:", name)
filter := tmux.TmuxFilter("#{==:#{session_name},work}")
matched, err := server.SearchPanes(ctx, &filter)
if err != nil {
return fmt.Errorf("search panes: %w", err)
}
fmt.Println("matched:", len(matched))
return nil
}
if err := run(); err != nil {
panic(err)
}
// Output:
// has work: true
// missing is not found: true
// panes: 1 session: work
// matched: 1
}

Run the saved file. Go checks the Output comment and fails on different output or an operation or cleanup error:

Terminal window
$ go test -count=1 -v example_test.go

Members110#

Collections and queries12#

  • Sessions method Sessions materializes the server's sessions. Failures, including ErrNoServer, remain errors rather than empty results.
  • Windows method Windows materializes one record per winlink. Failures, including ErrNoServer, remain errors rather than empty results.
  • Panes method Panes materializes pane records for every winlink. Failures, including ErrNoServer, remain errors rather than empty results.
  • Clients method Clients materializes attached clients. Failures, including ErrNoServer, remain errors rather than empty results.
  • ListBuffers method ListBuffers returns an owned snapshot of live tmux buffer rows. A command or transport failure is returned rather than answered with no rows; context cancellation still returns its context error. The result is not a live collection.
  • ListCommands method ListCommands returns an owned snapshot of raw tmux command-description lines. A list failure is returned rather than answered with no rows. Like Server.ListKeys, it answers on a socket holding no server.
  • ListKeys method ListKeys returns an owned snapshot of raw tmux key-binding lines. Format requires tmux 3.7 and follows UnsupportedPolicy. tmux 3.7 through 3.7c send a table's sole matching binding to client status and leave stdout empty; this method preserves that upstream and Python behavior. Listing failures remain errors.
  • ListClients method ListClients returns an owned snapshot of raw tmux client-description lines, the text tmux itself prints. A list failure is returned rather than answered with no rows. Server.Clients answers the same question as typed Client records and is what most callers want.
  • Snapshot method Snapshot materializes sessions, winlinks, panes, and clients. Its sequential commands produce an observationally consistent result, not an atomic transaction. Failures remain errors rather than empty snapshots; cancellation may occur after earlier listings completed.
  • SearchPanes method SearchPanes returns a newly materialized snapshot projection of pane views selected by tmux's live -f expression. A nil filter omits -f and a nonnil empty filter sends an explicit expression.
  • SearchSessions method SearchSessions returns a newly materialized snapshot projection of sessions selected by tmux's live -f expression. A nil filter omits -f; a nonnil empty filter remains an explicit empty expression.
  • SearchWindows method SearchWindows returns a newly materialized snapshot projection of winlinks selected by tmux's live -f expression. A nil filter omits -f and a nonnil empty filter sends an explicit expression.

Common operations51#

  • NewSession method NewSession creates a detached session, then returns a newly materialized Session. It never changes client focus. KillExisting is not rolled back; transport and context failures may be delivery-ambiguous.
  • Kill method Kill terminates the configured tmux server and all of its sessions, windows, panes, and clients. After a completed failed kill, a liveness probe makes repeated calls harmless when no daemon answers. Transport or context errors can be delivery-ambiguous; no rollback is attempted.
  • SourceFile method SourceFile loads or parses one tmux configuration file. The path expands ~ and ~/... for the current user and normalizes redundant separators and dot components without collapsing parent components. Named-user forms are rejected. Exact "-" is rejected because it requires process stdin; a relative path naming a file called "-" remains file data. It can mutate tmux configuration; completed stderr is an error, and cancellation does not prove that parsing or sourcing did not occur.
  • Options method Options returns a freshly decoded, caller-owned view of known server options, including inherited values. A read or transport failure is returned rather than answered with zero values; context errors propagate. Each returned accessor names the setter that writes it, so ServerOptionValues.BufferLimit pairs with Server.SetBufferLimit.
  • ShowBuffer method ShowBuffer returns one buffer using Python-compatible line reconstruction. The returned string is owned by the caller; nil Name selects tmux's most recent buffer. Completed stderr is an error.
  • SetBuffer method SetBuffer stores or appends exact string data without refreshing models. It mutates the selected paste buffer; completed stderr is reported as a redacted command error because Data may be secret. Cancellation does not prove that tmux did not store data.
  • DeleteBuffer method DeleteBuffer deletes a named buffer, or the most recent buffer when name is nil. Cancellation does not prove that tmux did not delete the buffer.
  • Cmd method Cmd executes raw tmux arguments and returns caller-owned result slices. A completed nonzero exit remains a result; validation and transport failures return errors. Cancellation cannot prove whether a mutation reached tmux.
  • SetOption method SetOption stores a server-scope option without refreshing existing models. It may validate a known option against the live version. Completed failures return secret-safe option errors; cancellation does not prove the mutation was not accepted by tmux.
  • ShowEnvironment method ShowEnvironment returns an owned server-global non-hidden tmux environment. Completed command failures return an empty map unless strict errors are enabled. Externally injected multiline entries return ErrMalformedEnvironment because tmux's multi-entry output does not frame continuation lines. Decode errors are compatible with ErrMalformedEnvironment and return no partial map.
  • SetEnvironment method SetEnvironment stores a value in the server's global tmux environment. ExpandFormat and Hidden select tmux flags; cancellation does not prove the value was not stored.
  • UnsetEnvironment method UnsetEnvironment deletes a value from the server's global tmux environment. Cancellation does not prove deletion did not occur.
  • WaitFor method WaitFor waits for, signals, locks, or unlocks a named tmux channel. It changes only that server-side channel state; cancellation can interrupt the client wait but cannot prove a preceding signal or lock did not take effect. See tmux.WaitForModeLock: before tmux 3.8, abandoning a lock wait costs that channel one unlock.
  • IsAlive method IsAlive reports whether a tmux server answers on the configured socket. Only an absent server reports false without an error: a socket that exists but cannot be reached, such as one the process may not read, is a question that could not be answered and is returned as an error. Use Server.CheckAlive where an absent server is itself the failure.
  • UnsetOption method UnsetOption unsets a server-scope option without refreshing existing models. UnsetPanes is invalid at server scope. Completed failures are secret-safe option errors; cancellation does not prove the unset was not accepted.
  • RunShell method RunShell executes a shell command through tmux and returns an owned stdout slice. Captured foreground shell jobs require tmux 3.5 before execution; older releases deliver that output to no client. A background request returns nil after tmux accepts the job. TargetPane delivers output to that pane on older supported daemons. AsTmuxCommand uses native tmux command semantics rather than promising captured shell-job output. Unsupported optional flags follow UnsupportedPolicy. A completed stderr result is an error; context cancellation can be observed with errors.Is but does not establish that tmux did not start the job.
  • Session method Session performs a canonical live lookup of id and returns a newly materialized record. Use Session.Refresh when beginning from a record.
  • Window method Window performs a canonical live lookup of id using tmux's canonical session and returns a newly materialized record. It does not preserve a linked-session view; use Window.ResolveSession for that exact relationship.
  • Pane method Pane performs a canonical live lookup of id using tmux's canonical session and returns a newly materialized record. It does not preserve a linked-session view; use Pane.ResolveWindow for that exact relationship.
  • RawOption method RawOption returns one exact server-scope option value. A successful string is caller-owned; ok reports presence. Targeted reads do not use list leniency, and completed failures return a secret-safe option error. An unindexed empty array is indistinguishable from an empty scalar; use Options for typed array presence.
  • LoadBuffer method LoadBuffer reads a file into a named or newly allocated buffer. Path follows Server.SourceFile's current-user expansion and lexical normalization. It mutates tmux's destination buffer. Exact "-" is rejected because it names tmux's stdin rather than a path; Server.LoadBufferFrom streams from an io.Reader, and this method is the one that runs over a Connection.
  • HasSession method HasSession reports whether Target selects a session. With Pattern false it compares session names exactly; with Pattern true, tmux may resolve IDs, client TTYs, unique prefixes, or globs. Pattern-mode completed nonzero exits are misses. Exact-name lookup treats ErrNoServer as a miss and returns other failures.
  • BindKey method BindKey binds Key to Command in a tmux key table. An empty Command creates a no-op binding. It mutates the table; cancellation does not prove that tmux did not bind Key.
  • UnbindKey method UnbindKey removes one key binding or every binding in a key table. Key and AllKeys must select exactly one target; cancellation does not prove removal did not occur.
  • Version method Version returns a materialized handle's daemon version or an unbound handle's cached executable version. Failed probes are not cached. A waiting caller can abandon an in-flight shared probe when ctx ends without canceling its owner.
  • AttachSession method AttachSession attaches the caller's terminal to a matching session and blocks until detach or context cancellation. Nil standard streams inherit the process streams; each stream must be a concrete terminal descriptor. The call retains caller-supplied files while attached and never owns or closes them. A completed nonzero exit returns CommandError; cancellation can end waiting but does not prove that attachment or detachment did not occur. On Unix, cancellation requests a tmux disconnect before bounded forced cleanup. If the daemon cannot respond, callers may need to restore their terminal state after the call returns.
  • RemoveEnvironment method RemoveEnvironment marks a variable for removal from new process environments.
  • SaveBuffer method SaveBuffer writes a named or most-recent buffer to a file. Path follows Server.SourceFile's current-user expansion and lexical normalization. It changes that file. Exact "-" is rejected because it names tmux's stdout rather than a path; Server.SaveBufferTo streams to an io.Writer, and this method is the one that runs over a Connection.
  • DetachClient method DetachClient detaches one client, or tmux's current client when no target is set. A completed stderr result is an error; cancellation does not prove delivery or detachment did not occur.
  • Start method Start starts the configured tmux server. It is idempotent when that server is already running. Completed stderr is an error; cancellation does not prove that a daemon was not started.
  • IfShell method IfShell executes ThenCommand when ShellCommand succeeds and ElseCommand, if present, when it fails. A completed stderr result is an error; cancellation can interrupt delivery without proving that tmux did not execute a branch.
  • ShowPromptHistory method ShowPromptHistory returns an owned snapshot of tmux prompt-history lines. It is available on every supported tmux. A tmux command or transport failure is returned rather than answered with no history.
  • ClearPromptHistory method ClearPromptHistory clears all tmux prompt history or one selected class. Version, transport, and completed-stderr failures are returned. It is available on every supported tmux.
  • LockServer method LockServer locks every attached client on the tmux server. Cancellation does not prove the server did not lock a client.
  • CheckAlive method CheckAlive returns a CommandError when the configured server is not alive. Cancellation and transport failures are returned directly. Use Server.IsAlive where an absent server is an answer rather than a failure.
  • ShowMessages method ShowMessages returns an owned snapshot of the tmux message log, terminal capabilities, job summary, or both terminal and job summaries. A zero TargetClient selects tmux's current client; a list failure is returned rather than answered with no rows.
  • CommandPrompt method CommandPrompt asks tmux to display a background command prompt and returns after tmux accepts it, not after input is submitted or Template runs. It is available on every supported tmux. Later flags follow UnsupportedPolicy. Completed stderr is an error; cancellation does not prove prompt delivery or later execution.
  • DisplayMessage method DisplayMessage displays or prints a server-scoped tmux message. Print returns an owned stdout slice even when tmux exits nonzero; completed stderr is delivered synchronously through tmux.WarningCommandStderr, not returned as a completed-error classification. Unsupported flags follow UnsupportedPolicy. Any warnings run on the caller goroutine before return. Cancellation does not prove display did not occur.
  • RefreshClient method RefreshClient redraws a client, or tmux's current client when no target is set. RequestClipboard requires tmux 3.6a and follows UnsupportedPolicy.
  • SwitchClient method SwitchClient switches tmux's current client to targetSession. TargetSession is a validated session name rather than a stable identity; cancellation does not prove the switch did not occur.
  • KillSession method KillSession terminates the session selected by tmux target syntax. Pattern and prefix matching are deliberately left to tmux. Completed nonzero exits without stderr are ignored. Transport and context errors are delivery-ambiguous.
  • ConfigFile method ConfigFile returns the configured tmux configuration path.
  • SocketPath method SocketPath returns the absolute socket path selected when the server was constructed. An invalid server returns an empty string.
  • GetEnvironment method GetEnvironment returns one non-hidden global environment entry. A missing or hidden variable reports ok false.
  • ConfirmBefore method ConfirmBefore asks tmux to display a background confirmation prompt and returns after tmux accepts it, not after the user answers or Command runs. It is available on every supported tmux. ConfirmKey and DefaultYes require tmux 3.4 and follow UnsupportedPolicy. Completed stderr is an error; cancellation does not prove prompt delivery or later command execution did not occur.
  • DisplayMenu method DisplayMenu displays a menu and waits until tmux closes it. The target client must own a TTY; control-mode clients cannot render menu overlays. It returns no selected value and does not establish whether an item command ran. Unsupported optional flags follow UnsupportedPolicy. Completed stderr is an error, and cancellation does not prove menu delivery or a selected command's effect.
  • DetachAllClients method DetachAllClients detaches every client except KeepClient or tmux's current client. Cancellation does not prove every client was detached.
  • LockClient method LockClient locks a client, or tmux's current client when targetClient is nil. Cancellation does not prove the target client was not locked.
  • SuspendClient method SuspendClient suspends a client, or tmux's current client when targetClient is nil. Cancellation does not prove suspension did not occur.
  • Equal method Equal reports whether both handles currently select the same socket path. It evaluates relative paths and environment-dependent named and default sockets against each handle's frozen binding.
  • GlobalSessionScope method GlobalSessionScope returns a handle that preserves s and its error policy.

Other members47#

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