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.

MoreLess about this notice

class libtmux-dotnet

Server

Represents an immutable server handle and snapshot.

Source and package
Qualified name
LibTmux.Server
Namespace
LibTmux
Package
LibTmux
Source
src/LibTmux/Server.cs
class LibTmux.Server

Description

Thread-safe: the handle is immutable once constructed and may be shared freely, including as a singleton. Every mutating call answers a new handle rather than changing this one.

A handle names the server on one socket, chosen by its ServerConnectionOptions, rather than the process behind it, so it can be opened before any server is listening. Two handles that reach the same endpoint are equal (Equals()) and hash alike (GetHashCode()). Letting go of a handle never stops the server; disposing an OwnedServerScope does.

What is on here

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

Connecting
Open a handle without running tmux, then connect it to find the server already listening; connecting never starts one. Take the server this process is already inside, or start one and own it, so that disposing the scope stops it. A connected handle is bound to the server it found, so after tmux restarts its sessions, windows, and panes throw StaleServerGenerationException rather than reach the new one.
Inside tmux
Timeout
Checking the server
Ask whether a server is answering, or have the call throw when none is. Inspecting reads the live server without running InitializeAsync, and answers null when none is listening. Starting the daemon returns no handle, because with tmux's exit-empty default a server holding no sessions exits as soon as it starts.
Finding one thing
Read one session, window, or pane by its identifier. The Get methods throw TmuxObjectNotFoundException when it is absent; the Find methods answer null instead, but only after a read that succeeded. Ask by name whether a session exists, or find a client by name.
Listing everything
Read every session, window, pane, or client on the server. Each throws when the listing fails, so an outage never reads as an empty server. A capture reads one listing per level, down to the depth asked for, and answers a new handle whose relations then answer without another command; clients are not part of a capture.
Querying things and getting around
Searching hands tmux an UnsafeTmuxFilter, so rows it rejects never become objects; a malformed filter returns no rows rather than an error, and searching clients needs tmux 3.4. To filter what has already been read, give the Matching extension in QueryExtensions a C# predicate; the same class translates a predicate into a portable document and plans it for tmux to evaluate. Moving between levels of a capture never reaches tmux, and a relation the capture did not read throws IncompleteSnapshotException rather than reading as empty.
Translate and plan
Changing things
Create a session, with the identifiers of its first window and pane in the receipt form, or inside a scope that stops it when disposed. Creating a session under a name already taken throws TmuxSessionExistsException. Stopping the server counts one that is already gone as success; windows and panes change through Session, Window, and Pane.
Options and hooks
The server's options, its global hooks, and the environment new sessions inherit are objects of their own: TmuxOptions, TmuxHooks, and TmuxEnvironment. Server options belong to the daemon rather than to anything inside it, so nothing is targeted. tmux has no server hook table, so the global one serves as the server's.
Everything else tmux keeps
Cancelling a shell command stops the call from waiting, not the command from running. Prefer an open wait channel to a plain wait whenever the wait has a deadline, because cancelling a plain wait leaves its queue entry in tmux before 3.8, and that entry takes the next signal. A layout check at parse time never contacts tmux; the check against a server also catches names that only some tmux versions accept.
Buffers and keys
Configuration
Things that need a terminal
Menus, command prompts, and confirmations draw on an attached client, and switching the caller's own client acts on one; tmux refuses all four when none is attached. Attaching makes the client instead, so it needs a terminal of its own. The other client commands take the name of a client, which the client listing returns.
Raw commands
Anything tmux can do that is not here runs as a raw command, one at a time with its result handed back, or several chained into one tmux invocation. A process the library cannot dispatch itself, such as an interactive attach, takes the endpoint arguments to select the endpoint and a guarded command line that runs only while the server generation is still current.

Examples

Distinguish an endpoint handle from a discovered server. Connection discovery returns an immutable replacement without capturing child relations. Use Linux or macOS with tmux 3.3a or newer, the .NET 10 SDK or newer, and the .NET 8 and 10 runtimes. In an empty directory, save this project as Example.csproj. It references the 0.1.1 release of LibTmux on NuGet: View source

Example.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>net8.0;net10.0</TargetFrameworks>
<LangVersion>12.0</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AnalysisLevel>10-recommended</AnalysisLevel>
</PropertyGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<PackageReference Include="LibTmux" Version="[0.1.1]" />
</ItemGroup>
</Project>

Save this complete program as Program.cs. It creates a private server; await using disposes its owned scopes after success, cancellation or failure. The complete file contains explicit imports, a top-level async entry point and a cancellation deadline. View source

Program.csComplete program
using System;
using System.IO;
using System.Threading;
using LibTmux;
if (OperatingSystem.IsWindows())
{
throw new PlatformNotSupportedException("This example requires tmux on Linux or macOS.");
}
using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(10));
CancellationToken token = deadline.Token;
string? testTmux = Environment.GetEnvironmentVariable("LIBTMUX_TEST_TMUX");
string? configured = !string.IsNullOrWhiteSpace(testTmux)
? testTmux
: Environment.GetEnvironmentVariable("LIBTMUX_TMUX");
string binary = string.IsNullOrWhiteSpace(configured) ? "tmux" : configured;
using TemporaryDirectory socketRoot = new();
ServerConnectionOptions options = new()
{
SocketPath = Path.Combine(socketRoot.FullName, "tmux.sock"),
ConfigurationFile = "/dev/null",
TmuxBinaryPath = binary,
};
// Open records the endpoint without running tmux or reading its state.
Server endpoint = Server.Open(options);
if (endpoint.IsMaterialized)
{
throw new InvalidOperationException("Open must not discover a server.");
}
await using OwnedServerScope owned = await Server.CreateOwnedAsync(options, token);
await using OwnedSessionScope session = await owned.Value.CreateOwnedSessionAsync(
new NewSessionRequest { Name = "demo", Command = "/bin/cat" }, token);
// Connect discovers the live daemon and returns a new materialized handle.
Server connected = await endpoint.ConnectAsync(token);
Server sameEndpoint = await Server.ConnectAsync(options, token);
if (!connected.IsMaterialized || !sameEndpoint.IsMaterialized || endpoint.IsMaterialized)
{
throw new InvalidOperationException("Connecting must leave the original handle unchanged.");
}
if (connected.Generation != sameEndpoint.Generation || connected.Sessions.IsCaptured)
{
throw new InvalidOperationException("Connection discovery must not capture the hierarchy.");
}
Console.WriteLine("Open records an endpoint; Connect discovers the running server.");
Console.WriteLine("The original handle stays unmaterialized; relations remain uncaptured.");
internal sealed class TemporaryDirectory : IDisposable
{
private readonly DirectoryInfo _directory = Directory.CreateTempSubdirectory("libtmux-example-");
public string FullName => _directory.FullName;
public void Dispose() => _directory.Delete(recursive: true);
}

Build the project and run both supported frameworks. Each program checks its result and exits unsuccessfully after an unhandled error:

Terminal window
$ dotnet build Example.csproj --configuration Release && \
dotnet bin/Release/net8.0/Example.dll && \
dotnet bin/Release/net10.0/Example.dll

Expected program output from each framework:

Open records an endpoint; Connect discovers the running server.
The original handle stays unmaterialized; relations remain uncaptured.

Properties16

Server properties
NameTypeDescription
Sessions CapturedRelation<Session> Gets the sessions this handle captured.
Windows CapturedRelation<Window> Gets the windows this handle captured, across every session.
Panes CapturedRelation<Pane> Gets the panes this handle captured, across every window.
Clients CapturedRelation<Client> Gets the clients this handle captured.
Buffers TmuxBuffers Gets the paste buffers of this server.
Hooks TmuxHooks Gets the hooks of this server.
Options TmuxOptions Gets the options of this server.
Environment TmuxEnvironment Gets the environment new sessions inherit from.
Version TmuxVersion? Gets the tmux version this handle was checked on.
ConnectionOptions ServerConnectionOptions Gets the connection options.
DaemonVersion TmuxVersion? Gets the daemon version read by inspection, or null when it was not acquired.
EndpointArguments IReadOnlyList<string> Gets the endpoint selection arguments -- -L, -S, or a configuration file flag -- this handle's connection resolved.
Generation ServerGeneration? Gets the materialized server generation.
IsMaterialized bool Gets whether this handle has discovered a live server.
Keys TmuxKeys Gets the key bindings of this server.
SnapshotMetadata SnapshotMetadata? Gets acquisition metadata, or null when this handle was not captured.

Members61 members

Collections and queries9

Common operations38

Other members14

Order: the accessors that walk the hierarchy, the operations the ports share, then the rest.

Guides

task material

Pages that discuss Server.

In other ports

task equivalence 22 other ports mapped

Source-verified mappings for A tmux server. A mapping says these APIs perform the same task. It does not say they share defaults, errors or completion: check each page.

A tmux server in each port
PortAPIDiffers from C#
C# LibTmux.Server
Represents an immutable server handle and snapshot.
This page
Python libtmux.Server
tmux(1) Server [server_manual].
None recorded in the model
Ruby LibTmux::Server
Connects to an existing endpoint. Closing retires clients, never the daemon.
None recorded in the model
Lua libtmux.Server None recorded in the model
PowerShell LibTmux\New-TmuxServer
Construct a tmux endpoint handle without contacting it.
2 overloads
This cmdlet constructs a shared .NET LibTmux.Server handle without contacting tmux.
Julia LibTmux.Server
Describe a tmux endpoint without contacting it. Supply exactly one socket selector. A description does not own a daemon or any sessions. Use from_env to opt into the ambient tmux endpoint.
Server describes an endpoint without contacting tmux. Read its hierarchy with snapshot.
Erlang tmux_server
Open tmux endpoints and execute explicit command values.
open/1 observes an existing daemon and starts an endpoint owner. Domain rows remain immutable values.
Elixir LibTmux.Server
An explicit local tmux server descriptor.
Server describes an existing server by executable and socket. It neither connects nor reserves the server’s identity.
Haskell LibTmux.Server
Start, observe and change a tmux daemon through a scoped handle.
LibTmux.Server owns the Server handle. withOwnedServer starts and retires a private daemon; withServer borrows an existing endpoint and releases its own resources afterwards. killServer retires the admitted daemon generation explicitly. Operations such as capture and renameSession are functions of this module that take the handle.
Common Lisp libtmux:client
A connection scope with one external-operation lease. Closing cancels owned work and leaves the tmux daemon alive. Captured data may outlive the client. Public operations never expose its mutable storage.
client is a connection scope with one external-operation lease. Closing it cancels owned work and leaves the tmux daemon alive; daemon owns a daemon the library started.
TypeScript server.Server
One tmux server, addressed by the socket it listens on.
None recorded in the model
Rust server.Server
A cloneable handle to one captured tmux server endpoint.
None recorded in the model
Go tmux.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).
None recorded in the model
Java io.github.libtmux.Server
Manages sessions, windows, and panes on a tmux server.
readonly
Clojure libtmux.core/open!
Opens local resources for an explicit :socket-path or :socket-name endpoint.
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
Manages sessions, windows, and panes on a tmux server.
None recorded in the model
Scala io.github.libtmux.scaladsl.Server
The Java client, opaque: every member beyond java.lang.AutoCloseable#close is an extension, generated from the operation catalog or handwritten where the catalog marks it WAIT, STREAM or LIFECYCLE. Closing an owned client releases its transport, not tmux; close() comes from the AutoCloseable bound with no forwarding of its own, so Using.resource(server) { ... } works.
2 overloads
F# LibTmux.FSharp.Server
Starts server reads and queries with the caller's cancellation token.
This F# module provides functions over the shared .NET LibTmux.Server type.
C++ libtmux::Server
One tmux server, addressed by the socket it listens on.
None recorded in the model
Swift Server
A tmux server, addressed by its endpoint.
None recorded in the model
OCaml Libtmux_unix.Client
An explicit generation-bound connection. Applications retain ownership of the endpoint choice and resource lifetime.
A client is a live, generation-bound server connection. Endpoint describes a socket without connecting; closing a client releases its resources.
Perl LibTmux::Server
Explicit tmux acquisition and commands
Construction records connection settings without tmux I/O. Optional LibTmux::Async::Server returns standard Future results for operations.
Raku LibTmux::Server None recorded in the model
Esc
Search in

Type to search.

Reference previewOpen reference