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.

method libtmux-java latest

Server.newSession

Creates a detached session and returns that exact session.

Source and package
Qualified name
io.github.libtmux.Server.newSession
Package
io.github.libtmux
Declared in
Server
Distribution
io.github.libtmux:libtmux
Source
libtmux/src/main/java/io/github/libtmux/Server.java
Other languages
Perlmethod Erlang PowerShell Julia Elixir Haskell Common Lisp PythonRubyLuaTypeScriptRustGoC#C++SwiftKotlinScalaOCaml F# Clojure

Description#

tmux reports which session it made, so the result is exact even when another session already carries the same name.

Keep : and . out of the name. tmux decides what to do with them and changes its mind across the supported range: 3.3a through 3.6 rewrite each one to _, 3.7 refuses the name, and 3.7a onwards keeps it — where a bare -t target still misreads the delimiter, so #hasSession() and #killSession() resolve the id by comparing names instead of building one. Session#name() reports what tmux settled on.

Examples#

Create a session running cat. Use JDK 25, Gradle 9 or newer, and tmux 3.3a or newer on Linux, with /bin/cat and /bin/sh available. In an empty directory, save this consumer setup as settings.gradle.kts:

rootProject.name = "api-example"

Save this consumer setup as build.gradle.kts. It depends on the 0.1.2 release from Maven Central:

plugins {
application
}
repositories { mavenCentral() }
dependencies {
implementation("io.github.libtmux:libtmux:0.1.2")
}
java { toolchain { languageVersion.set(JavaLanguageVersion.of(25)) } }
application { mainClass.set(providers.gradleProperty("exampleMain")) }

Save this consumer setup as gradle.properties: View source

org.gradle.jvmargs=-Xmx2g -XX:MaxMetaspaceSize=768m -Dfile.encoding=UTF-8
kotlin.daemon.jvmargs=-Xmx2g
org.gradle.workers.max=2

Save this launcher as run.sh. It creates and stops a private tmux server, including after program failure. A shutdown failure retains its socket directory and exits unsuccessfully. View source

#!/bin/sh
set -eu
if [ "$#" -eq 0 ]; then
printf 'Usage: sh run.sh program [arguments...]\n' >&2
exit 2
fi
binary=$(command -v "${TMUX_BIN:-tmux}")
root=${API_RUN_ROOT:-/tmp/libtmux-java-dev}
# A client that names no socket follows TMUX or LIBTMUX_SOCKET*, and otherwise lands on the default
# socket under TMUX_TMPDIR. The program gets none of them, and a TMUX_TMPDIR of its own below.
unset TMUX TMUX_PANE
for name in $(env | sed -n 's/^\(LIBTMUX_SOCKET[A-Za-z0-9_]*\)=.*/\1/p'); do
unset "$name"
done
mkdir -p "$root"
directory=$(mktemp -d "$root/api.XXXXXX")
tmpdir=$(mktemp -d "$root/tmpdir.XXXXXX")
socket="$directory/tmux.sock"
config="$directory/tmux.conf"
serves() {
"$binary" -S "$1" display-message -p '#{pid}' >/dev/null 2>&1
}
# Stops the server on the socket, then waits for it to stop answering.
stop() {
"$binary" -S "$1" kill-server || return 1
attempts=0
while serves "$1" && [ "$attempts" -lt 60 ]; do
sleep 0.05
attempts=$((attempts + 1))
done
! serves "$1"
}
cleanup() {
status=$?
trap - 0 HUP INT TERM PIPE
# A closed output must not end the cleanup, whose messages are the only thing left to write.
trap '' PIPE
set +e
stuck=
left=
if [ -S "$socket" ] && serves "$socket" && ! stop "$socket"; then
stuck="$stuck tmux.sock"
fi
# Every socket anywhere under either directory, without following links. Only one a server answers
# on is a leak; the runner's own is expected to be there.
old_ifs=$IFS
IFS='
'
set -f
for candidate in $(find "$tmpdir" "$directory" -type s 2>/dev/null); do
[ "$candidate" = "$socket" ] && continue
serves "$candidate" || continue
case "$candidate" in
"$tmpdir"/*) name=${candidate#"$tmpdir"/} ;;
*) name=${candidate#"$directory"/} ;;
esac
left="$left $name"
stop "$candidate" || stuck="$stuck $name"
done
set +f
IFS=$old_ifs
if [ -n "$stuck" ]; then
printf 'tmux still answers on%s after kill-server; kept %s and %s under the runner root\n' \
"$stuck" "${directory##*/}" "${tmpdir##*/}" >&2
exit 1
fi
rm -rf "$directory" "$tmpdir" || exit 1
if [ -n "$left" ]; then
printf 'The program left a tmux server running:%s\n' "$left" >&2
exit 1
fi
exit "$status"
}
trap cleanup 0
trap 'exit 1' HUP INT TERM PIPE
# A default socket path longer than this does not fit in sun_path.
default_socket="$tmpdir/tmux-$(id -u)/default"
if [ "$(printf '%s' "$default_socket" | wc -c)" -gt 100 ]; then
printf 'API_RUN_ROOT is too long for a tmux socket\n' >&2
exit 1
fi
TMUX_TMPDIR=$tmpdir
export TMUX_TMPDIR
printf 'set-option -g default-shell /bin/sh\n' > "$config"
"$binary" -S "$socket" -f "$config" new-session -d -s work-one -n editor /bin/cat
"$binary" -S "$socket" split-window -h -t '=work-one:editor' /bin/cat
"$binary" -S "$socket" new-window -d -t '=work-one' -n logs /bin/cat
"$binary" -S "$socket" new-session -d -s work-two -n editor /bin/cat
"$@" "$binary" "$socket" "$config"
"$binary" -S "$socket" has-session -t '=work-one'
"$binary" -S "$socket" has-session -t '=work-two'

Save this complete program as src/main/java/NewSession.java. It opens an ordinary client for the launcher's server; closing the client releases its transport. View source

package io.github.libtmux.examples.api.java;
import io.github.libtmux.Server;
import io.github.libtmux.ServerConfig;
import io.github.libtmux.ServerEndpoint;
import io.github.libtmux.SessionSpec;
import java.nio.file.Path;
/** Create a session running cat. */
public final class NewSession {
private NewSession() {}
public static void main(String[] args) {
try {
if (args.length != 3) {
throw new IllegalArgumentException("expected: tmux-binary socket-path config-file");
}
var config = ServerConfig.builder()
.binary(args[0])
.endpoint(ServerEndpoint.socketPath(Path.of(args[1])))
.configFile(Path.of(args[2]))
.build();
try (Server server = Server.open(config)) {
var session = server.newSession(SessionSpec.builder()
.named("api-session")
.running("/bin/cat")
.build());
System.out.println("created=" + session.name());
}
} catch (Exception error) {
if (error instanceof InterruptedException) Thread.currentThread().interrupt();
System.err.println("Example failed: " + error.getMessage());
System.exit(1);
}
}
}

Build the minimal consumer with Gradle and run the saved program with the private fixture. An operation or cleanup error makes the command exit unsuccessfully:

Terminal window
$ gradle --console=plain --quiet installDist -PexampleMain=io.github.libtmux.examples.api.java.NewSession && \
sh run.sh build/install/api-example/bin/api-example

Expected output:

created=api-session
Parameters
Raises

tmux command#

The tmux commands behind newSession.

tmux C API#

The C declarations in tmux that implement these commands.

Each path starts at a function a command runs, which is degree 1. The degree counts steps from there along the path, and each step is a call or a reference: degree 2 is reached from that function, degree 3 from the next, and so on.

Create a session and its first pane

  1. 1 cmd_new_session_exec
  2. calls → 2 spawn_window
  3. calls → 3 spawn_pane
  4. calls → 4 window_add_pane
  5. calls → 5 window_pane_create

In other ports#

Create a session

Equivalents of Create a session in other languages
Language Equivalent
Python libtmux.Server.new_session
Ruby LibTmux::Server#new_session
Lua libtmux.Server:new_session
Erlang tmux_session:create/2
Haskell No public Haskell equivalent is implemented; the current modules expose scalar values and version parsing.
TypeScript server.Server.newSession
Rust server.Server.new_session
Go tmux.Server.NewSession
Clojure libtmux.core/new-session!
Kotlin io.github.libtmux.kotlin.Server.newSession
Scala io.github.libtmux.scaladsl.Server.newSession
C# LibTmux.Server.CreateSessionAsync
C++ libtmux::Server::new_session
Swift Server.newSession(named:startDirectory:windowName:width:height:environment:shell:)
OCaml Libtmux_unix.Client.create_session
Perl LibTmux::Server::new_session Explicit Server operation. Captured entities remain local observations; use a new snapshot to observe changes.

No equivalent is recorded in PowerShell, Julia, Elixir, Common Lisp or F#.

Esc

Type to search.

Reference previewOpen reference