Server
A tmux server, addressed by its endpoint.
Source and package
-
Description#
Serveris a value: copying one is free, copies compare equal, and passing one across a task boundary needs no ceremony. The mutable part — the process boundary and anything cached about the running daemon — lives behind an actor that every copy shares, so two copies of the same server coordinate with each other rather than racing.Addressing a server does not start it. Every command carries the endpoint you gave, so no call reaches a server you did not name. Name none, with
Server.init(tmuxExecutable:configurationFile:environment:), and tmux picks the server itself unlessLIBTMUX_SOCKETorLIBTMUX_SOCKET_PATHnames one. What a call returns — aSession,Window,Pane, orClient— is a value as it stood when tmux was asked, and it carries no operations: to act on one, pass it to a method here. A method that changes what a value names refuses the value, rather than acting on whatever tmux has since given that ID, if it came from another server (TmuxError.foreignServerValue) or from a daemon that has been replaced (TmuxError.serverRestarted), or if its ID no longer names the object it described (TmuxError.staleServerValue). The last two are checked inside the tmux command that acts.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
- The initializers address a server without starting it. A program running inside tmux finds its server through its
TmuxContext, and a discovery call lists the servers already running. The running check answers whether anything is listening, the required form throws when nothing is, and a third call starts the daemon. The version call reads the tmux binary's version, so it answers before any daemon exists, while the incarnation and the process ID identify the daemon that is running. Running a scope in aTmuxModesends each command either to a process of its own or over one control-mode connection, and two calls open that connection and hand it to you. - Address a server without starting itWhat was addressedHow commands reach itFrom inside tmuxServers already runningIs anything listeningRequire a listening serverStart the daemonRead the tmux binary's versionIdentify the running daemonRun a scope in a modeOpen the connection
- Finding one thing
- Look up a session, window or pane by ID, or a session or windows by name. Each lookup answers
nil, or an empty array for the plural, when tmux does not have it, and throws when the server cannot answer. Window names are not unique, which is why the lookup by window name returns an array. A session can be checked for by name or ID without returning it, and a value you hold can be refreshed. A refresh answersnilonce the object has gone. If the daemon was replaced and the ID names something in the new one, it throwsTmuxError.serverRestartedinstead, because tmux numbers IDs from zero again. - By nameBy name or ID, without returning it
- Listing everything
- Each call reads one tmux listing. A failed listing throws rather than reading as an empty server; use
Server.isRunning()when absence is an expected answer. A window linked into several sessions appears once in the window listing and once per session in the window-link listing. Taking a snapshot reads every listing as oneSnapshotand throwsTmuxError.serverRestartedif a different daemon bound the socket in between. It is not a transaction: another client can still change the same daemon between the listings. - Every listing as one snapshot
- Querying things and getting around
- Each filtered listing takes a
FilterExpr. tmux evaluates as much of it as its format language can express before the rows cross the process boundary, and the rest is applied here, so the answer is the one filtering the full listing would give; the filtered client listing applies all of it here. Filtered listings throwFilteredListingError, which keeps a tmux failure apart from a regular expression that ran out of budget.exactlyOne(_:)takes the one element a filter matches from any listing, andFilterSelectionErrortells no match from several. To move between levels without another tmux command, ask aSnapshot. Selecting the sessions where some, every, or no pane matches takes aRelationQuantifier, and panes can be selected by a filter on their session. APanecarries its window ID and aClientits session ID, so a value you hold leads back up. - Filter a listingGo down a level
Snapshot.windows(of:)Snapshot/panes(of:)-(Window)Snapshot/panes(of:)-(Session)
Go up a levelSessions by their panesPanes by their sessionBack up from a value you hold - Changing things
- Creating returns what was made: creating a session returns the
Session, creating a window returns aWindowAppearance, and a split returns the newPane. A split divides a window's active pane or the pane you name. Killing destroys one object, killing the server stops the daemon, and renaming changes the name of a session or a window. Selecting chooses what is active. - New window next to a window you nameSplit a window's active paneSplit the pane you nameStop the daemonRename a session or a windowChoose what is active
- Arranging windows and panes
- Apply a layout, cycle through tmux's presets, or check layout strings before anything changes. Set a pane's size, move one of its boundaries, or zoom it. Rotate the panes of a window through its layout, and exchange two windows or two panes. Move a pane into a window of its own or into another window. Move a window between sessions, show it in a second one, or remove one of its appearances. Restart what a pane or a window runs.
- Apply a layoutCycle through the presetsCheck layout strings firstSet a pane's sizeMove one boundary of a paneZoom a paneMove panes through the layoutExchange two windows or two panes
Server/swap(_:with:)-(WindowLink,WindowLink)Server/swap(_:with:)-(Pane,Pane)
Move a pane into a window of its ownMove a pane into another windowMove a window between sessionsShow a window in a second sessionRemove one appearance of a windowRestart what a pane or a window runs - Options and hooks
- An
OptionScopenames the exact table: the server's, the global session or window table, or one session, window, or pane. Listing a table shows what has been set in it, not tmux's built-in defaults. Reading one value there answersnilwhen it is not set, and the resolved read gives the effective value after tmux resolves inheritance. Hooks live in the global table or in one session's, chosen by aHookScope. The environment, global or one session's through anEnvironmentScope, can be read whole or by variable; removing a variable marks it so that new processes start without it. Writing an option, a hook or an environment variable hands back tmux'sTmuxReply, so a name tmux refuses is in the reply rather than thrown. - List a tableRead one valueRead the effective valueWrite an optionList the bound hooksBind a command to a hookUnbind a hookRun a hook's commands nowRead the environmentWrite the environmentRemove a variable for new processes
- Everything else tmux keeps
- Paste buffers can be listed, read, set, loaded, saved, deleted and pasted; the load and save pair have tmux read or write the file itself, which avoids the argument-size limit of
Server.setBuffer(_:named:)and, on a connected server, its refusal of newlines. Format expansion reaches any field the library does not model, for the server, for an object you hold, or for an ID that arrived as a string. Load a configuration file into the running server. A wait blocks until something signals the channel, and throwsTmuxError.serverRestartedif the server went away while it waited. - List and read paste buffersSet a bufferThrough a fileDelete a bufferPaste a bufferFormat for the serverFormat for an object you hold
Server/format(_:for:)-(String,Session)Server/format(_:for:)-(String,WindowLink)format(_:for:through:)
Format for an ID as a stringLoad a configuration fileWait for a channelSignal a channel - Talking to a pane
- Send keys as characters rather than key names when
literallyis set, and type a command line followed by Enter. A shell invocation spells a tmux that reaches this server for a command running inside a pane. A capture reads the visible rows, and the scrollback too on request; a capture with a line limit keeps the newest and reports how many it dropped, and a ranged capture reads a range of them. A capture since aCaptureCursorreturns only what has been printed since it, and waiting for output ends once a pane prints something that matches. Copy a pane's output to a shell command, enter copy mode, clear every mode, clear its scrollback, and set its title. - Send keysType a command lineSpell a tmux for a command in a paneRead the visible rowsKeep the newest and report the dropRead since a cursorWait for matching outputCopy output to a shell commandEnter copy modeClear every modeClear the scrollbackSet the title
- Things that need a terminal
- None. Menus, popups, prompts, and key bindings need an attached client to mean anything, so this type leaves them out. Detaching acts on clients the server already holds and needs no terminal of its own, and a connected scope attaches a control-mode client, which talks over pipes rather than a terminal.
- Attach a control-mode client
- Running a command
- Anything tmux can do that is not here is reachable by running a tmux command. One call runs a single command and another runs several in one invocation. Both hand back a
TmuxReply: a nonzero status is a reply, not an error. - Run one command
Server/run(_:)-(TmuxCommand)
Run several in one invocationServer/run(_:)-(TmuxCommandList)
Examples#
Address an existing server by socket. Construct a Server for the fixture's socket and list its sessions. Server is a value that addresses a tmux daemon; constructing it does not start or stop that daemon. Use Swift 6.2 or newer and tmux 3.3a or newer on Linux or macOS. In an empty directory, save this consumer package as
Package.swift; SwiftPM fetches the library from release 0.1.1:// swift-tools-version: 6.2import PackageDescriptionlet package = Package(name: "ApiExample",platforms: [.macOS(.v13)],dependencies: [.package(url: "https://github.com/libtmux/libtmux-swift.git", from: "0.1.1")],targets: [.executableTarget(name: "ApiExample",dependencies: [.product(name: "LibTmux", package: "libtmux-swift"),.product(name: "TmuxFixture", package: "libtmux-swift"),],path: "Sources")])Create a
Sourcesdirectory and save this complete program asSources/Example.swift. ThewithTmuxServerfixture owns a private tmux server and stops it after success or failure. Ordinary application code usesServerfor its own socket; these examples use the fixture until their setup moves to ordinary server objects. View sourceimport Foundationimport LibTmuximport TmuxFixture@mainstruct ApiServer {static func main() async {do {try await withTmuxServer { @Sendable fixture inguard case let .socketPath(path) = fixture.endpoint else {throw ExampleError.expectedSocketPath}let server = try Server(socketPath: path,tmuxExecutable: fixture.tmuxExecutable,configurationFile: "/dev/null")let names = try await server.sessions().map(\.name).sorted()print("Sessions: \(names.joined(separator: ", "))")}} catch {FileHandle.standardError.write(Data("Example failed: \(error)\n".utf8))exit(EXIT_FAILURE)}}enum ExampleError: Error {case expectedSocketPath}}Build and run the saved program. An operation or cleanup error produces a failing exit status. Set
LIBTMUX_TMUX_BINto an absolute executable path to select a tmux version:Terminal window $ swift run ApiExampleExpected output:
Sessions: bootstrap
Members107#
Collections and queries11#
- sessions() method Every session on this server, in tmux's own order.
- windows() method Every window on this server, in tmux's own order.
- panes() method Every pane on this server, in tmux's own order. A pane whose window has several session links appears once.
- clients() method Every client attached to this server.
- buffers() method The server's paste buffers, most recent first.
- sessions(where:) method Sessions matching
expression. - windows(named:) method Every window with this name, in tmux's own order.
- windows(where:) method Windows matching
expression. - panes(where:) method Panes matching
expression. - clients(where:) method Clients matching
expression. - snapshot() method Reads every object from one daemon incarnation.
Common operations65#
- capture(_:includingHistory:) method The pane's visible contents, one line per row. The source read is capped at 1 MiB; use incremental capture for a large scrollback instead of collecting its entire history.
- sendKeys(_:to:literally:) method Sends keys to a pane.
- newSession(named:startDirectory:windowName:width:height:environment:shell:) method Creates a detached session.
- newWindow(in:named:startDirectory:at:environment:shell:) method Creates a window in a session and returns its exact appearance.
- split(_:direction:size:startDirectory:environment:shell:) method Splits one pane, returning the pane that appeared.
- killServer() method
- selectLayout(_:_:) method Applies a named layout, unique abbreviation or checksummed saved layout, or a JSON layout document on tmux 3.8 and later. Invalid syntax is refused before dispatch; tmux validates geometry.
- kill(_:) method
- rename(_:to:) method
- link(_:into:) method Links a window into another session. The same window then appears in both, sharing one id — which is tmux's model, not a copy. The source is global because no existing session-local appearance is involved.
- respawn(_:running:killingExisting:) method
- unlink(_:) method Removes one of a linked window's appearances. The window survives while any session still holds it.
- select(_:) method
- resize(_:width:height:) method Sets a pane's size outright.
- hooks(_:) method Hooks tmux has a command for.
- move(_:to:at:) method Moves one window appearance into another session.
- breakPane(_:from:named:) method Moves a pane out into a window of its own, and returns its appearance.
- splitWindow(_:direction:size:startDirectory:environment:shell:) method Splits a window's active pane, returning the pane that appeared.
- setTitle(_:of:) method Sets a pane's title. The title is only shown when tmux is configured to display it, but it is always readable through a format.
- clearHistory(_:) method Clears a pane's scrollback; the visible screen stays as it is.
- paste(buffer:into:) method Pastes a buffer into a pane.
- sourceFile(_:) method Loads a tmux configuration file into the running server.
- options(_:) method Every option set in one exact table.
- buffer(named:) method Reads a buffer's contents, or
nilif no such buffer exists. - setBuffer(_:named:) method Puts text into a named buffer.
- deleteBuffer(named:) method
- join(_:into:direction:size:) method Moves a pane into another window, splitting it.
- pipe(_:to:) method Copies everything a pane outputs to a shell command, or stops doing so when
commandis omitted. - rotate(_:upward:) method Shifts every pane in a window one position around the layout.
- setOption(_:to:scope:) method Sets an option.
- unsetOption(_:scope:) method Puts an option back the way it was before anyone set it.
- setHook(_:to:at:in:) method Binds a command to a hook.
- environment(_:) method Every variable in an environment, in the order tmux printed them.
- setEnvironment(_:to:in:) method Sets a variable, replacing whatever was there.
- unsetEnvironment(_:in:) method Unsets a variable, leaving no trace of it.
- wait(for:) method Blocks until something signals
channel. - swap(_:with:) method Swaps two window appearances. Their underlying window ids do not change, but both links move to new indices.
- isRunning() method Whether a server is listening on this endpoint.
- option(_:scope:) method The value of one option, or
nilif it is not set in that table. - nextLayout(_:) method Cycles a window through tmux's preset layouts.
- detachClients(from:) method Detaches every client attached to a session.
- unsetHook(_:in:) method Unbinds every command from a hook.
- loadBuffer(from:named:) method Fills a buffer from a file, letting tmux read it.
- hasSession(_:) method Whether a session by this name or id exists.
- version() method Which tmux executable this server runs.
- previousLayout(_:) method
- selectNextWindow(in:) method Moves to the next window of a session, wrapping at the end.
- selectPreviousWindow(in:) method
- selectLastWindow(in:) method Returns to the window that was active before the current one.
- removeEnvironment(_:in:) method Marks a variable so new processes start without it, even when it is set in the environment tmux itself was started from.
- saveBuffer(named:to:) method Writes a buffer to a file, letting tmux do the writing.
- detach(_:) method Detaches a client from the server it is attached to.
- startServer() method Starts the server if it is not already running.
- selectLastPane(in:) method Returns to the pane that was active before the current one.
- runHook(_:in:) method Runs a hook's commands now, without waiting for what would trigger it.
- connected(attachingTo:_:) method Runs
bodywith every command carried by one live connection instead of a new tmux process each time. - run(_:in:) method Runs a shell command line in a pane, as if typed.
- signal(_:) method Releases one waiter on
channel. - waitForOutput(in:matching:stoppingAt:requiringFreshOutput:startingAt:timeout:tailLimit:) method Waits until a pane prints something, driven by tmux output events.
- format(_:for:) method Evaluates a tmux format and hands back what it printed.
- init(socketPath:tmuxExecutable:configurationFile:) method
- init(tmuxExecutable:configurationFile:environment:) method A server on the socket the environment names, else on the one tmux picks.
- session(_:) method The session with this id, or
nilif the server has no such session. - shellInvocation: var shell
Invocation : String property How a command running inside a pane spells a tmux that reaches this server. - using(_:_:) method Runs
bodywith this server inmode.
Other members31#
- ==(_:_:) function Returns a Boolean value indicating whether two values are equal.
- cancelModes(in:) method Idempotently clears the entire mode stack of a pane.
- capture(_:includingHistory:maximumLines:) method Reads the newest rows without collecting older rows that will be discarded.
- capture(_:since:limit:) method Reads only what a pane has printed since
cursor. - captureRange(_:startingAt:endingAt:joiningWrappedLines:maximumLines:) method Reads a bounded tmux capture range using tmux's relative row numbering.
- endpoint: let endpoint: Endpoint property Where this server listens. Every command carries it, so a call reaches the server you named, and the one tmux picks only when this is
Endpoint.tmuxChoice. - enterCopyMode(_:) method Enters copy mode in a pane.
- environmentValue(_:in:) method What one variable is set to, or
nilwhen it is unset or marked for removal. - format(_:) method Evaluates a tmux format against the server rather than any one object.
- format(_:addressing:) method Evaluates a tmux format against a target named by id.
- format(_:for:through:) method Evaluates a tmux format against a pane through one of its window links. See
format(_:for:)-(String,Session). - hash(into:) method Hashes the essential components of this value by feeding them into the given hasher.
- incarnation() method The running daemon at this endpoint.
- init(socketName:tmuxExecutable:configurationFile:) method
- mode: var mode: Tmux
Mode property How work from this server reaches tmux. - newWindow(_:_:named:startDirectory:) method Creates a window next to one that already exists and returns its exact appearance.
- pane(_:) method The pane with this id, or
nilif the server has no such pane. - refresh(_:) method This session as it is now, or
nilif it has gone away. - requireRunning() method Throws unless a server is listening.
- resize(_:by:toward:) method Nudges a pane's boundary, leaving the rest of the layout to absorb it.
- resolvedOption(_:scope:) method The effective value after tmux resolves inherited option tables.
- respawn(_:running:killingExisting:startDirectory:) method Restarts the command in a pane.
- run(_:) method Runs a list of commands in one tmux invocation.
- serverProcessID() method The running server's process id.
- session(named:) method The session with this name, or
nilif no session has it. - tmuxExecutable: var tmux
Executable : String property The tmux this server runs, resolved to a path. - toggleZoom(_:) method Toggles whether one pane fills its window.
- validateLayouts(_:) method Checks layouts and their required pane counts before changing tmux.
- window(_:) method The window with this id, or
nilif the server has no such window. - windowLinks() method Every session-local link to a window, in tmux's own order.
- withControlMode(attachingTo:_:) method Opens a control-mode connection for the duration of
body, handing over the connection itself.
Inherited members1 member#
Reached through Equatable.!=(_:_:).
Guides#
Pages that discuss Server.
- Concepts
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 |
| Rust | 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:: |
| 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.