Core Library0.xGuides

Choose documentation 1

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

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.

libtmux.org libtmux-kotlin

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 increments N. 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: ServerConfig
withServer(config) { server ->
val session = server.newSession("build")
session.name // → build
server.admissionBound > 0 // → true
}

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: ServerConfig
withServer(config) { server ->
val session = server.newSession {
name = "editors"
window { name = "left" }
window {
name = "right"
split { toRight(); percent(30) }
}
}
session.windows.size // → 2
}
  • @DslMarker keeps a nested block from reaching an outer block’s receiver by accident. A split { } inside a window { } cannot set the session’s directory without writing this@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.orNull
import io.github.libtmux.kotlin.withServer
import kotlin.time.Duration.Companion.seconds
// Given: config: ServerConfig
withServer(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.Pane
import io.github.libtmux.kotlin.query.active
import io.github.libtmux.kotlin.query.command
import io.github.libtmux.kotlin.withServer
// Given: config: ServerConfig
withServer(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
}

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.CardinalityException
import io.github.libtmux.exception.CommandRejectedException
import io.github.libtmux.exception.ControlEndedException
import io.github.libtmux.exception.DispatchException
import io.github.libtmux.exception.LibTmuxException
import io.github.libtmux.exception.MalformedResponseException
import io.github.libtmux.exception.ServerUnavailableException
import io.github.libtmux.exception.TargetGoneException
import io.github.libtmux.exception.UnencodableTextException
import 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)) // → ambiguous

A 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.retryIfSafe
import io.github.libtmux.kotlin.withServer
// Given: config: ServerConfig
withServer(config) { server ->
val version = retryIfSafe(times = 3) { server.version() }
version.major >= 3 // → true
}
  • It catches only DispatchException and checks failure.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.Delivery
import io.github.libtmux.kotlin.withControl
import io.github.libtmux.kotlin.withServer
import kotlinx.coroutines.flow.first
// Given: config: ServerConfig
withServer(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
}
}
  • output and events open a fresh Java EventSubscription per collect(), 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 onSubscribed block, which runs once the subscription exists and before the first read.
  • A Delivery.Gap is 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.withLiveState
import io.github.libtmux.kotlin.withServer
import kotlinx.coroutines.flow.first
// Given: config: ServerConfig
withServer(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 liveState so 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.
  • withLiveState is the scoped form for everything shorter: it cancels the pump once its block returns, as withServer and withControl do 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.Metadata is not null-marked under JSpecify (KT-47417), so the dependency runs one way only.
  • A retry executor. retryIfSafe is 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 increments N. 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

Esc
Search in

Type to search.

Reference previewOpen reference