Core Library0.xConcepts

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
Edit this page on GitHub

Filtering and queries

Filter captured objects in Scala, handle result counts explicitly, and match sessions by their related windows. Local filters read captured values; they do not subscribe to changes or issue a fresh tmux query.

Expr supports &&, || and !. The field companions expose equality, prefix, suffix, substring and pattern matching. Use .matching(expression) for a typed query or .filter(predicate) for an ordinary Scala condition.

Setup and run

Use an empty directory on Linux with tmux 3.3a or newer, JDK 25, and Gradle 9. Save the project files below, then save any complete program on this page. Each program has its own imports and entry point.

Gradle resolves libtmux-scala_3 0.1.2 from Maven Central (source).

settings.gradle.kts
rootProject.name = "connect"
build.gradle.kts
val example = providers.gradleProperty("example").getOrElse("Local")
plugins {
application
scala
}
repositories { mavenCentral() }
dependencies {
implementation("org.scala-lang:scala3-library_3:3.9.0")
implementation("io.github.libtmux:libtmux-scala_3:0.1.2")
}
java { toolchain { languageVersion.set(JavaLanguageVersion.of(25)) } }
sourceSets.main { scala.srcDir("."); scala.include("${example}.scala") }
application { mainClass.set(example) }
gradle.properties
org.gradle.jvmargs=-Xmx2g -XX:MaxMetaspaceSize=768m -Dfile.encoding=UTF-8
kotlin.daemon.jvmargs=-Xmx2g
org.gradle.workers.max=2

Each program starts its own private tmux server with two sessions: work-one with an editor window, and work-two with a logs window. Each pane runs cat so it stays alive. The program stops only that server when it finishes or fails, then removes the server’s directory. If shutdown fails, it reports the retained directory and exits with an error.

Each run starts from the same two-session fixture. Programs do not depend on another example having run first. Their assertions fail if the observed result differs.

Match names and combine conditions

Select the two names beginning with work-, then assert equality, AND, OR and exclusion against the same captured collection. Matching is case sensitive. The native collection predicate agrees with the typed prefix query.

Local.scala
import io.github.libtmux.{ServerConfig, ServerEndpoint, SessionSpec}
import io.github.libtmux.scaladsl.*
import io.github.libtmux.scaladsl.query.*
import java.nio.file.{Files, Path}
import java.time.Duration
import scala.util.Using
import scala.jdk.CollectionConverters.*
object Local {
def demonstrate(server: Server): Unit = {
val sessions = server.sessions()
val matching = sessions.matching(Session.name.startsWith("work-"))
val names = matching.map(_.name).sorted
assert(names == Vector("work-one", "work-two"))
println(names.mkString(", "))
// Filtering the captured vector makes no new tmux calls.
assert(sessions.filter(_.name.startsWith("work-")) == matching)
val onlyOne = Session.name.startsWith("work-") &&
Session.name.endsWith("one")
assert(sessions.matching(onlyOne).head.name == "work-one")
val either = Session.name.is("work-one") || Session.name.is("work-two")
assert(sessions.matching(either).size == 2)
val others = sessions.matching(!Session.name.is("work-one"))
assert(others.head.name == "work-two")
}
def main(args: Array[String]): Unit = {
val directory = Files.createTempDirectory("libtmux-example-")
val socket = directory.resolve("tmux.sock")
val config = ServerConfig.builder()
.endpoint(ServerEndpoint.socketPath(socket))
.configFile(Path.of("/dev/null"))
.defaultTimeout(Duration.ofSeconds(5))
.build()
var stopped = false
try {
Using.resource(Server.open(config)) { server =>
try {
server.newSession(SessionSpec.builder()
.named("work-one").firstWindowNamed("editor")
.running("/bin/cat").build())
server.newSession(SessionSpec.builder()
.named("work-two").firstWindowNamed("logs")
.running("/bin/cat").build())
demonstrate(server)
} finally {
if (Files.exists(socket)) server.killServer()
stopped = true
}
}
} finally {
if (stopped || !Files.exists(socket)) {
Files.deleteIfExists(socket)
Files.delete(directory)
} else {
System.err.println(s"Cannot stop tmux; kept $directory")
}
}
}
}
Terminal window
$ gradle --console=plain --no-daemon run -Pexample=Local

Expected program output:

work-one, work-two

Distinguish missing and ambiguous results

An exactly-one selection returns an Either: one handle on success, CardinalityError.NoMatch for zero, or MultipleMatches for several. An at-most-one selection also rejects ambiguity; it does not pick an arbitrary first result.

Cardinality.scala
import io.github.libtmux.{ServerConfig, ServerEndpoint, SessionSpec}
import io.github.libtmux.scaladsl.*
import io.github.libtmux.scaladsl.query.*
import java.nio.file.{Files, Path}
import java.time.Duration
import scala.util.Using
import scala.jdk.CollectionConverters.*
object Cardinality {
def demonstrate(server: Server): Unit = {
val sessions = server.sessions()
for (name <- Vector("work-one", "missing")) {
sessions.matching(Session.name.is(name)).exactlyOne match {
case Right(session) => println(s"${session.name}: selected")
case Left(CardinalityError.NoMatch) => println(s"$name: absent")
case Left(CardinalityError.MultipleMatches(count)) =>
throw new IllegalStateException(
s"At least $count sessions named $name")
}
}
val many = sessions.matching(Session.name.startsWith("work-")).atMostOne
assert(many == Left(CardinalityError.MultipleMatches(2)))
println("work-: ambiguous")
}
def main(args: Array[String]): Unit = {
val directory = Files.createTempDirectory("libtmux-example-")
val socket = directory.resolve("tmux.sock")
val config = ServerConfig.builder()
.endpoint(ServerEndpoint.socketPath(socket))
.configFile(Path.of("/dev/null"))
.defaultTimeout(Duration.ofSeconds(5))
.build()
var stopped = false
try {
Using.resource(Server.open(config)) { server =>
try {
server.newSession(SessionSpec.builder()
.named("work-one").firstWindowNamed("editor")
.running("/bin/cat").build())
server.newSession(SessionSpec.builder()
.named("work-two").firstWindowNamed("logs")
.running("/bin/cat").build())
demonstrate(server)
} finally {
if (Files.exists(socket)) server.killServer()
stopped = true
}
}
} finally {
if (stopped || !Files.exists(socket)) {
Files.deleteIfExists(socket)
Files.delete(directory)
} else {
System.err.println(s"Cannot stop tmux; kept $directory")
}
}
}
}
Terminal window
$ gradle --console=plain --no-daemon run -Pexample=Cardinality

Expected program output:

work-one: selected
missing: absent
work-: ambiguous

Match sessions with any window named editor, then match sessions with none. For an empty captured relation, any is false and none is true; all is true. An uncaptured relation is a different condition and must be captured before filtering.

Relations.scala
import io.github.libtmux.{ServerConfig, ServerEndpoint, SessionSpec}
import io.github.libtmux.scaladsl.*
import io.github.libtmux.scaladsl.query.*
import java.nio.file.{Files, Path}
import java.time.Duration
import scala.util.Using
import scala.jdk.CollectionConverters.*
object Relations {
def demonstrate(server: Server): Unit = {
val sessions = server.sessions()
val editorWindow = Window.name.is("editor")
val withEditor = sessions.matching(Session.windows.any(editorWindow))
val withoutEditor = sessions.matching(Session.windows.none(editorWindow))
assert(withEditor.map(_.name) == Vector("work-one"))
assert(withoutEditor.map(_.name) == Vector("work-two"))
println(s"editor: ${withEditor.head.name}")
println(s"no editor: ${withoutEditor.head.name}")
}
def main(args: Array[String]): Unit = {
val directory = Files.createTempDirectory("libtmux-example-")
val socket = directory.resolve("tmux.sock")
val config = ServerConfig.builder()
.endpoint(ServerEndpoint.socketPath(socket))
.configFile(Path.of("/dev/null"))
.defaultTimeout(Duration.ofSeconds(5))
.build()
var stopped = false
try {
Using.resource(Server.open(config)) { server =>
try {
server.newSession(SessionSpec.builder()
.named("work-one").firstWindowNamed("editor")
.running("/bin/cat").build())
server.newSession(SessionSpec.builder()
.named("work-two").firstWindowNamed("logs")
.running("/bin/cat").build())
demonstrate(server)
} finally {
if (Files.exists(socket)) server.killServer()
stopped = true
}
}
} finally {
if (stopped || !Files.exists(socket)) {
Files.deleteIfExists(socket)
Files.delete(directory)
} else {
System.err.println(s"Cannot stop tmux; kept $directory")
}
}
}
}
Terminal window
$ gradle --console=plain --no-daemon run -Pexample=Relations

Expected program output:

editor: work-one
no editor: work-two

Refresh before repeating a decision

Reusing the same list repeats the same decision over old state. Capture again when you need to observe a rename, new window or closed pane. The snapshot example shows the old and fresh values side by side.

Esc
Search in

Type to search.

Reference previewOpen reference