Getting started
Needs libtmux for Kotlin 0.x Install
Coroutine wrapper classes, a session/window/split DSL, and Flow/StateFlow
bridges over the Java API.
Drive tmux from Kotlin: withServer opens a server and closes
it, the newSession DSL declares a session with its
windows and splits, and Pane.run runs a command to its exit status.
Wrapper reads and mutations that reach tmux are suspend.
Server.channel returns Java’s Channel; its signal()
and drain() calls block the caller. Closing a wrapper is synchronous too.
io.github.libtmux:libtmux-kotlin — on Maven
Central.
API reference: libtmux.org for the current trunk,
javadoc.io for a
released version.
Releases are numbered
0.1.N, and each release incrementsN. The API is not settled: any release may change or remove exported identifiers, and the changelog marks each break. Pin an exact version to avoid one.
Contents — Quick start · Declare a session · Send keys · Query · Handle failures · Watch tmux · Leaves out · Support
Quick start
Add it through the BOM, which names one version for every module:
dependencies { implementation(platform("io.github.libtmux:libtmux-bom:0.1.2")) implementation("io.github.libtmux:libtmux-kotlin")}withServer: open a server, close it however the block ends
Server, Session, Window, Pane,
Client and ControlClient here are Kotlin classes
over the matching Java handle. withServer closes the server even if the block
throws or is cancelled:
import io.github.libtmux.kotlin.withServer
// Given: config: ServerConfigwithServer(config) { server -> val session = server.newSession("build")
session.name // → build server.admissionBound > 0 // → true}- Each class answers its Java handle as
asJava, andServer.fromJavawraps a server opened in Java. - Captured state is a plain property.
- A subsystem an accessor answers, such as
Pane.options(),Server.hooks()andServer.keys(), is wrapped the same way, so calling into it never blocks the caller’s thread outsideExecutionPolicy.
Declare a session, its windows, and their splits
Server.newSession: the DSL
SessionBuilder, WindowBuilder and
SplitBuilder nest, so the code reads like the layout:
import io.github.libtmux.kotlin.withServer
// Given: config: ServerConfigwithServer(config) { server -> val session = server.newSession { name = "editors" window { name = "left" } window { name = "right" split { toRight(); percent(30) } } }
session.windows.size // → 2}@DslMarkerkeeps a nested block from reaching an outer block’s receiver by accident. Asplit { }inside awindow { }cannot set the session’sdirectorywithout writingthis@newSession.directory.- tmux always gives a new session one window. The first
window { }block renames it, and each later block is a new window, so two blocks make two windows, not three.
Send keys, capture output, and run a command
Pane.run: a command to its exit status
Pane types a line, waits for text, captures the screen, and runs a
command to its end. orNull turns the exit status’s OptionalInt
into a Kotlin nullable:
import io.github.libtmux.kotlin.orNullimport io.github.libtmux.kotlin.withServerimport kotlin.time.Duration.Companion.seconds
// Given: config: ServerConfigwithServer(config) { server -> val session = server.newSession("keys-demo") val pane = session.activeWindow?.activePane ?: error("no active pane")
pane.sendLine("echo ready") pane.awaitText("ready", timeout = 5.seconds) val lines = pane.capture()
val run = pane.run("echo hi && exit 3", timeout = 5.seconds) run.exitStatus.orNull() // → 3 lines.isNotEmpty() // → true}Query with typed fields
Pane.command: fields live on the companion
Fields live on the handle type’s companion: Pane.command, where Java has the
static Pane_.command(). They are generated from the same field-catalog.tsv
that generates the Java metamodel, so the two cannot disagree:
import io.github.libtmux.kotlin.Paneimport io.github.libtmux.kotlin.query.activeimport io.github.libtmux.kotlin.query.commandimport io.github.libtmux.kotlin.withServer
// Given: config: ServerConfigwithServer(config) { server -> server.newSession("query-demo") val editors = server.panes(Pane.command startsWith "nvim") val activePanes = server.panes(Pane.active.isTrue())
editors.size >= 0 // → true activePanes.isNotEmpty() // → true}server.session(expr)throwsCardinalityExceptionon no match or more than one.server.sessionOrNull(expr)is null on no match and still throws on more than one. That is Kotlin’s collection convention (singleandsingleOrNull), applied to a tmux lookup.FlagField.isTrueand the text operators build the expression.
Handle failures
LibTmuxException: an exhaustive when
Every failure the library raises is one sealed tree, so a when over it needs
no else:
import io.github.libtmux.exception.CardinalityExceptionimport io.github.libtmux.exception.CommandRejectedExceptionimport io.github.libtmux.exception.ControlEndedExceptionimport io.github.libtmux.exception.DispatchExceptionimport io.github.libtmux.exception.LibTmuxExceptionimport io.github.libtmux.exception.MalformedResponseExceptionimport io.github.libtmux.exception.ServerUnavailableExceptionimport io.github.libtmux.exception.TargetGoneExceptionimport io.github.libtmux.exception.UnencodableTextExceptionimport io.github.libtmux.exception.UnsupportedFeatureException
fun nextStep(failure: LibTmuxException): String = when (failure) { // exhaustive, no else is TargetGoneException -> "look it up again" is ServerUnavailableException -> "start a server" is CommandRejectedException -> "change the request" is DispatchException -> if (failure.safeToRetry()) "send it again" else "read state first" is ControlEndedException -> "attach again" is UnsupportedFeatureException -> if (failure.belowFloor()) "upgrade tmux" else "do without" is UnencodableTextException -> "use a UTF-8 locale" is MalformedResponseException -> "report it" is CardinalityException.NoMatch -> "nothing matched" is CardinalityException.MultipleMatches -> "ambiguous" }
nextStep(CardinalityException.MultipleMatches("many", 3)) // → ambiguousA new leaf breaks every such when at the branch that omits it:
ExhaustivenessCompileTest compiles a when one branch short and asserts the
compiler rejects it.
retryIfSafe: retry only when it is safe
import io.github.libtmux.kotlin.retryIfSafeimport io.github.libtmux.kotlin.withServer
// Given: config: ServerConfigwithServer(config) { server -> val version = retryIfSafe(times = 3) { server.version() } version.major >= 3 // → true}- It catches only
DispatchExceptionand checksfailure.safeToRetry(), which the operation that threw it computed from its own catalogued idempotence. - There is no retry executor, and no catalog lookup at the call site.
Watch tmux change
ControlClient.output: a subscription as a cold Flow
withControl attaches a control client, and output turns a
Delivery stream into a Flow:
Managed control requires tmux 3.7+ and a carrier-owned pinned socket. Ordinary suspend operations retain the core 3.3a minimum.
import io.github.libtmux.control.Deliveryimport io.github.libtmux.kotlin.withControlimport io.github.libtmux.kotlin.withServerimport kotlinx.coroutines.flow.first
// Given: config: ServerConfigwithServer(config) { server -> val session = server.newSession("flow-demo") withControl(server, session) { control -> val step = control.output(capacity = 64) { control.send("send-keys", "-t", session.name, "echo flowed", "Enter") }.first() val outcome = when (step) { // exhaustive, no else is Delivery.Event -> "kept" is Delivery.Gap -> "lost ${step.missed}" } outcome // → kept }}outputandeventsopen a fresh JavaEventSubscriptionpercollect(), never a parked thread, and close it when collection ends, is cancelled, or throws.- Output tmux sends before the subscription opens is not delivered. Put the
command whose output you want in the trailing
onSubscribedblock, which runs once the subscription exists and before the first read. - A
Delivery.Gapis an element like any other, ahead of the events that survived a full buffer. Nothing is silently dropped.
Server.withLiveState: the live server as a StateFlow
import io.github.libtmux.kotlin.withLiveStateimport io.github.libtmux.kotlin.withServerimport kotlinx.coroutines.flow.first
// Given: config: ServerConfigwithServer(config) { server -> val session = server.newSession("live-demo") server.withLiveState(session) { live -> val view = live.first()
view.epoch >= 0L // → true }}- It wraps Java’s
ServerMirror, so the resnapshot after a notification, a gap or a reconnect happens once, inside it. - It is named
liveStateso it does not collide with the Java type it wraps. liveState’s background pump runs until its scope ends, so a caller collecting for a program’s whole life passes its own long-lived scope.withLiveStateis the scoped form for everything shorter: it cancels the pump once its block returns, aswithServerandwithControldo for the resources they open.
What it leaves out
- Java depending on it. The build fails if anything in Java does: a class
carrying
@kotlin.Metadatais not null-marked under JSpecify (KT-47417), so the dependency runs one way only. - A retry executor.
retryIfSafeis a function, with no catalog lookup at the call site.
Support and status
- Kotlin 2.1 or newer.
- Releases. Releases are numbered
0.1.N, and each release incrementsN. The API is not settled: any release may change or remove exported identifiers, and the changelog marks each break. Pin an exact version to avoid one.
Documentation
- Kotlin guide
libtmux— the API this wraps- Root README
- Changelog — what each release of this module changed