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

Server

A tmux server, addressed by its endpoint.

Source and package
Qualified name
Server
Package
libtmux-swift
Source
Sources/LibTmux/Server.swift
Other languages
Perlclass Erlangmodule PowerShellcmdlet Juliastruct Elixirstruct Haskell Common Lisp PythonRubyLuaTypeScriptRustGoJavaC#C++KotlinScalaOCamltypealias F#module Clojurefunction
struct Server : struct Server

Description#

Server is 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 unless LIBTMUX_SOCKET or LIBTMUX_SOCKET_PATH names one. What a call returns — a Session, Window, Pane, or Client — 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 a TmuxMode sends 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.
What was addressed
How commands reach it
Is anything listening
Require a listening server
Start the daemon
Read the tmux binary's version
Identify the running daemon
Run a scope in a mode
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 answers nil once the object has gone. If the daemon was replaced and the ID names something in the new one, it throws TmuxError.serverRestarted instead, because tmux numbers IDs from zero again.
By name or ID, without returning it
Re-read a value you hold
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 one Snapshot and throws TmuxError.serverRestarted if 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 throw FilteredListingError, 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, and FilterSelectionError tells no match from several. To move between levels without another tmux command, ask a Snapshot. Selecting the sessions where some, every, or no pane matches takes a RelationQuantifier, and panes can be selected by a filter on their session. A Pane carries its window ID and a Client its session ID, so a value you hold leads back up.
Go down a level
Sessions by their panes
Panes by their session
Back up from a value you hold
Changing things
Creating returns what was made: creating a session returns the Session, creating a window returns a WindowAppearance, and a split returns the new Pane. 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 name
Destroy one object
Stop the daemon
Rename a session or a window
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 layout
Cycle through the presets
Check layout strings first
Set a pane's size
Move one boundary of a pane
Zoom a pane
Move panes through the layout
Exchange two windows or two panes
Move a pane into a window of its own
Move a pane into another window
Move a window between sessions
Show a window in a second session
Remove one appearance of a window
Options and hooks
An OptionScope names 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 answers nil when 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 a HookScope. The environment, global or one session's through an EnvironmentScope, 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's TmuxReply, so a name tmux refuses is in the reply rather than thrown.
List a table
Read one value
Read the effective value
List the bound hooks
Bind a command to a hook
Unbind a hook
Run a hook's commands now
Remove 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 throws TmuxError.serverRestarted if the server went away while it waited.
List and read paste buffers
Set a buffer
Delete a buffer
Paste a buffer
Format for the server
Format for an object you hold
Format for an ID as a string
Load a configuration file
Wait for a channel
Signal a channel
Talking to a pane
Send keys as characters rather than key names when literally is 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 a CaptureCursor returns 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.
Type a command line
Spell a tmux for a command in a pane
Read the visible rows
Keep the newest and report the drop
Read since a cursor
Copy output to a shell command
Enter copy mode
Clear every mode
Clear the scrollback
Set 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
Run several in one invocation

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.2
import PackageDescription
let 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 Sources directory and save this complete program as Sources/Example.swift. The withTmuxServer fixture owns a private tmux server and stops it after success or failure. Ordinary application code uses Server for its own socket; these examples use the fixture until their setup moves to ordinary server objects. View source

import Foundation
import LibTmux
import TmuxFixture
@main
struct ApiServer {
static func main() async {
do {
try await withTmuxServer { @Sendable fixture in
guard 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_BIN to an absolute executable path to select a tmux version:

Terminal window
$ swift run ApiExample

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

Other members31#

Inherited members1 member#

Reached through Equatable.!=(_:_:).

  • !=(_:_:) function inherited Returns a Boolean value indicating whether two values are not equal.

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