tmux, in your language
Control tmux from your application.
Create sessions, arrange panes, send input, and capture output.
Start with Python
from __future__ import annotations
from pathlib import Pathimport tempfileimport time
import libtmuxfrom libtmux.constants import PaneDirection
directory = Path(tempfile.mkdtemp(prefix="libtmux-py-home-"))socket = directory / "tmux.sock"server = libtmux.Server(socket_path=socket, config_file="/dev/null")
session = server.new_session(session_name="demo")
# Lay out the session: name its window, split it, add a second window.editor = session.active_windoweditor.rename_window("editor")left = editor.active_paneassert left is not Noneright = left.split(direction=PaneDirection.Right, shell="sh")logs = session.new_window(window_name="logs")
# Type a command into the new pane and wait for what it prints.right.send_keys("printf 'hello from %s\\n' tmux", enter=True)deadline = time.monotonic() + 5while "hello from tmux" not in right.capture_pane(): if time.monotonic() >= deadline: raise TimeoutError("The pane did not print hello from tmux") time.sleep(0.02)
# Move the focus an attached client sees: the pane, then the window.right.select()logs.select()
# Walk the objects: down from the server, then up from one pane.sessions = server.sessionsfor each in sessions: print("session", each.session_name) windows = each.windows for window in windows: panes = window.panes ids = " ".join(pane.pane_id for pane in panes) print(f" window {window.window_index}:{window.window_name}: {ids}")window = right.windowowner = window.sessionprint(right.pane_id, "is in window", window.window_name, "of session", owner.session_name)from __future__ import annotations
from pathlib import Pathimport tempfileimport time
import libtmuxfrom libtmux.constants import PaneDirection
directory = Path(tempfile.mkdtemp(prefix="libtmux-py-home-"))socket = directory / "tmux.sock"server = libtmux.Server(socket_path=socket, config_file="/dev/null")
try: session = server.new_session(session_name="demo")
# Lay out the session: name its window, split it, add a second window. editor = session.active_window editor.rename_window("editor") left = editor.active_pane assert left is not None right = left.split(direction=PaneDirection.Right, shell="sh") logs = session.new_window(window_name="logs")
# Type a command into the new pane and wait for what it prints. right.send_keys("printf 'hello from %s\\n' tmux", enter=True) deadline = time.monotonic() + 5 while "hello from tmux" not in right.capture_pane(): if time.monotonic() >= deadline: raise TimeoutError("The pane did not print hello from tmux") time.sleep(0.02)
# Move the focus an attached client sees: the pane, then the window. right.select() logs.select()
# Walk the objects: down from the server, then up from one pane. sessions = server.sessions for each in sessions: print("session", each.session_name) windows = each.windows for window in windows: panes = window.panes ids = " ".join(pane.pane_id for pane in panes) print(f" window {window.window_index}:{window.window_name}: {ids}") window = right.window owner = window.session print(right.pane_id, "is in window", window.window_name, "of session", owner.session_name)except Exception as error: raise RuntimeError("tmux quickstart failed") from errorfrom __future__ import annotations
from pathlib import Pathimport shutilimport tempfileimport time
import libtmuxfrom libtmux.constants import PaneDirection
directory = Path(tempfile.mkdtemp(prefix="libtmux-py-home-"))socket = directory / "tmux.sock"server = libtmux.Server(socket_path=socket, config_file="/dev/null")
try: session = server.new_session(session_name="demo")
# Lay out the session: name its window, split it, add a second window. editor = session.active_window editor.rename_window("editor") left = editor.active_pane assert left is not None right = left.split(direction=PaneDirection.Right, shell="sh") logs = session.new_window(window_name="logs")
# Type a command into the new pane and wait for what it prints. right.send_keys("printf 'hello from %s\\n' tmux", enter=True) deadline = time.monotonic() + 5 while "hello from tmux" not in right.capture_pane(): if time.monotonic() >= deadline: raise TimeoutError("The pane did not print hello from tmux") time.sleep(0.02)
# Move the focus an attached client sees: the pane, then the window. right.select() logs.select()
# Walk the objects: down from the server, then up from one pane. sessions = server.sessions for each in sessions: print("session", each.session_name) windows = each.windows for window in windows: panes = window.panes ids = " ".join(pane.pane_id for pane in panes) print(f" window {window.window_index}:{window.window_name}: {ids}") window = right.window owner = window.session print(right.pane_id, "is in window", window.window_name, "of session", owner.session_name)finally: if socket.exists(): server.kill() shutil.rmtree(directory)from __future__ import annotations
from pathlib import Pathimport shutilimport tempfileimport time
import libtmuxfrom libtmux.constants import PaneDirection
directory = Path(tempfile.mkdtemp(prefix="libtmux-py-home-"))socket = directory / "tmux.sock"server = libtmux.Server(socket_path=socket, config_file="/dev/null")
try: session = server.new_session(session_name="demo")
# Lay out the session: name its window, split it, add a second window. editor = session.active_window editor.rename_window("editor") left = editor.active_pane assert left is not None right = left.split(direction=PaneDirection.Right, shell="sh") logs = session.new_window(window_name="logs")
# Type a command into the new pane and wait for what it prints. right.send_keys("printf 'hello from %s\\n' tmux", enter=True) deadline = time.monotonic() + 5 while "hello from tmux" not in right.capture_pane(): if time.monotonic() >= deadline: raise TimeoutError("The pane did not print hello from tmux") time.sleep(0.02)
# Move the focus an attached client sees: the pane, then the window. right.select() logs.select()
# Walk the objects: down from the server, then up from one pane. sessions = server.sessions for each in sessions: print("session", each.session_name) windows = each.windows for window in windows: panes = window.panes ids = " ".join(pane.pane_id for pane in panes) print(f" window {window.window_index}:{window.window_name}: {ids}") window = right.window owner = window.session print(right.pane_id, "is in window", window.window_name, "of session", owner.session_name)except Exception as error: raise RuntimeError("tmux quickstart failed") from errorfinally: if socket.exists(): server.kill() shutil.rmtree(directory)Run this example
POSIX shell, tmux 3.2a or newer, Python 3.14.6 and uv (tested 0.12.0).
Save the program above as quickstart.py in a new directory, along with the files below.
Cleanup is omitted; the private tmux server and its temporary files may remain. Select Cleanup to remove them when the program finishes. The program stops its private tmux server and removes any temporary files it created when it finishes. Error handling adds diagnostics; every version checks required results and deadlines.
Setup and run
uv venv .venvuv pip install --python .venv/bin/python libtmux==0.62.0unset TMUX TMUX_PANEexport ENV=/dev/null BASH_ENV=/dev/null SHELL=/bin/sh.venv/bin/python quickstart.pyExpected output
session demo window 0:editor: %0 %1 window 1:logs: %2%1 is in window editor of session demoDependency cooldowns
The checkbox turns a cooldown on and off for every picker on the site. It applies to what an install pulls in; the package itself, and the libtmux it pins, stay current.
What are cooldowns?
Cooldowns delay picking up newly uploaded packages so the community has time to spot supply-chain attacks before you install. Most package managers don't apply one by default; you opt in through a global setting in your tool's configuration.
Learn more at cooldowns.dev · Datadog Security Labs writeup.
$ pip install libtmux$ pip install libtmuxpip cannot exempt libtmux from its own cooldown, so a cooldown here would also hold back the release this installs. This command runs without one.
$ pip install libtmuxpip cannot exempt libtmux from its own cooldown, so a cooldown here would also hold back the release this installs. This command runs without one.
$ uv add libtmux$ uv add --no-config libtmux$ pipx install libtmux$ pipx install libtmuxpipx cannot exempt libtmux from its own cooldown, so a cooldown here would also hold back the release this installs. This command runs without one.
$ pipx install libtmuxpipx cannot exempt libtmux from its own cooldown, so a cooldown here would also hold back the release this installs. This command runs without one.
Start with Ruby
require "libtmux"
# A private server: its own socket and an empty config, so this neither# touches nor is changed by a tmux you already use.snapshot, ref = LibTmux::Server.start do |server| session = server.new_session(name: "demo", command: ["/bin/cat"])
# Lay out the session: name its window, split it, add a second window. editor = server.window(session.snapshot.current_window.ref) editor.rename("editor") left = server.pane(editor.snapshot.active_pane.ref) right = left.split(direction: :horizontal, command: ["/bin/sh"]) logs = session.new_window(name: "logs", command: ["/bin/cat"])
# Type a command into the new pane and wait for what it prints. right.send_text("printf 'hello from %s\\n' tmux") right.send_keys("Enter") deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 5 until right.capture.stdout.include?("hello from tmux") if Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline raise "Output did not arrive within five seconds" end sleep 0.05 end
# Move the focus an attached client sees: the pane, then the window. right.select session.list_window_links.find { |link| link.window == logs }.select
[server.snapshot, right.ref]end
# Walk the objects: down from the server, then up from one pane.snapshot.sessions.each do |entry| puts "session #{entry.name}" entry.window_links.each do |link| pane_ids = link.window.panes.map(&:id).join(" ") puts " window #{link.index}:#{link.window.name}: #{pane_ids}" endendpane = snapshot.resolve(ref)window = pane.windowowner = window.window_links.first.sessionputs "#{pane.id} is in window #{window.name} of session #{owner.name}"require "libtmux"
# A private server: its own socket and an empty config, so this neither# touches nor is changed by a tmux you already use.begin snapshot, ref = LibTmux::Server.start do |server| session = server.new_session(name: "demo", command: ["/bin/cat"])
# Lay out the session: name its window, split it, add a second window. editor = server.window(session.snapshot.current_window.ref) editor.rename("editor") left = server.pane(editor.snapshot.active_pane.ref) right = left.split(direction: :horizontal, command: ["/bin/sh"]) logs = session.new_window(name: "logs", command: ["/bin/cat"])
# Type a command into the new pane and wait for what it prints. right.send_text("printf 'hello from %s\\n' tmux") right.send_keys("Enter") deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 5 until right.capture.stdout.include?("hello from tmux") if Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline raise "Output did not arrive within five seconds" end sleep 0.05 end
# Move the focus an attached client sees: the pane, then the window. right.select session.list_window_links.find { |link| link.window == logs }.select
[server.snapshot, right.ref] end
# Walk the objects: down from the server, then up from one pane. snapshot.sessions.each do |entry| puts "session #{entry.name}" entry.window_links.each do |link| pane_ids = link.window.panes.map(&:id).join(" ") puts " window #{link.index}:#{link.window.name}: #{pane_ids}" end end pane = snapshot.resolve(ref) window = pane.window owner = window.window_links.first.session puts "#{pane.id} is in window #{window.name} of session #{owner.name}"rescue StandardError => error warn "tmux quickstart failed: #{error.message}" raiseendrequire "libtmux"
# A private server: its own socket and an empty config, so this neither# touches nor is changed by a tmux you already use.server = LibTmux::Server.start
begin session = server.new_session(name: "demo", command: ["/bin/cat"])
# Lay out the session: name its window, split it, add a second window. editor = server.window(session.snapshot.current_window.ref) editor.rename("editor") left = server.pane(editor.snapshot.active_pane.ref) right = left.split(direction: :horizontal, command: ["/bin/sh"]) logs = session.new_window(name: "logs", command: ["/bin/cat"])
# Type a command into the new pane and wait for what it prints. right.send_text("printf 'hello from %s\\n' tmux") right.send_keys("Enter") deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 5 until right.capture.stdout.include?("hello from tmux") if Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline raise "Output did not arrive within five seconds" end sleep 0.05 end
# Move the focus an attached client sees: the pane, then the window. right.select session.list_window_links.find { |link| link.window == logs }.select
# Walk the objects: down from the server, then up from one pane. snapshot = server.snapshot snapshot.sessions.each do |entry| puts "session #{entry.name}" entry.window_links.each do |link| pane_ids = link.window.panes.map(&:id).join(" ") puts " window #{link.index}:#{link.window.name}: #{pane_ids}" end end pane = snapshot.resolve(right.ref) window = pane.window owner = window.window_links.first.session puts "#{pane.id} is in window #{window.name} of session #{owner.name}"ensure server.closeendrequire "libtmux"
# A private server: its own socket and an empty config, so this neither# touches nor is changed by a tmux you already use.server = LibTmux::Server.start
begin session = server.new_session(name: "demo", command: ["/bin/cat"])
# Lay out the session: name its window, split it, add a second window. editor = server.window(session.snapshot.current_window.ref) editor.rename("editor") left = server.pane(editor.snapshot.active_pane.ref) right = left.split(direction: :horizontal, command: ["/bin/sh"]) logs = session.new_window(name: "logs", command: ["/bin/cat"])
# Type a command into the new pane and wait for what it prints. right.send_text("printf 'hello from %s\\n' tmux") right.send_keys("Enter") deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 5 until right.capture.stdout.include?("hello from tmux") if Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline raise "Output did not arrive within five seconds" end sleep 0.05 end
# Move the focus an attached client sees: the pane, then the window. right.select session.list_window_links.find { |link| link.window == logs }.select
# Walk the objects: down from the server, then up from one pane. snapshot = server.snapshot snapshot.sessions.each do |entry| puts "session #{entry.name}" entry.window_links.each do |link| pane_ids = link.window.panes.map(&:id).join(" ") puts " window #{link.index}:#{link.window.name}: #{pane_ids}" end end pane = snapshot.resolve(right.ref) window = pane.window owner = window.window_links.first.session puts "#{pane.id} is in window #{window.name} of session #{owner.name}"rescue StandardError => error warn "tmux quickstart failed: #{error.message}" raiseensure server.closeendRun this example
POSIX shell, tmux 3.3a or newer, Ruby 4.0.7, Bundler 4.0.20, a C build toolchain for gems and access to rubygems.org.
Save the program above as quickstart.rb in a new directory, along with the files below.
The Ruby block closes its server automatically. Cleanup shows the explicit ensure form. The program stops its private tmux server and removes any temporary files it created when it finishes. Error handling adds diagnostics; every version checks required results and deadlines.
Gemfile
source "https://rubygems.org"gem "libtmux", "~> 0.1"Gemfile.lock
GEM remote: https://rubygems.org/ specs: fiddle (1.1.8) fileutils (1.8.1) io-console (0.9.5) json (3.0.2) libtmux (0.1.2) fiddle (~> 1.1) io-console (~> 0.8) json (~> 3.0.2) securerandom (~> 0.4) tmpdir (~> 0.3) securerandom (0.4.1) tmpdir (0.3.2) fileutils
PLATFORMS ruby x86_64-linux
DEPENDENCIES libtmux (~> 0.1)
CHECKSUMS fiddle (1.1.8) sha256=7fa8ee3627271497f3add5503acdbc3f40b32f610fc1cf49634f083ef3f32eee fileutils (1.8.1) sha256=2d541a1ee34a9ed5c4f054be8fb819a26b5d654488a31dc8806917cf448b9cc3 io-console (0.9.5) sha256=83dd9bbf4c4680416629245b39cd4212eb5f4d9a4ea91804870c1f6b846414d5 json (3.0.2) sha256=8e6d7e7b11384c21230430cef90b71f14849a34a1f4452796670f7c981bd19df libtmux (0.1.2) sha256=340498b8e45b5b5d6511668909d9c3104fe7b17e65daaa9cfa50661ce299356a securerandom (0.4.1) sha256=cc5193d414a4341b6e225f0cb4446aceca8e50d5e1888743fac16987638ea0b1 tmpdir (0.3.2) sha256=e276ef386182169f8d417d9e90f12dba82a54e81646df0caf21de4a7987a0c27
BUNDLED WITH 4.0.20Setup and run
bundle config set --local path vendor/bundlebundle install --jobs 2unset TMUX TMUX_PANEexport ENV=/dev/null BASH_ENV=/dev/null SHELL=/bin/shbundle exec ruby quickstart.rbExpected output
session demo window 0:editor: %0 %1 window 1:logs: %2%1 is in window editor of session demo$ gem install libtmuxgem "libtmux"Start with Lua
local adapter = require("libtmux.runtime.luv")local uv = require("luv")
local function must(value, err) if err ~= nil then error(err, 0) end return valueend
local binaryfor directory in (os.getenv("PATH") or ""):gmatch("[^:]+") do local candidate = uv.fs_realpath(directory .. "/tmux") if candidate and uv.fs_access(candidate, "X") then binary = candidate break endendassert(binary, "tmux must be installed on PATH")
-- A private server: a socket and an empty config of its own, so this-- neither touches nor is changed by a tmux you already use.local directory = assert(uv.fs_mkdtemp("/tmp/ltx-lua-home-XXXXXX"))local socket = directory .. "/tmux.sock"
local function tmux(arguments) local args = { "-S", socket } for _, argument in ipairs(arguments) do args[#args + 1] = argument end
local timer = assert(uv.new_timer()) local process, status process = assert(uv.spawn(binary, { args = args, stdio = { nil, 1, 2 }, }, function(code) status = code process:close() timer:stop() timer:close() end)) timer:start(10000, 0, function() process:kill("sigkill") end) uv.run() assert(status == 0, "tmux command failed or timed out")end
-- This Lua API connects to an existing daemon. Start our own first,-- and keep it alive with no session so the program creates them all.tmux({ "-f", "/dev/null", "start-server", ";", "set-option", "-s", "exit-empty", "off",})
must(adapter.run(function(runtime) local server = must(runtime:connect({ binary = binary, socket_path = socket, }):await()) local created = must(server:new_session({ name = "demo", }):await())
-- Lay out the session: name its window, split it, add a second -- window. None of them takes the focus from the first pane. local editor = created.window must(editor:rename("editor"):await()) local split = must(created.pane:split({ direction = "right", }):await()) local right = split.pane local logs = must(created.session:new_window({ name = "logs", }):await())
-- Type a command into the new pane and wait for what it prints. local command = "printf 'hello from %s\\n' tmux" must(right:send_text(command):await()) must(right:send_keys({ "Enter" }):await()) must(right:wait_for_text("hello from tmux", { timeout = 10000, }):await())
-- Move the focus an attached client sees: the pane, then the window. must(right:select():await()) must(logs.window_link:select():await())
-- Walk the objects: down from the server, then up from one pane. local snapshot = must(server:snapshot():await()) for _, each in ipairs(snapshot.sessions) do print("session " .. each.name) for _, link in ipairs(each.window_links) do local window = link.window local line = (" window %d:%s:"):format( link.index, window.name ) for _, pane in ipairs(window.panes) do line = line .. " " .. pane.id end print(line) end end local id = right:reference().id for _, pane in ipairs(snapshot.panes) do if pane.id == id then local window = pane.window local owner = window.window_links[1].session print(("%s is in window %s of session %s"):format( pane.id, window.name, owner.name )) end end
must(server:close():await()) return trueend))local adapter = require("libtmux.runtime.luv")local uv = require("luv")
local function must(value, err) if err ~= nil then error(err, 0) end return valueend
local binaryfor directory in (os.getenv("PATH") or ""):gmatch("[^:]+") do local candidate = uv.fs_realpath(directory .. "/tmux") if candidate and uv.fs_access(candidate, "X") then binary = candidate break endendassert(binary, "tmux must be installed on PATH")
-- A private server: a socket and an empty config of its own, so this-- neither touches nor is changed by a tmux you already use.local directory = assert(uv.fs_mkdtemp("/tmp/ltx-lua-home-XXXXXX"))local socket = directory .. "/tmux.sock"
local function tmux(arguments) local args = { "-S", socket } for _, argument in ipairs(arguments) do args[#args + 1] = argument end
local timer = assert(uv.new_timer()) local process, status process = assert(uv.spawn(binary, { args = args, stdio = { nil, 1, 2 }, }, function(code) status = code process:close() timer:stop() timer:close() end)) timer:start(10000, 0, function() process:kill("sigkill") end) uv.run() assert(status == 0, "tmux command failed or timed out")end
local ok, failure = xpcall(function() -- This Lua API connects to an existing daemon. Start our own first, -- and keep it alive with no session so the program creates them all. tmux({ "-f", "/dev/null", "start-server", ";", "set-option", "-s", "exit-empty", "off", })
must(adapter.run(function(runtime) local server = must(runtime:connect({ binary = binary, socket_path = socket, }):await()) local created = must(server:new_session({ name = "demo", }):await())
-- Lay out the session: name its window, split it, add a second -- window. None of them takes the focus from the first pane. local editor = created.window must(editor:rename("editor"):await()) local split = must(created.pane:split({ direction = "right", }):await()) local right = split.pane local logs = must(created.session:new_window({ name = "logs", }):await())
-- Type a command into the new pane and wait for what it prints. local command = "printf 'hello from %s\\n' tmux" must(right:send_text(command):await()) must(right:send_keys({ "Enter" }):await()) must(right:wait_for_text("hello from tmux", { timeout = 10000, }):await())
-- Move the focus an attached client sees: the pane, then the window. must(right:select():await()) must(logs.window_link:select():await())
-- Walk the objects: down from the server, then up from one pane. local snapshot = must(server:snapshot():await()) for _, each in ipairs(snapshot.sessions) do print("session " .. each.name) for _, link in ipairs(each.window_links) do local window = link.window local line = (" window %d:%s:"):format( link.index, window.name ) for _, pane in ipairs(window.panes) do line = line .. " " .. pane.id end print(line) end end local id = right:reference().id for _, pane in ipairs(snapshot.panes) do if pane.id == id then local window = pane.window local owner = window.window_links[1].session print(("%s is in window %s of session %s"):format( pane.id, window.name, owner.name )) end end
must(server:close():await()) return true end))end, debug.traceback)
if not ok then error(failure, 0) endlocal adapter = require("libtmux.runtime.luv")local uv = require("luv")
local function must(value, err) if err ~= nil then error(err, 0) end return valueend
local binaryfor directory in (os.getenv("PATH") or ""):gmatch("[^:]+") do local candidate = uv.fs_realpath(directory .. "/tmux") if candidate and uv.fs_access(candidate, "X") then binary = candidate break endendassert(binary, "tmux must be installed on PATH")
-- A private server: a socket and an empty config of its own, so this-- neither touches nor is changed by a tmux you already use.local directory = assert(uv.fs_mkdtemp("/tmp/ltx-lua-home-XXXXXX"))local socket = directory .. "/tmux.sock"
local function tmux(arguments) local args = { "-S", socket } for _, argument in ipairs(arguments) do args[#args + 1] = argument end
local timer = assert(uv.new_timer()) local process, status process = assert(uv.spawn(binary, { args = args, stdio = { nil, 1, 2 }, }, function(code) status = code process:close() timer:stop() timer:close() end)) timer:start(10000, 0, function() process:kill("sigkill") end) uv.run() assert(status == 0, "tmux command failed or timed out")end
local ok, failure = pcall(function() -- This Lua API connects to an existing daemon. Start our own first, -- and keep it alive with no session so the program creates them all. tmux({ "-f", "/dev/null", "start-server", ";", "set-option", "-s", "exit-empty", "off", })
must(adapter.run(function(runtime) local server = must(runtime:connect({ binary = binary, socket_path = socket, }):await()) local created = must(server:new_session({ name = "demo", }):await())
-- Lay out the session: name its window, split it, add a second -- window. None of them takes the focus from the first pane. local editor = created.window must(editor:rename("editor"):await()) local split = must(created.pane:split({ direction = "right", }):await()) local right = split.pane local logs = must(created.session:new_window({ name = "logs", }):await())
-- Type a command into the new pane and wait for what it prints. local command = "printf 'hello from %s\\n' tmux" must(right:send_text(command):await()) must(right:send_keys({ "Enter" }):await()) must(right:wait_for_text("hello from tmux", { timeout = 10000, }):await())
-- Move the focus an attached client sees: the pane, then the window. must(right:select():await()) must(logs.window_link:select():await())
-- Walk the objects: down from the server, then up from one pane. local snapshot = must(server:snapshot():await()) for _, each in ipairs(snapshot.sessions) do print("session " .. each.name) for _, link in ipairs(each.window_links) do local window = link.window local line = (" window %d:%s:"):format( link.index, window.name ) for _, pane in ipairs(window.panes) do line = line .. " " .. pane.id end print(line) end end local id = right:reference().id for _, pane in ipairs(snapshot.panes) do if pane.id == id then local window = pane.window local owner = window.window_links[1].session print(("%s is in window %s of session %s"):format( pane.id, window.name, owner.name )) end end
must(server:close():await()) return true end))end)
local cleaned, cleanup_error = pcall(function() if uv.fs_stat(socket) then tmux({ "kill-server" }) end local removed, _, code = uv.fs_unlink(socket) assert(removed or code == "ENOENT", "could not remove owned socket") assert(uv.fs_rmdir(directory))end)
if not cleaned then io.stderr:write(tostring(cleanup_error), "\n") endif not ok then error(failure, 0) endassert(cleaned, "cleanup failed; retained " .. directory)local adapter = require("libtmux.runtime.luv")local uv = require("luv")
local function must(value, err) if err ~= nil then error(err, 0) end return valueend
local binaryfor directory in (os.getenv("PATH") or ""):gmatch("[^:]+") do local candidate = uv.fs_realpath(directory .. "/tmux") if candidate and uv.fs_access(candidate, "X") then binary = candidate break endendassert(binary, "tmux must be installed on PATH")
-- A private server: a socket and an empty config of its own, so this-- neither touches nor is changed by a tmux you already use.local directory = assert(uv.fs_mkdtemp("/tmp/ltx-lua-home-XXXXXX"))local socket = directory .. "/tmux.sock"
local function tmux(arguments) local args = { "-S", socket } for _, argument in ipairs(arguments) do args[#args + 1] = argument end
local timer = assert(uv.new_timer()) local process, status process = assert(uv.spawn(binary, { args = args, stdio = { nil, 1, 2 }, }, function(code) status = code process:close() timer:stop() timer:close() end)) timer:start(10000, 0, function() process:kill("sigkill") end) uv.run() assert(status == 0, "tmux command failed or timed out")end
local ok, failure = xpcall(function() -- This Lua API connects to an existing daemon. Start our own first, -- and keep it alive with no session so the program creates them all. tmux({ "-f", "/dev/null", "start-server", ";", "set-option", "-s", "exit-empty", "off", })
must(adapter.run(function(runtime) local server = must(runtime:connect({ binary = binary, socket_path = socket, }):await()) local created = must(server:new_session({ name = "demo", }):await())
-- Lay out the session: name its window, split it, add a second -- window. None of them takes the focus from the first pane. local editor = created.window must(editor:rename("editor"):await()) local split = must(created.pane:split({ direction = "right", }):await()) local right = split.pane local logs = must(created.session:new_window({ name = "logs", }):await())
-- Type a command into the new pane and wait for what it prints. local command = "printf 'hello from %s\\n' tmux" must(right:send_text(command):await()) must(right:send_keys({ "Enter" }):await()) must(right:wait_for_text("hello from tmux", { timeout = 10000, }):await())
-- Move the focus an attached client sees: the pane, then the window. must(right:select():await()) must(logs.window_link:select():await())
-- Walk the objects: down from the server, then up from one pane. local snapshot = must(server:snapshot():await()) for _, each in ipairs(snapshot.sessions) do print("session " .. each.name) for _, link in ipairs(each.window_links) do local window = link.window local line = (" window %d:%s:"):format( link.index, window.name ) for _, pane in ipairs(window.panes) do line = line .. " " .. pane.id end print(line) end end local id = right:reference().id for _, pane in ipairs(snapshot.panes) do if pane.id == id then local window = pane.window local owner = window.window_links[1].session print(("%s is in window %s of session %s"):format( pane.id, window.name, owner.name )) end end
must(server:close():await()) return true end))end, debug.traceback)
local cleaned, cleanup_error = pcall(function() if uv.fs_stat(socket) then tmux({ "kill-server" }) end local removed, _, code = uv.fs_unlink(socket) assert(removed or code == "ENOENT", "could not remove owned socket") assert(uv.fs_rmdir(directory))end)
if not cleaned then io.stderr:write(tostring(cleanup_error), "\n") endif not ok then error(failure, 0) endassert(cleaned, "cleanup failed; retained " .. directory)Run this example
POSIX shell, tmux 3.3a or newer, Lua 5.5.1, LuaRocks 3.13.0, CMake and a C compiler; setup installs luv 1.52.1-0 and libtmux 0.1.1.
Save the program above as quickstart.lua in a new directory, along with the files below.
Cleanup is omitted; the private tmux server and its temporary files may remain. Select Cleanup to remove them when the program finishes. The program stops its private tmux server and removes any temporary files it created when it finishes. Error handling adds diagnostics; every version checks required results and deadlines.
Setup and run
luarocks --tree .rocks install luv 1.52.1-0luarocks --tree .rocks install libtmux 0.1.1-1unset TMUX TMUX_PANEexport ENV=/dev/null BASH_ENV=/dev/null SHELL=/bin/sheval "$(luarocks --tree .rocks path)"lua quickstart.luaExpected output
session demo window 0:editor: %0 %1 window 1:logs: %2%1 is in window editor of session demo$ luarocks --local install libtmuxStart with PowerShell
$ErrorActionPreference = 'Stop'Import-Module "$PSScriptRoot/modules/LibTmux/0.1.0/LibTmux.psd1"
# A private server: a socket and an empty config of its own, so this# neither touches nor is changed by a tmux you already use.# The process ID in the socket name keeps one run apart from the next.$socket = 'libtmux-home-' + $PID$server = New-TmuxServer -SocketName $socket -ConfigurationFile /dev/null$session = $server | New-TmuxSession -Name demo
# Lay out the session: name its window, split it, add a second window.$window = $session | Get-TmuxWindow | Where-Object Active$editor = $window.RenameAsync('editor').GetAwaiter().GetResult()$left = $editor | Get-TmuxPane | Where-Object Active$right = $left | Split-TmuxPane -Horizontal$logs = $session | New-TmuxWindow -Name logs
# Type a command into the new pane and wait for what it prints.$right | Send-TmuxText -Text "printf 'hello from %s\n' tmux" -Enter$found = $right | Wait-TmuxPaneText -Pattern 'hello from tmux' -Timeout 10if (-not $found.Found) { throw 'the pane never showed the output' }
# Move the focus an attached client sees: the pane, then the window.$request = [LibTmux.SelectPaneRequest]::new()$right = $right.SelectAsync($request).GetAwaiter().GetResult()$logs = $logs.SelectAsync().GetAwaiter().GetResult()
# Walk the objects: down from the server, then up from one pane.$snapshot = $server | Get-TmuxSnapshotforeach ($each in $snapshot.Sessions) { "session $($each.Name)" foreach ($window in $each.Windows) { ' window {0}:{1}: {2}' -f $window.Index, $window.Name, ($window.Panes.Id -join ' ') }}$pane = $snapshot.Panes | Where-Object Id -eq $right.Id$window = $pane.Window$owner = $pane.Session"$($pane.Id) is in window $($window.Name) of session $($owner.Name)"$ErrorActionPreference = 'Stop'Import-Module "$PSScriptRoot/modules/LibTmux/0.1.0/LibTmux.psd1"
try { # A private server: a socket and an empty config of its own, so this # neither touches nor is changed by a tmux you already use. # The process ID in the socket name keeps one run apart from the next. $socket = 'libtmux-home-' + $PID $server = New-TmuxServer -SocketName $socket -ConfigurationFile /dev/null $session = $server | New-TmuxSession -Name demo
# Lay out the session: name its window, split it, add a second window. $window = $session | Get-TmuxWindow | Where-Object Active $editor = $window.RenameAsync('editor').GetAwaiter().GetResult() $left = $editor | Get-TmuxPane | Where-Object Active $right = $left | Split-TmuxPane -Horizontal $logs = $session | New-TmuxWindow -Name logs
# Type a command into the new pane and wait for what it prints. $right | Send-TmuxText -Text "printf 'hello from %s\n' tmux" -Enter $found = $right | Wait-TmuxPaneText -Pattern 'hello from tmux' -Timeout 10 if (-not $found.Found) { throw 'the pane never showed the output' }
# Move the focus an attached client sees: the pane, then the window. $request = [LibTmux.SelectPaneRequest]::new() $right = $right.SelectAsync($request).GetAwaiter().GetResult() $logs = $logs.SelectAsync().GetAwaiter().GetResult()
# Walk the objects: down from the server, then up from one pane. $snapshot = $server | Get-TmuxSnapshot foreach ($each in $snapshot.Sessions) { "session $($each.Name)" foreach ($window in $each.Windows) { ' window {0}:{1}: {2}' -f $window.Index, $window.Name, ($window.Panes.Id -join ' ') } } $pane = $snapshot.Panes | Where-Object Id -eq $right.Id $window = $pane.Window $owner = $pane.Session "$($pane.Id) is in window $($window.Name) of session $($owner.Name)"} catch { $failure = [InvalidOperationException]::new( "tmux quickstart failed: $($_.Exception.Message)", $_.Exception) throw $failure}$ErrorActionPreference = 'Stop'Import-Module "$PSScriptRoot/modules/LibTmux/0.1.0/LibTmux.psd1"
$session = $null$failure = $nulltry { # A private server: a socket and an empty config of its own, so this # neither touches nor is changed by a tmux you already use. # The process ID in the socket name keeps one run apart from the next. $socket = 'libtmux-home-' + $PID $server = New-TmuxServer -SocketName $socket -ConfigurationFile /dev/null $session = $server | New-TmuxSession -Name demo
# Lay out the session: name its window, split it, add a second window. $window = $session | Get-TmuxWindow | Where-Object Active $editor = $window.RenameAsync('editor').GetAwaiter().GetResult() $left = $editor | Get-TmuxPane | Where-Object Active $right = $left | Split-TmuxPane -Horizontal $logs = $session | New-TmuxWindow -Name logs
# Type a command into the new pane and wait for what it prints. $right | Send-TmuxText -Text "printf 'hello from %s\n' tmux" -Enter $found = $right | Wait-TmuxPaneText -Pattern 'hello from tmux' -Timeout 10 if (-not $found.Found) { throw 'the pane never showed the output' }
# Move the focus an attached client sees: the pane, then the window. $request = [LibTmux.SelectPaneRequest]::new() $right = $right.SelectAsync($request).GetAwaiter().GetResult() $logs = $logs.SelectAsync().GetAwaiter().GetResult()
# Walk the objects: down from the server, then up from one pane. $snapshot = $server | Get-TmuxSnapshot foreach ($each in $snapshot.Sessions) { "session $($each.Name)" foreach ($window in $each.Windows) { ' window {0}:{1}: {2}' -f $window.Index, $window.Name, ($window.Panes.Id -join ' ') } } $pane = $snapshot.Panes | Where-Object Id -eq $right.Id $window = $pane.Window $owner = $pane.Session "$($pane.Id) is in window $($window.Name) of session $($owner.Name)"} catch { $failure = $_.Exception throw} finally { if ($session) { $cleanupErrors = @() $session | Remove-TmuxSession -Confirm:$false ` -ErrorAction SilentlyContinue -ErrorVariable cleanupErrors if ($cleanupErrors) { if ($failure) { $errors = @($failure) + $cleanupErrors.Exception throw [AggregateException]::new( 'tmux operation and cleanup failed.', [Exception[]]$errors) } throw $cleanupErrors[0] } }}$ErrorActionPreference = 'Stop'Import-Module "$PSScriptRoot/modules/LibTmux/0.1.0/LibTmux.psd1"
$session = $null$failure = $nulltry { # A private server: a socket and an empty config of its own, so this # neither touches nor is changed by a tmux you already use. # The process ID in the socket name keeps one run apart from the next. $socket = 'libtmux-home-' + $PID $server = New-TmuxServer -SocketName $socket -ConfigurationFile /dev/null $session = $server | New-TmuxSession -Name demo
# Lay out the session: name its window, split it, add a second window. $window = $session | Get-TmuxWindow | Where-Object Active $editor = $window.RenameAsync('editor').GetAwaiter().GetResult() $left = $editor | Get-TmuxPane | Where-Object Active $right = $left | Split-TmuxPane -Horizontal $logs = $session | New-TmuxWindow -Name logs
# Type a command into the new pane and wait for what it prints. $right | Send-TmuxText -Text "printf 'hello from %s\n' tmux" -Enter $found = $right | Wait-TmuxPaneText -Pattern 'hello from tmux' -Timeout 10 if (-not $found.Found) { throw 'the pane never showed the output' }
# Move the focus an attached client sees: the pane, then the window. $request = [LibTmux.SelectPaneRequest]::new() $right = $right.SelectAsync($request).GetAwaiter().GetResult() $logs = $logs.SelectAsync().GetAwaiter().GetResult()
# Walk the objects: down from the server, then up from one pane. $snapshot = $server | Get-TmuxSnapshot foreach ($each in $snapshot.Sessions) { "session $($each.Name)" foreach ($window in $each.Windows) { ' window {0}:{1}: {2}' -f $window.Index, $window.Name, ($window.Panes.Id -join ' ') } } $pane = $snapshot.Panes | Where-Object Id -eq $right.Id $window = $pane.Window $owner = $pane.Session "$($pane.Id) is in window $($window.Name) of session $($owner.Name)"} catch { $failure = [InvalidOperationException]::new( "tmux quickstart failed: $($_.Exception.Message)", $_.Exception) throw $failure} finally { if ($session) { $cleanupErrors = @() $session | Remove-TmuxSession -Confirm:$false ` -ErrorAction SilentlyContinue -ErrorVariable cleanupErrors if ($cleanupErrors) { if ($failure) { $errors = @($failure) + $cleanupErrors.Exception throw [AggregateException]::new( 'tmux operation and cleanup failed.', [Exception[]]$errors) } throw $cleanupErrors[0] } }}Run this example
PowerShell 7.4.20 with PSResourceGet 1.1.1, POSIX shell and tmux on Linux.
Save the program above as quickstart.ps1 in a new directory, along with the files below.
Cleanup is omitted; the private tmux server and its temporary files may remain. Select Cleanup to remove them when the program finishes. The program stops its private tmux server and removes any temporary files it created when it finishes. Error handling adds diagnostics; every version checks required results and deadlines.
Setup and run
pwsh -NoLogo -NoProfile -Command ' $ErrorActionPreference = "Stop" $null = New-Item -ItemType Directory -Path ./modules -Force Save-PSResource -Name LibTmux -Version 0.1.0 ` -Path ./modules -TrustRepository'unset TMUX TMUX_PANEexport ENV=/dev/null BASH_ENV=/dev/null SHELL=/bin/shpwsh -NoLogo -NoProfile -File quickstart.ps1Expected output
session demo window 0:editor: %0 %1 window 1:logs: %2%1 is in window editor of session demoInstall-Module -Name LibTmuxRequires PowerShell 7.4 or later and tmux on the same Unix host.
Install-PSResource -Name LibTmuxRequires PowerShell 7.4 or later and tmux on the same Unix host.
Start with Julia
using LibTmux
# A private server: a socket and an empty config of its own, so this# neither touches nor is changed by a tmux you already use.owned = open_server()server = owned.server
demo = new_session(server; name="demo")
# Lay out the session: name its window, split it, add a second window.editor = only(windows(snapshot(server, demo))).refrename_window(server, editor, "editor")left = only(filter(p -> p.active, panes(snapshot(server, editor)))).refright = split_window(server, left; direction=:right)logs = new_window(server, demo; name="logs")
# Type a command into the new pane and wait for what it prints.send_keys(server, right, "printf 'hello from %s\\n' tmux", "Enter")wait_for_text(server, right, "hello from tmux"; baseline=true)
# Move the focus an attached client sees: the pane, then the window.select_pane(server, right)select_window(server, WindowLinkRef(demo, logs, 1))
# Walk the objects: down from the server, then up from one pane.snap = snapshot(server)listed = sessions(snap)for each in listed println("session ", each.name) links = windowlinks(each) wins = [window(link) for link in links] for (link, win) in zip(links, wins) members = panes(win) ids = join((string(p.id) for p in members), " ") println(" window ", link.index, ":", win.name, ": ", ids) endendpane = snap[right]home = window(pane)owner = session(only(windowlinks(home)))println(string(pane.id), " is in window ", home.name, " of session ", owner.name)using LibTmux
try # A private server: a socket and an empty config of its own, so this # neither touches nor is changed by a tmux you already use. owned = open_server() server = owned.server
demo = new_session(server; name="demo")
# Lay out the session: name its window, split it, add a second window. editor = only(windows(snapshot(server, demo))).ref rename_window(server, editor, "editor") left = only(filter(p -> p.active, panes(snapshot(server, editor)))).ref right = split_window(server, left; direction=:right) logs = new_window(server, demo; name="logs")
# Type a command into the new pane and wait for what it prints. send_keys(server, right, "printf 'hello from %s\\n' tmux", "Enter") wait_for_text(server, right, "hello from tmux"; baseline=true)
# Move the focus an attached client sees: the pane, then the window. select_pane(server, right) select_window(server, WindowLinkRef(demo, logs, 1))
# Walk the objects: down from the server, then up from one pane. snap = snapshot(server) listed = sessions(snap) for each in listed println("session ", each.name) links = windowlinks(each) wins = [window(link) for link in links] for (link, win) in zip(links, wins) members = panes(win) ids = join((string(p.id) for p in members), " ") println(" window ", link.index, ":", win.name, ": ", ids) end end pane = snap[right] home = window(pane) owner = session(only(windowlinks(home))) println(string(pane.id), " is in window ", home.name, " of session ", owner.name)catch error println(stderr, "tmux quickstart failed: ", sprint(showerror, error)) rethrow()endusing LibTmux
# A private server: a socket and an empty config of its own, so this# neither touches nor is changed by a tmux you already use.with_server() do server demo = new_session(server; name="demo")
# Lay out the session: name its window, split it, add a second window. editor = only(windows(snapshot(server, demo))).ref rename_window(server, editor, "editor") left = only(filter(p -> p.active, panes(snapshot(server, editor)))).ref right = split_window(server, left; direction=:right) logs = new_window(server, demo; name="logs")
# Type a command into the new pane and wait for what it prints. send_keys(server, right, "printf 'hello from %s\\n' tmux", "Enter") wait_for_text(server, right, "hello from tmux"; baseline=true)
# Move the focus an attached client sees: the pane, then the window. select_pane(server, right) select_window(server, WindowLinkRef(demo, logs, 1))
# Walk the objects: down from the server, then up from one pane. snap = snapshot(server) listed = sessions(snap) for each in listed println("session ", each.name) links = windowlinks(each) wins = [window(link) for link in links] for (link, win) in zip(links, wins) members = panes(win) ids = join((string(p.id) for p in members), " ") println(" window ", link.index, ":", win.name, ": ", ids) end end pane = snap[right] home = window(pane) owner = session(only(windowlinks(home))) println(string(pane.id), " is in window ", home.name, " of session ", owner.name)endusing LibTmux
try # A private server: a socket and an empty config of its own, so this # neither touches nor is changed by a tmux you already use. with_server() do server demo = new_session(server; name="demo")
# Lay out the session: name its window, split it, add a second window. editor = only(windows(snapshot(server, demo))).ref rename_window(server, editor, "editor") left = only(filter(p -> p.active, panes(snapshot(server, editor)))).ref right = split_window(server, left; direction=:right) logs = new_window(server, demo; name="logs")
# Type a command into the new pane and wait for what it prints. send_keys(server, right, "printf 'hello from %s\\n' tmux", "Enter") wait_for_text(server, right, "hello from tmux"; baseline=true)
# Move the focus an attached client sees: the pane, then the window. select_pane(server, right) select_window(server, WindowLinkRef(demo, logs, 1))
# Walk the objects: down from the server, then up from one pane. snap = snapshot(server) listed = sessions(snap) for each in listed println("session ", each.name) links = windowlinks(each) wins = [window(link) for link in links] for (link, win) in zip(links, wins) members = panes(win) ids = join((string(p.id) for p in members), " ") println(" window ", link.index, ":", win.name, ": ", ids) end end pane = snap[right] home = window(pane) owner = session(only(windowlinks(home))) println(string(pane.id), " is in window ", home.name, " of session ", owner.name) endcatch error println(stderr, "tmux quickstart failed: ", sprint(showerror, error)) rethrow()endRun this example
Julia 1.13.0, Git, POSIX shell and tmux on Linux.
Save the program above as quickstart.jl in a new directory, along with the files below.
Cleanup is omitted; the private tmux server and its temporary files may remain. Select Cleanup to remove them when the program finishes. The program stops its private tmux server and removes any temporary files it created when it finishes. Error handling adds diagnostics; every version checks required results and deadlines.
Setup and run
git init -q sourcegit -C source fetch -q --depth=1 \ https://github.com/libtmux/libtmux-julia.git \ f2b0fb8e3c4d2e951579e9620cb3396dd5cdc59fgit -C source checkout -q --detach FETCH_HEADunset TMUX TMUX_PANEexport ENV=/dev/null BASH_ENV=/dev/null SHELL=/bin/shjulia --startup-file=no --project=source quickstart.jlExpected output
session demo window 0:editor: %0 %1 window 1:logs: %2%1 is in window editor of session demoRun in Julia with tmux on PATH. The package is not registered in General, so this installs from Git; Manifest.toml records the package tree hash.
Start with Erlang
-module(readme_demo).-moduledoc "Create a workspace, query its graph and preserve captured values.".-export([run/1]).-import_record(tmux_model, [pane]).
-spec run(binary()) -> map().run(Executable) -> {ok, Server, Ownership} = tmux_server:start_owned(#{executable => Executable}), try {ok, Session} = tmux_session:create(Server, #{name => <<"workspace">>, window_name => <<"editor">>, width => 120, height => 30, launch => #{argv => [<<"/bin/cat">>]}}), {ok, Worker} = tmux_window:create(Session, #{name => <<"workers">>, launch => #{argv => [<<"/bin/cat">>]}}), {ok, Right} = tmux_pane:split(Worker, #{direction => horizontal, launch => #{argv => [<<"/bin/cat">>]}}), {ok, _} = tmux_window:select_layout(Worker, even_horizontal), {ok, _} = tmux_pane:resize(Right, #{width => 40}), {ok, Snapshot} = tmux_server:snapshot(Server), Windows = tmux_select:windows(Snapshot), Workers = #{name => <<"workers">>, panes => #{count => 2, every => #{current_command => <<"cat">>}}}, {ok, Captured} = tmux_select:one(Workers, Windows), {ok, Children} = tmux_snapshot:related(panes, Captured, Snapshot), Ids = [Id || #pane{id = Id} <:- Children], 2 = length(Ids), Criteria = #{width => #{gte => 20}, window => #{is => #{name => <<"workers">>}}}, Query = tmux_query:where(Criteria, tmux_query:panes(Server)), {ok, Fetched} = tmux_query:fetch(Query), 2 = tmux_select:size(Fetched), {ok, _} = tmux_window:rename(Worker, <<"finished">>), <<"workers">> = tmux_model:get(name, Captured), {ok, Fresh} = tmux_query:fetch(tmux_query:where( #{name => <<"finished">>}, tmux_query:windows(Server))), {ok, Renamed} = tmux_select:one(Fresh), <<"finished">> = tmux_model:get(name, Renamed), 1 = length(tmux_snapshot:sessions(Snapshot)), 2 = length(tmux_snapshot:windows(Snapshot)), 3 = length(tmux_snapshot:panes(Snapshot)), #{sessions => 1, windows => 2, panes => 3, matched_panes => 2, captured_name => <<"workers">>, immutable => true} after ok = tmux_server:stop_owned(Ownership) end.-module(readme_demo).-moduledoc "Create a workspace, query its graph and preserve captured values.".-export([run/1]).-import_record(tmux_model, [pane]).
-spec run(binary()) -> map().run(Executable) -> {ok, Server, Ownership} = tmux_server:start_owned(#{executable => Executable}), try {ok, Session} = tmux_session:create(Server, #{name => <<"workspace">>, window_name => <<"editor">>, width => 120, height => 30, launch => #{argv => [<<"/bin/cat">>]}}), {ok, Worker} = tmux_window:create(Session, #{name => <<"workers">>, launch => #{argv => [<<"/bin/cat">>]}}), {ok, Right} = tmux_pane:split(Worker, #{direction => horizontal, launch => #{argv => [<<"/bin/cat">>]}}), {ok, _} = tmux_window:select_layout(Worker, even_horizontal), {ok, _} = tmux_pane:resize(Right, #{width => 40}), {ok, Snapshot} = tmux_server:snapshot(Server), Windows = tmux_select:windows(Snapshot), Workers = #{name => <<"workers">>, panes => #{count => 2, every => #{current_command => <<"cat">>}}}, {ok, Captured} = tmux_select:one(Workers, Windows), {ok, Children} = tmux_snapshot:related(panes, Captured, Snapshot), Ids = [Id || #pane{id = Id} <:- Children], 2 = length(Ids), Criteria = #{width => #{gte => 20}, window => #{is => #{name => <<"workers">>}}}, Query = tmux_query:where(Criteria, tmux_query:panes(Server)), {ok, Fetched} = tmux_query:fetch(Query), 2 = tmux_select:size(Fetched), {ok, _} = tmux_window:rename(Worker, <<"finished">>), <<"workers">> = tmux_model:get(name, Captured), {ok, Fresh} = tmux_query:fetch(tmux_query:where( #{name => <<"finished">>}, tmux_query:windows(Server))), {ok, Renamed} = tmux_select:one(Fresh), <<"finished">> = tmux_model:get(name, Renamed), 1 = length(tmux_snapshot:sessions(Snapshot)), 2 = length(tmux_snapshot:windows(Snapshot)), 3 = length(tmux_snapshot:panes(Snapshot)), #{sessions => 1, windows => 2, panes => 3, matched_panes => 2, captured_name => <<"workers">>, immutable => true} after ok = tmux_server:stop_owned(Ownership) end.-module(readme_demo).-moduledoc "Create a workspace, query its graph and preserve captured values.".-export([run/1]).-import_record(tmux_model, [pane]).
-spec run(binary()) -> map().run(Executable) -> {ok, Server, Ownership} = tmux_server:start_owned(#{executable => Executable}), try {ok, Session} = tmux_session:create(Server, #{name => <<"workspace">>, window_name => <<"editor">>, width => 120, height => 30, launch => #{argv => [<<"/bin/cat">>]}}), try {ok, Worker} = tmux_window:create(Session, #{name => <<"workers">>, launch => #{argv => [<<"/bin/cat">>]}}), {ok, Right} = tmux_pane:split(Worker, #{direction => horizontal, launch => #{argv => [<<"/bin/cat">>]}}), {ok, _} = tmux_window:select_layout(Worker, even_horizontal), {ok, _} = tmux_pane:resize(Right, #{width => 40}), {ok, Snapshot} = tmux_server:snapshot(Server), Windows = tmux_select:windows(Snapshot), Workers = #{name => <<"workers">>, panes => #{count => 2, every => #{current_command => <<"cat">>}}}, {ok, Captured} = tmux_select:one(Workers, Windows), {ok, Children} = tmux_snapshot:related(panes, Captured, Snapshot), Ids = [Id || #pane{id = Id} <:- Children], 2 = length(Ids), Criteria = #{width => #{gte => 20}, window => #{is => #{name => <<"workers">>}}}, Query = tmux_query:where(Criteria, tmux_query:panes(Server)), {ok, Fetched} = tmux_query:fetch(Query), 2 = tmux_select:size(Fetched), {ok, _} = tmux_window:rename(Worker, <<"finished">>), <<"workers">> = tmux_model:get(name, Captured), {ok, Fresh} = tmux_query:fetch(tmux_query:where( #{name => <<"finished">>}, tmux_query:windows(Server))), {ok, Renamed} = tmux_select:one(Fresh), <<"finished">> = tmux_model:get(name, Renamed), 1 = length(tmux_snapshot:sessions(Snapshot)), 2 = length(tmux_snapshot:windows(Snapshot)), 3 = length(tmux_snapshot:panes(Snapshot)), #{sessions => 1, windows => 2, panes => 3, matched_panes => 2, captured_name => <<"workers">>, immutable => true} after {ok, _} = tmux_session:kill(Session) end after ok = tmux_server:stop_owned(Ownership) end.-module(readme_demo).-moduledoc "Create a workspace, query its graph and preserve captured values.".-export([run/1]).-import_record(tmux_model, [pane]).
-spec run(binary()) -> map().run(Executable) -> {ok, Server, Ownership} = tmux_server:start_owned(#{executable => Executable}), try {ok, Session} = tmux_session:create(Server, #{name => <<"workspace">>, window_name => <<"editor">>, width => 120, height => 30, launch => #{argv => [<<"/bin/cat">>]}}), try {ok, Worker} = tmux_window:create(Session, #{name => <<"workers">>, launch => #{argv => [<<"/bin/cat">>]}}), {ok, Right} = tmux_pane:split(Worker, #{direction => horizontal, launch => #{argv => [<<"/bin/cat">>]}}), {ok, _} = tmux_window:select_layout(Worker, even_horizontal), {ok, _} = tmux_pane:resize(Right, #{width => 40}), {ok, Snapshot} = tmux_server:snapshot(Server), Windows = tmux_select:windows(Snapshot), Workers = #{name => <<"workers">>, panes => #{count => 2, every => #{current_command => <<"cat">>}}}, {ok, Captured} = tmux_select:one(Workers, Windows), {ok, Children} = tmux_snapshot:related(panes, Captured, Snapshot), Ids = [Id || #pane{id = Id} <:- Children], 2 = length(Ids), Criteria = #{width => #{gte => 20}, window => #{is => #{name => <<"workers">>}}}, Query = tmux_query:where(Criteria, tmux_query:panes(Server)), {ok, Fetched} = tmux_query:fetch(Query), 2 = tmux_select:size(Fetched), {ok, _} = tmux_window:rename(Worker, <<"finished">>), <<"workers">> = tmux_model:get(name, Captured), {ok, Fresh} = tmux_query:fetch(tmux_query:where( #{name => <<"finished">>}, tmux_query:windows(Server))), {ok, Renamed} = tmux_select:one(Fresh), <<"finished">> = tmux_model:get(name, Renamed), 1 = length(tmux_snapshot:sessions(Snapshot)), 2 = length(tmux_snapshot:windows(Snapshot)), 3 = length(tmux_snapshot:panes(Snapshot)), #{sessions => 1, windows => 2, panes => 3, matched_panes => 2, captured_name => <<"workers">>, immutable => true} after {ok, _} = tmux_session:kill(Session) end after ok = tmux_server:stop_owned(Ownership) end.Run this example
Linux, tmux 3.3a–3.8, Erlang/OTP 29.1.2, Rebar3 3.28.0, Git, make and a C11 compiler. Save the displayed files in an empty project directory.
Save the program above as src/readme_demo.erl in a new directory, along with the files below.
Every version retires its owned server in try/after. Cleanup also removes the created session explicitly. The program stops its private tmux server and removes any temporary files it created when it finishes. Unmatched tagged results raise with a stack trace. The program propagates failures through try/after cleanup.
rebar.config
{minimum_otp_vsn, "29.1.2"}.{erl_opts, [debug_info, warnings_as_errors]}.{deps, [ {libtmux_erlang, {git_subdir, "https://github.com/libtmux/libtmux-erlang.git", {ref, "9a1ca749f7bf6f082c910c99f961bb586781ab0b"}, "apps/libtmux_erlang"}}]}.src/tmux_example.app.src
{application, tmux_example, [ {vsn, "0.1.0"}, {applications, [kernel, stdlib, libtmux_erlang]}, {modules, []}]}.Setup and run
rebar3 compileenv \ -u TMUX \ -u TMUX_PANE \ erl \ -noshell \ -pa _build/default/lib/tmux_example/ebin \ -pa _build/default/lib/libtmux_erlang/apps/libtmux_erlang/ebin \ -eval ' {ok, _} = application:ensure_all_started(libtmux_erlang), Tmux = unicode:characters_to_binary(os:find_executable("tmux")), Stats = readme_demo:run(Tmux), io:format("~B session, ~B windows, ~B panes; ~B matches~n", [ maps:get(sessions, Stats), maps:get(windows, Stats), maps:get(panes, Stats), maps:get(matched_panes, Stats)]), halt().'Expected output
1 session, 2 windows, 3 panes; 2 matchesrebar.config
rebar3 compileMerge this deps entry into rebar.config. Requires Erlang/OTP 29.1.2, Rebar3 3.28.0, Linux, tmux 3.3a–3.8, make and a C11 compiler. Commit rebar.lock to retain the resolved Git revision. The application is unreleased; no Hex package is advertised.
Start with Elixir
Mix.install([{:libtmux, "0.1.1"}])
alias LibTmux.{Command, Pane, Ref, Selection, Server, Session, Snapshot, Window}
tmux = System.find_executable("tmux") || raise "tmux is not on PATH"id = Base.encode16(:crypto.strong_rand_bytes(8), case: :lower)dir = Path.join(System.tmp_dir!(), "libtmux-" <> id)socket = Path.join(dir, "tmux.sock")File.mkdir!(dir)File.chmod!(dir, 0o700)
# libtmux works on a running server, so tmux itself starts the private one.create = ["new-session", "-d", "-s", "demo"]{_, 0} = System.cmd(tmux, ["-S", socket, "-f", "/dev/null" | create])server = Server.new(executable: tmux, socket: socket)
# Lay out the session: name its window, split it, add a second window.snapshot = Server.snapshot!(server)session = snapshot |> Snapshot.sessions() |> Selection.one!()editor = Session.active_window(snapshot, session){:ok, session_ref} = Ref.from_observation(session){:ok, editor_ref} = Ref.from_observation(editor)Window.rename!(server, editor_ref, "editor")left = snapshot |> Snapshot.panes() |> Selection.one!(window_id: editor.id, active: true){:ok, left_ref} = Ref.from_observation(left)%{id: right_id} = Pane.split!(server, left_ref, axis: :horizontal)%{id: logs_id} = Session.new_window!(server, session_ref, "logs"){:ok, right} = Ref.new(:pane, right_id, session.server_instance)
# Type a command into the new pane and wait for what it prints.Pane.send_text!(server, right, "printf 'hello from %s\\n' tmux")Pane.send_keys!(server, right, ["Enter"])
shown = Enum.find_value(1..250, fn _ -> screen = Pane.capture!(server, right) screen =~ "hello from tmux" || (Process.sleep(20) && nil) end)
shown || raise "the pane did not print hello from tmux"
# Move the focus an attached client sees: the pane, then the window.select_pane = Command.new("select-pane", ["-t", right_id])select_window = Command.new("select-window", ["-t", logs_id]){:ok, _} = Server.run(server, select_pane){:ok, _} = Server.run(server, select_window)
# Walk the objects: down from the server, then up from one pane.snapshot = Server.snapshot!(server)sessions = Snapshot.sessions(snapshot)
for each <- sessions do IO.puts("session #{each.name}") links = Snapshot.related(snapshot, :session, each.id, :window_links)
for link <- Enum.sort_by(links, & &1.index) do {:ok, window} = Snapshot.fetch(snapshot, :window, link.window_id) panes = Window.panes(snapshot, window) ids = Enum.map_join(panes, " ", & &1.id) IO.puts(" window #{link.index}:#{window.name}: #{ids}") endend
pane = snapshot |> Snapshot.panes() |> Selection.one!(id: right_id)window = Snapshot.related(snapshot, :pane, pane.id, :window)[owner] = Snapshot.related(snapshot, :window, window.id, :sessions)IO.puts("#{pane.id} is in window #{window.name} of session #{owner.name}")Mix.install([{:libtmux, "0.1.1"}])
alias LibTmux.{Command, Pane, Ref, Selection, Server, Session, Snapshot, Window}
tmux = System.find_executable("tmux") || raise "tmux is not on PATH"id = Base.encode16(:crypto.strong_rand_bytes(8), case: :lower)dir = Path.join(System.tmp_dir!(), "libtmux-" <> id)socket = Path.join(dir, "tmux.sock")File.mkdir!(dir)File.chmod!(dir, 0o700)
# libtmux works on a running server, so tmux itself starts the private one.create = ["new-session", "-d", "-s", "demo"]{_, 0} = System.cmd(tmux, ["-S", socket, "-f", "/dev/null" | create])server = Server.new(executable: tmux, socket: socket)
# Lay out the session: name its window, split it, add a second window.snapshot = Server.snapshot!(server)session = snapshot |> Snapshot.sessions() |> Selection.one!()editor = Session.active_window(snapshot, session){:ok, session_ref} = Ref.from_observation(session){:ok, editor_ref} = Ref.from_observation(editor)Window.rename!(server, editor_ref, "editor")left = snapshot |> Snapshot.panes() |> Selection.one!(window_id: editor.id, active: true){:ok, left_ref} = Ref.from_observation(left)%{id: right_id} = Pane.split!(server, left_ref, axis: :horizontal)%{id: logs_id} = Session.new_window!(server, session_ref, "logs"){:ok, right} = Ref.new(:pane, right_id, session.server_instance)
# Type a command into the new pane and wait for what it prints.Pane.send_text!(server, right, "printf 'hello from %s\\n' tmux")Pane.send_keys!(server, right, ["Enter"])
shown = Enum.find_value(1..250, fn _ -> screen = Pane.capture!(server, right) screen =~ "hello from tmux" || (Process.sleep(20) && nil) end)
shown || raise "the pane did not print hello from tmux"
# Move the focus an attached client sees: the pane, then the window.select_pane = Command.new("select-pane", ["-t", right_id])select_window = Command.new("select-window", ["-t", logs_id]){:ok, _} = Server.run(server, select_pane){:ok, _} = Server.run(server, select_window)
# Walk the objects: down from the server, then up from one pane.snapshot = Server.snapshot!(server)sessions = Snapshot.sessions(snapshot)
for each <- sessions do IO.puts("session #{each.name}") links = Snapshot.related(snapshot, :session, each.id, :window_links)
for link <- Enum.sort_by(links, & &1.index) do {:ok, window} = Snapshot.fetch(snapshot, :window, link.window_id) panes = Window.panes(snapshot, window) ids = Enum.map_join(panes, " ", & &1.id) IO.puts(" window #{link.index}:#{window.name}: #{ids}") endend
pane = snapshot |> Snapshot.panes() |> Selection.one!(id: right_id)window = Snapshot.related(snapshot, :pane, pane.id, :window)[owner] = Snapshot.related(snapshot, :window, window.id, :sessions)IO.puts("#{pane.id} is in window #{window.name} of session #{owner.name}")Mix.install([{:libtmux, "0.1.1"}])
alias LibTmux.{Command, Pane, Ref, Selection, Server, Session, Snapshot, Window}
tmux = System.find_executable("tmux") || raise "tmux is not on PATH"id = Base.encode16(:crypto.strong_rand_bytes(8), case: :lower)dir = Path.join(System.tmp_dir!(), "libtmux-" <> id)socket = Path.join(dir, "tmux.sock")File.mkdir!(dir)File.chmod!(dir, 0o700)
try do # libtmux works on a running server, so tmux itself starts the private one. create = ["new-session", "-d", "-s", "demo"] {_, 0} = System.cmd(tmux, ["-S", socket, "-f", "/dev/null" | create]) server = Server.new(executable: tmux, socket: socket)
# Lay out the session: name its window, split it, add a second window. snapshot = Server.snapshot!(server) session = snapshot |> Snapshot.sessions() |> Selection.one!() editor = Session.active_window(snapshot, session) {:ok, session_ref} = Ref.from_observation(session) {:ok, editor_ref} = Ref.from_observation(editor) Window.rename!(server, editor_ref, "editor") left = snapshot |> Snapshot.panes() |> Selection.one!(window_id: editor.id, active: true) {:ok, left_ref} = Ref.from_observation(left) %{id: right_id} = Pane.split!(server, left_ref, axis: :horizontal) %{id: logs_id} = Session.new_window!(server, session_ref, "logs") {:ok, right} = Ref.new(:pane, right_id, session.server_instance)
# Type a command into the new pane and wait for what it prints. Pane.send_text!(server, right, "printf 'hello from %s\\n' tmux") Pane.send_keys!(server, right, ["Enter"])
shown = Enum.find_value(1..250, fn _ -> screen = Pane.capture!(server, right) screen =~ "hello from tmux" || (Process.sleep(20) && nil) end)
shown || raise "the pane did not print hello from tmux"
# Move the focus an attached client sees: the pane, then the window. select_pane = Command.new("select-pane", ["-t", right_id]) select_window = Command.new("select-window", ["-t", logs_id]) {:ok, _} = Server.run(server, select_pane) {:ok, _} = Server.run(server, select_window)
# Walk the objects: down from the server, then up from one pane. snapshot = Server.snapshot!(server) sessions = Snapshot.sessions(snapshot)
for each <- sessions do IO.puts("session #{each.name}") links = Snapshot.related(snapshot, :session, each.id, :window_links)
for link <- Enum.sort_by(links, & &1.index) do {:ok, window} = Snapshot.fetch(snapshot, :window, link.window_id) panes = Window.panes(snapshot, window) ids = Enum.map_join(panes, " ", & &1.id) IO.puts(" window #{link.index}:#{window.name}: #{ids}") end end
pane = snapshot |> Snapshot.panes() |> Selection.one!(id: right_id) window = Snapshot.related(snapshot, :pane, pane.id, :window) [owner] = Snapshot.related(snapshot, :window, window.id, :sessions) IO.puts("#{pane.id} is in window #{window.name} of session #{owner.name}")after System.cmd(tmux, ["-S", socket, "kill-server"], stderr_to_stdout: true) File.rm_rf(dir)endMix.install([{:libtmux, "0.1.1"}])
alias LibTmux.{Command, Pane, Ref, Selection, Server, Session, Snapshot, Window}
tmux = System.find_executable("tmux") || raise "tmux is not on PATH"id = Base.encode16(:crypto.strong_rand_bytes(8), case: :lower)dir = Path.join(System.tmp_dir!(), "libtmux-" <> id)socket = Path.join(dir, "tmux.sock")File.mkdir!(dir)File.chmod!(dir, 0o700)
try do # libtmux works on a running server, so tmux itself starts the private one. create = ["new-session", "-d", "-s", "demo"] {_, 0} = System.cmd(tmux, ["-S", socket, "-f", "/dev/null" | create]) server = Server.new(executable: tmux, socket: socket)
# Lay out the session: name its window, split it, add a second window. snapshot = Server.snapshot!(server) session = snapshot |> Snapshot.sessions() |> Selection.one!() editor = Session.active_window(snapshot, session) {:ok, session_ref} = Ref.from_observation(session) {:ok, editor_ref} = Ref.from_observation(editor) Window.rename!(server, editor_ref, "editor") left = snapshot |> Snapshot.panes() |> Selection.one!(window_id: editor.id, active: true) {:ok, left_ref} = Ref.from_observation(left) %{id: right_id} = Pane.split!(server, left_ref, axis: :horizontal) %{id: logs_id} = Session.new_window!(server, session_ref, "logs") {:ok, right} = Ref.new(:pane, right_id, session.server_instance)
# Type a command into the new pane and wait for what it prints. Pane.send_text!(server, right, "printf 'hello from %s\\n' tmux") Pane.send_keys!(server, right, ["Enter"])
shown = Enum.find_value(1..250, fn _ -> screen = Pane.capture!(server, right) screen =~ "hello from tmux" || (Process.sleep(20) && nil) end)
shown || raise "the pane did not print hello from tmux"
# Move the focus an attached client sees: the pane, then the window. select_pane = Command.new("select-pane", ["-t", right_id]) select_window = Command.new("select-window", ["-t", logs_id]) {:ok, _} = Server.run(server, select_pane) {:ok, _} = Server.run(server, select_window)
# Walk the objects: down from the server, then up from one pane. snapshot = Server.snapshot!(server) sessions = Snapshot.sessions(snapshot)
for each <- sessions do IO.puts("session #{each.name}") links = Snapshot.related(snapshot, :session, each.id, :window_links)
for link <- Enum.sort_by(links, & &1.index) do {:ok, window} = Snapshot.fetch(snapshot, :window, link.window_id) panes = Window.panes(snapshot, window) ids = Enum.map_join(panes, " ", & &1.id) IO.puts(" window #{link.index}:#{window.name}: #{ids}") end end
pane = snapshot |> Snapshot.panes() |> Selection.one!(id: right_id) window = Snapshot.related(snapshot, :pane, pane.id, :window) [owner] = Snapshot.related(snapshot, :window, window.id, :sessions) IO.puts("#{pane.id} is in window #{window.name} of session #{owner.name}")after System.cmd(tmux, ["-S", socket, "kill-server"], stderr_to_stdout: true) File.rm_rf(dir)endRun this example
POSIX shell, tmux 3.3 or newer, Elixir 1.20.4 or newer, Erlang/OTP 29.1.2 or a newer 29.x release, access to hex.pm, and a C11 compiler on Linux.
Save the program above as quickstart.exs in a new directory, along with the files below.
Cleanup is omitted; the private tmux server and its temporary files may remain. Select Cleanup to remove them when the program finishes. The program stops its private tmux server and removes any temporary files it created when it finishes. An unmatched result or a raised error ends the script with its message and stack trace, so there is no separate error handling to add. Every version checks required results.
Setup and run
unset TMUX TMUX_PANEexport ENV=/dev/null BASH_ENV=/dev/null SHELL=/bin/shelixir quickstart.exsExpected output
session demo window 0:editor: %0 %1 window 1:logs: %2%1 is in window editor of session demomix.exs
{:libtmux, "~> 0.1.1"}mix deps.getAdd the tuple to the deps list in mix.exs, then fetch it. Needs Elixir 1.20.4 or newer, Erlang/OTP 29.1.2 or a newer 29.x release, tmux 3.3 or newer (the planned floor), and a C11 compiler on Linux.
Start with Haskell
{-# LANGUAGE OverloadedStrings #-}
-- | Construct tmux domain values without starting a process-- or contacting a server.module Main (main) where
import LibTmux.Id (parseWindowId, renderWindowId)import LibTmux.Value (dimensionValue, mkDimension)import LibTmux.Version (parseVersion, renderVersion, requireSupported)
main :: IO ()main = do version <- either (fail . show) pure $ parseVersion "tmux 3.3a\n" >>= requireSupported window <- either (fail . show) pure (parseWindowId "@17") width <- either (fail . show) pure (mkDimension 120) print (renderVersion version, renderWindowId window, dimensionValue width)Run this example
Linux x86_64, GHC 9.14.1, Cabal 3.18.2.0, Git, a C11 compiler, and network access to GitHub and Hackage for source dependencies. No running tmux server is required.
Save the program above as Main.hs in a new directory, along with the files below.
This program validates supplied values and prints the result. It does not start tmux or create resources requiring cleanup.
libtmux-typed-values.cabal
cabal-version: 3.18name: libtmux-typed-valuesversion: 0.0.0build-type: Simplelicense: MIT
executable typed-values main-is: Main.hs default-language: GHC2024 ghc-options: -Wall -Werror build-depends: base >=4.22 && <4.23, libtmux-haskell ^>=0.1.0.0cabal.project
packages: .index-state: 2026-11-06T00:00:00Z
source-repository-package type: git location: https://github.com/libtmux/libtmux-haskell tag: 581f0ee45016ffb2283366bb1edc1658df26c5edSetup and run
cabal updatecabal run --verbose=0 typed-valuesExpected output
("3.3a","@17",120)cabal.project
Save as cabal.project and add libtmux-haskell ^>=0.1.0.0 to your component's build-depends. Requires Linux x86_64, GHC 9.14.1 and Cabal 3.18.2.0. The core package is available from source; it is not published on Hackage.
Start with Common Lisp
(require :asdf)
(defparameter *source-root* (or (uiop:getenv "LIBTMUX_SOURCE") "."))(defparameter *program* (or (uiop:getenv "LIBTMUX_PROGRAM") "tmux"))(defparameter *socket-path* (or (uiop:getenv "LIBTMUX_EXAMPLE_SOCKET") (error "Set LIBTMUX_EXAMPLE_SOCKET to the owned tmux socket path")))
(asdf:load-asd (truename (merge-pathnames "libtmux.asd" (uiop:ensure-directory-pathname *source-root*))))(asdf:load-system "libtmux")
(defun observed-value (outcome) "Return OUTCOME's observed value, or signal its observation failure." (when (libtmux:outcome-observation-error outcome) (error (libtmux:outcome-observation-error outcome))) (multiple-value-bind (value present-p) (libtmux:outcome-value outcome) (unless present-p (error "The operation did not return an observation")) value))
(libtmux:with-client (client :program *program* :socket-path *socket-path* :config-file "/dev/null") (let* ((before (libtmux:fetch-snapshot client)) (demo (find "demo" (libtmux:sessions before) :key #'libtmux:name :test #'string=)) (editor-link (aref (libtmux:window-links demo) 0)) (editor (libtmux:window editor-link)) (left (aref (libtmux:panes editor) 0)) (right (observed-value (libtmux:split-pane client left :direction :horizontal :command '("/bin/cat")))) (logs (observed-value (libtmux:new-window client demo :name "logs" :command '("/bin/cat"))))) (declare (ignore logs)) (libtmux:send-text client right "hello from tmux" :enter t) (multiple-value-bind (text outcome) (libtmux:capture-pane client right) (assert (eq :succeeded (libtmux:outcome-status outcome))) (assert (search "hello from tmux" text))) (let* ((snapshot (libtmux:fetch-snapshot client)) (pane (find (libtmux:id right) (libtmux:panes snapshot) :key #'libtmux:id :test #'string=)) (window (libtmux:window pane)) (owner-link (aref (libtmux:window-links window) 0)) (owner (libtmux:session owner-link))) (loop for session across (libtmux:sessions snapshot) do (format t "session ~A~%" (libtmux:name session)) (loop for link across (libtmux:window-links session) for each = (libtmux:window link) do (format t " window ~D:~A:" (libtmux:index link) (libtmux:name each)) (loop for item across (libtmux:panes each) do (format t " ~A" (libtmux:id item))) (terpri))) (format t "~A is in window ~A of session ~A~%" (libtmux:id pane) (libtmux:name window) (libtmux:name owner)))) (libtmux:kill-server client))(require :asdf)
(defparameter *source-root* (or (uiop:getenv "LIBTMUX_SOURCE") "."))(defparameter *program* (or (uiop:getenv "LIBTMUX_PROGRAM") "tmux"))(defparameter *socket-path* (or (uiop:getenv "LIBTMUX_EXAMPLE_SOCKET") (error "Set LIBTMUX_EXAMPLE_SOCKET to the owned tmux socket path")))
(asdf:load-asd (truename (merge-pathnames "libtmux.asd" (uiop:ensure-directory-pathname *source-root*))))(asdf:load-system "libtmux")
(defun observed-value (outcome) "Return OUTCOME's observed value, or signal its observation failure." (when (libtmux:outcome-observation-error outcome) (error (libtmux:outcome-observation-error outcome))) (multiple-value-bind (value present-p) (libtmux:outcome-value outcome) (unless present-p (error "The operation did not return an observation")) value))
(libtmux:with-client (client :program *program* :socket-path *socket-path* :config-file "/dev/null") (let* ((before (libtmux:fetch-snapshot client)) (demo (find "demo" (libtmux:sessions before) :key #'libtmux:name :test #'string=)) (editor-link (aref (libtmux:window-links demo) 0)) (editor (libtmux:window editor-link)) (left (aref (libtmux:panes editor) 0)) (right (observed-value (libtmux:split-pane client left :direction :horizontal :command '("/bin/cat")))) (logs (observed-value (libtmux:new-window client demo :name "logs" :command '("/bin/cat"))))) (declare (ignore logs)) (libtmux:send-text client right "hello from tmux" :enter t) (multiple-value-bind (text outcome) (libtmux:capture-pane client right) (assert (eq :succeeded (libtmux:outcome-status outcome))) (assert (search "hello from tmux" text))) (let* ((snapshot (libtmux:fetch-snapshot client)) (pane (find (libtmux:id right) (libtmux:panes snapshot) :key #'libtmux:id :test #'string=)) (window (libtmux:window pane)) (owner-link (aref (libtmux:window-links window) 0)) (owner (libtmux:session owner-link))) (loop for session across (libtmux:sessions snapshot) do (format t "session ~A~%" (libtmux:name session)) (loop for link across (libtmux:window-links session) for each = (libtmux:window link) do (format t " window ~D:~A:" (libtmux:index link) (libtmux:name each)) (loop for item across (libtmux:panes each) do (format t " ~A" (libtmux:id item))) (terpri))) (format t "~A is in window ~A of session ~A~%" (libtmux:id pane) (libtmux:name window) (libtmux:name owner)))) (libtmux:kill-server client))(require :asdf)
(defparameter *source-root* (or (uiop:getenv "LIBTMUX_SOURCE") "."))(defparameter *program* (or (uiop:getenv "LIBTMUX_PROGRAM") "tmux"))(defparameter *socket-path* (or (uiop:getenv "LIBTMUX_EXAMPLE_SOCKET") (error "Set LIBTMUX_EXAMPLE_SOCKET to the owned tmux socket path")))
(asdf:load-asd (truename (merge-pathnames "libtmux.asd" (uiop:ensure-directory-pathname *source-root*))))(asdf:load-system "libtmux")
(defun observed-value (outcome) "Return OUTCOME's observed value, or signal its observation failure." (when (libtmux:outcome-observation-error outcome) (error (libtmux:outcome-observation-error outcome))) (multiple-value-bind (value present-p) (libtmux:outcome-value outcome) (unless present-p (error "The operation did not return an observation")) value))
(libtmux:with-client (client :program *program* :socket-path *socket-path* :config-file "/dev/null") (let ((normal nil)) (unwind-protect (multiple-value-prog1 (let* ((before (libtmux:fetch-snapshot client)) (demo (find "demo" (libtmux:sessions before) :key #'libtmux:name :test #'string=)) (editor-link (aref (libtmux:window-links demo) 0)) (editor (libtmux:window editor-link)) (left (aref (libtmux:panes editor) 0)) (right (observed-value (libtmux:split-pane client left :direction :horizontal :command '("/bin/cat")))) (logs (observed-value (libtmux:new-window client demo :name "logs" :command '("/bin/cat"))))) (declare (ignore logs)) (libtmux:send-text client right "hello from tmux" :enter t) (multiple-value-bind (text outcome) (libtmux:capture-pane client right) (assert (eq :succeeded (libtmux:outcome-status outcome))) (assert (search "hello from tmux" text))) (let* ((snapshot (libtmux:fetch-snapshot client)) (pane (find (libtmux:id right) (libtmux:panes snapshot) :key #'libtmux:id :test #'string=)) (window (libtmux:window pane)) (owner-link (aref (libtmux:window-links window) 0)) (owner (libtmux:session owner-link))) (loop for session across (libtmux:sessions snapshot) do (format t "session ~A~%" (libtmux:name session)) (loop for link across (libtmux:window-links session) for each = (libtmux:window link) do (format t " window ~D:~A:" (libtmux:index link) (libtmux:name each)) (loop for item across (libtmux:panes each) do (format t " ~A" (libtmux:id item))) (terpri))) (format t "~A is in window ~A of session ~A~%" (libtmux:id pane) (libtmux:name window) (libtmux:name owner)))) (setf normal t)) (handler-case (libtmux:kill-server client) (error (condition) (if normal (error condition) (warn "Owned server cleanup also failed: ~A" condition)))))))(require :asdf)
(defparameter *source-root* (or (uiop:getenv "LIBTMUX_SOURCE") "."))(defparameter *program* (or (uiop:getenv "LIBTMUX_PROGRAM") "tmux"))(defparameter *socket-path* (or (uiop:getenv "LIBTMUX_EXAMPLE_SOCKET") (error "Set LIBTMUX_EXAMPLE_SOCKET to the owned tmux socket path")))
(asdf:load-asd (truename (merge-pathnames "libtmux.asd" (uiop:ensure-directory-pathname *source-root*))))(asdf:load-system "libtmux")
(defun observed-value (outcome) "Return OUTCOME's observed value, or signal its observation failure." (when (libtmux:outcome-observation-error outcome) (error (libtmux:outcome-observation-error outcome))) (multiple-value-bind (value present-p) (libtmux:outcome-value outcome) (unless present-p (error "The operation did not return an observation")) value))
(libtmux:with-client (client :program *program* :socket-path *socket-path* :config-file "/dev/null") (let ((normal nil)) (unwind-protect (multiple-value-prog1 (let* ((before (libtmux:fetch-snapshot client)) (demo (find "demo" (libtmux:sessions before) :key #'libtmux:name :test #'string=)) (editor-link (aref (libtmux:window-links demo) 0)) (editor (libtmux:window editor-link)) (left (aref (libtmux:panes editor) 0)) (right (observed-value (libtmux:split-pane client left :direction :horizontal :command '("/bin/cat")))) (logs (observed-value (libtmux:new-window client demo :name "logs" :command '("/bin/cat"))))) (declare (ignore logs)) (libtmux:send-text client right "hello from tmux" :enter t) (multiple-value-bind (text outcome) (libtmux:capture-pane client right) (assert (eq :succeeded (libtmux:outcome-status outcome))) (assert (search "hello from tmux" text))) (let* ((snapshot (libtmux:fetch-snapshot client)) (pane (find (libtmux:id right) (libtmux:panes snapshot) :key #'libtmux:id :test #'string=)) (window (libtmux:window pane)) (owner-link (aref (libtmux:window-links window) 0)) (owner (libtmux:session owner-link))) (loop for session across (libtmux:sessions snapshot) do (format t "session ~A~%" (libtmux:name session)) (loop for link across (libtmux:window-links session) for each = (libtmux:window link) do (format t " window ~D:~A:" (libtmux:index link) (libtmux:name each)) (loop for item across (libtmux:panes each) do (format t " ~A" (libtmux:id item))) (terpri))) (format t "~A is in window ~A of session ~A~%" (libtmux:id pane) (libtmux:name window) (libtmux:name owner)))) (setf normal t)) (handler-case (libtmux:kill-server client) (error (condition) (if normal (error condition) (warn "Owned server cleanup also failed: ~A" condition)))))))Run this example
mise 2026.11.3, Git, POSIX shell and tmux 3.3a or newer on Linux x86-64. The source lock installs SBCL 2.6.10 and ASDF/UIOP 3.3.7.
Save the program above as quickstart.lisp in a new directory, along with the files below.
Cleanup is omitted; the private tmux server and its temporary files may remain. Select Cleanup to remove them when the program finishes. The program stops its private tmux server and removes any temporary files it created when it finishes. Unhandled conditions already end the script with SBCL's diagnostic and backtrace, so there is no separate error wrapper to add.
Setup and run
git init -q sourcegit -C source fetch -q --depth=1 \ https://github.com/libtmux/libtmux-lisp.git \ 99874b44dbe29b3651597a5debbacccde235d96cgit -C source checkout -q --detach FETCH_HEADmise trust sourcemise -C source installunset TMUX TMUX_PANEexport ENV=/dev/null BASH_ENV=/dev/null SHELL=/bin/shexport LIBTMUX_SOURCE="$PWD/source"export LIBTMUX_PROGRAM="${LIBTMUX_NATIVE_TMUX:-$(command -v tmux)}"LIBTMUX_DEMO_DIR="$(mktemp -d)"export LIBTMUX_EXAMPLE_SOCKET="$LIBTMUX_DEMO_DIR/tmux.sock"trap 'rm -rf "$LIBTMUX_DEMO_DIR"' EXITtmux -S "$LIBTMUX_EXAMPLE_SOCKET" -f /dev/null \ new-session -d -s demo -n editor -x 80 -y 24 -- /bin/catLIBTMUX_ASDF="$(mise -C source where http:asdf-lisp)/asdf.lisp"mise -C source exec -- sbcl --noinform --no-sysinit --no-userinit \ --load "$LIBTMUX_ASDF" --script "$PWD/quickstart.lisp"Expected output
session demo window 0:editor: %0 %1 window 1:logs: %2%1 is in window editor of session demoThe 0.1.0 ASDF systems are unreleased. This installs the pinned SBCL, ASDF and Qlot toolchain from source.
Start with TypeScript
import { mkdtemp } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { setTimeout as delay } from "node:timers/promises";import { PaneDirection, Server } from "libtmux";
const directory = await mkdtemp(join(tmpdir(), "ltx-home-"));const server = new Server({ socketPath: join(directory, "tmux.sock"), configFile: "/dev/null", timeoutMs: 5_000,});
const signal = AbortSignal.timeout(5_000);const session = await server.newSession({ name: "demo", signal });
// Lay out the session: name its window, split it, add a second window.const editor = session.activeWindow;if (!editor) throw new Error("The session has no active window");await editor.rename("editor");
const left = editor.activePane;if (!left) throw new Error("The window has no active pane");const right = await left.split({ direction: PaneDirection.Right, signal,});const logs = await session.newWindow({ name: "logs", signal });
// Type a command into the new pane and wait for what it prints.await right.sendKeys("printf 'hello from %s\\n' tmux", { signal });
for (;;) { const lines = await right.capture({ signal }); if (lines.some((line) => line.includes("hello from tmux"))) break;
await delay(20, undefined, { signal });}
// Move the focus an attached client sees: the pane, then the window.await right.select();await logs.select();
// Walk the objects: down from the server, then up from one pane.const snapshot = await server.snapshot({ signal });for (const each of snapshot.sessions) { console.log("session", each.name); for (const window of each.windows) { const ids = window.panes.map((pane) => pane.id).join(" "); console.log(` window ${window.index}:${window.name}: ${ids}`); }}
const pane = snapshot.panes.one({ id: right.id });const home = pane.window;const owner = pane.session;if (!home || !owner) throw new Error("The pane has no window or session");console.log(pane.id, "is in window", home.name, "of session", owner.name);import { mkdtemp } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { setTimeout as delay } from "node:timers/promises";import { PaneDirection, Server } from "libtmux";
const directory = await mkdtemp(join(tmpdir(), "ltx-home-"));const server = new Server({ socketPath: join(directory, "tmux.sock"), configFile: "/dev/null", timeoutMs: 5_000,});
try { const signal = AbortSignal.timeout(5_000); const session = await server.newSession({ name: "demo", signal });
// Lay out the session: name its window, split it, add a second window. const editor = session.activeWindow; if (!editor) throw new Error("The session has no active window"); await editor.rename("editor");
const left = editor.activePane; if (!left) throw new Error("The window has no active pane"); const right = await left.split({ direction: PaneDirection.Right, signal, }); const logs = await session.newWindow({ name: "logs", signal });
// Type a command into the new pane and wait for what it prints. await right.sendKeys("printf 'hello from %s\\n' tmux", { signal });
for (;;) { const lines = await right.capture({ signal }); if (lines.some((line) => line.includes("hello from tmux"))) break;
await delay(20, undefined, { signal }); }
// Move the focus an attached client sees: the pane, then the window. await right.select(); await logs.select();
// Walk the objects: down from the server, then up from one pane. const snapshot = await server.snapshot({ signal }); for (const each of snapshot.sessions) { console.log("session", each.name); for (const window of each.windows) { const ids = window.panes.map((pane) => pane.id).join(" "); console.log(` window ${window.index}:${window.name}: ${ids}`); } }
const pane = snapshot.panes.one({ id: right.id }); const home = pane.window; const owner = pane.session; if (!home || !owner) throw new Error("The pane has no window or session"); console.log(pane.id, "is in window", home.name, "of session", owner.name);} catch (error) { throw new Error("tmux quickstart failed", { cause: error });}import { mkdtemp, readdir, rm } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { setTimeout as delay } from "node:timers/promises";import { PaneDirection, Server } from "libtmux";
const directory = await mkdtemp(join(tmpdir(), "ltx-home-"));const server = new Server({ socketPath: join(directory, "tmux.sock"), configFile: "/dev/null", timeoutMs: 5_000,});
try { const signal = AbortSignal.timeout(5_000); const session = await server.newSession({ name: "demo", signal });
// Lay out the session: name its window, split it, add a second window. const editor = session.activeWindow; if (!editor) throw new Error("The session has no active window"); await editor.rename("editor");
const left = editor.activePane; if (!left) throw new Error("The window has no active pane"); const right = await left.split({ direction: PaneDirection.Right, signal, }); const logs = await session.newWindow({ name: "logs", signal });
// Type a command into the new pane and wait for what it prints. await right.sendKeys("printf 'hello from %s\\n' tmux", { signal });
for (;;) { const lines = await right.capture({ signal }); if (lines.some((line) => line.includes("hello from tmux"))) break;
await delay(20, undefined, { signal }); }
// Move the focus an attached client sees: the pane, then the window. await right.select(); await logs.select();
// Walk the objects: down from the server, then up from one pane. const snapshot = await server.snapshot({ signal }); for (const each of snapshot.sessions) { console.log("session", each.name); for (const window of each.windows) { const ids = window.panes.map((pane) => pane.id).join(" "); console.log(` window ${window.index}:${window.name}: ${ids}`); } }
const pane = snapshot.panes.one({ id: right.id }); const home = pane.window; const owner = pane.session; if (!home || !owner) throw new Error("The pane has no window or session"); console.log(pane.id, "is in window", home.name, "of session", owner.name);} finally { if ((await readdir(directory)).includes("tmux.sock")) { await server.kill(); } await rm(directory, { recursive: true });}import { mkdtemp, readdir, rm } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { setTimeout as delay } from "node:timers/promises";import { PaneDirection, Server } from "libtmux";
const directory = await mkdtemp(join(tmpdir(), "ltx-home-"));const server = new Server({ socketPath: join(directory, "tmux.sock"), configFile: "/dev/null", timeoutMs: 5_000,});
const failures: unknown[] = [];try { const signal = AbortSignal.timeout(5_000); const session = await server.newSession({ name: "demo", signal });
// Lay out the session: name its window, split it, add a second window. const editor = session.activeWindow; if (!editor) throw new Error("The session has no active window"); await editor.rename("editor");
const left = editor.activePane; if (!left) throw new Error("The window has no active pane"); const right = await left.split({ direction: PaneDirection.Right, signal, }); const logs = await session.newWindow({ name: "logs", signal });
// Type a command into the new pane and wait for what it prints. await right.sendKeys("printf 'hello from %s\\n' tmux", { signal });
for (;;) { const lines = await right.capture({ signal }); if (lines.some((line) => line.includes("hello from tmux"))) break;
await delay(20, undefined, { signal }); }
// Move the focus an attached client sees: the pane, then the window. await right.select(); await logs.select();
// Walk the objects: down from the server, then up from one pane. const snapshot = await server.snapshot({ signal }); for (const each of snapshot.sessions) { console.log("session", each.name); for (const window of each.windows) { const ids = window.panes.map((pane) => pane.id).join(" "); console.log(` window ${window.index}:${window.name}: ${ids}`); } }
const pane = snapshot.panes.one({ id: right.id }); const home = pane.window; const owner = pane.session; if (!home || !owner) throw new Error("The pane has no window or session"); console.log(pane.id, "is in window", home.name, "of session", owner.name);} catch (error) { failures.push(error);}
try { if ((await readdir(directory)).includes("tmux.sock")) { await server.kill(); }
await rm(directory, { recursive: true });} catch (error) { failures.push(new Error(`Cleanup failed: ${directory}`, { cause: error, }));}
if (failures.length) throw new AggregateError(failures);Run this example
POSIX shell, tmux 3.3a or newer and Bun 1.4.2.
Save the program above as quickstart.ts in a new directory, along with the files below.
Cleanup is omitted; the private tmux server and its temporary files may remain. Select Cleanup to remove them when the program finishes. The program stops its private tmux server and removes any temporary files it created when it finishes. Error handling adds diagnostics; every version checks required results and deadlines.
package.json
{"type":"module","private":true,"dependencies":{"libtmux":"0.1.2"}}Setup and run
bun installunset TMUX TMUX_PANEexport ENV=/dev/null BASH_ENV=/dev/null SHELL=/bin/shbun run quickstart.tsExpected output
session demo window 0:editor: %0 %1 window 1:logs: %2%1 is in window editor of session demoDependency cooldowns
The checkbox turns a cooldown on and off for every picker on the site. It applies to what an install pulls in; the package itself, and the libtmux it pins, stay current.
What are cooldowns?
Cooldowns delay picking up newly uploaded packages so the community has time to spot supply-chain attacks before you install. Most package managers don't apply one by default; you opt in through a global setting in your tool's configuration.
Learn more at cooldowns.dev · Datadog Security Labs writeup.
$ npm install libtmux$ npm install --min-release-age=0 libtmux$ pnpm add libtmux$ pnpm_config_minimum_release_age=0 pnpm add libtmux$ yarn add libtmux$ YARN_NPM_MINIMAL_AGE_GATE=0 yarn add libtmux$ bun add libtmux$ bun add libtmuxBun cannot exempt libtmux from its own cooldown, so a cooldown here would also hold back the release this installs. This command runs without one.
$ bun add --minimum-release-age=0 libtmuxStart with Rust
use libtmux::{PaneWait, Server, SplitDirection, SplitOptions};use std::{error::Error, time::Duration};
type ExampleError = Box<dyn Error>;
async fn work(server: &Server) -> Result<(), ExampleError> { let session = server.new_session("demo").await?;
// Lay out the session: name its window, split it, add a second window. let mut editor = session.active_window().await?.ok_or("missing window")?; editor.rename("editor").await?; let left = editor.active_pane().await?.ok_or("missing pane")?; let mut right = left.split(SplitOptions::new(SplitDirection::Right)).await?; let mut logs = session.new_window("logs").await?;
// Type a command into the new pane and wait for what it prints. right.send_line("printf 'hello from %s\\n' tmux").await?; let seen = right .wait_for_text("hello from tmux", Duration::from_secs(5)) .await?; if seen != PaneWait::Arrived { return Err("The pane did not print hello from tmux".into()); }
// Move the focus an attached client sees: the pane, then the window. right.select().await?; logs.select().await?;
// Walk the objects: down from the server, then up from one pane. let sessions = server.sessions().await?; for each in sessions { println!("session {}", each.name().to_string_lossy()); let windows = each.windows().await?; for window in windows { let name = window.name().to_string_lossy(); print!(" window {}:{}:", window.index(), name); let panes = window.panes().await?; for pane in panes { print!(" {}", pane.id()); } println!(); } } let window = right.window().await?.ok_or("missing window")?; let owner = window.session().await?.ok_or("missing session")?; println!( "{} is in window {} of session {}", right.id(), window.name().to_string_lossy(), owner.name().to_string_lossy(), ); Ok(())}
#[tokio::main(flavor = "current_thread")]async fn main() -> Result<(), ExampleError> { let root = std::path::Path::new("/tmp/libtmux-rs-dev"); std::fs::create_dir_all(root)?; let directory = tempfile::Builder::new().prefix("home-").tempdir_in(root)?.keep();
let server = Server::builder() .socket_path(directory.join("tmux.sock")) .config_file("/dev/null") .default_timeout(Duration::from_secs(5)) .build()?;
let outcome = tokio::time::timeout(Duration::from_secs(10), work(&server)) .await;
server.shutdown().await?; outcome??; Ok(())}use libtmux::{PaneWait, Server, SplitDirection, SplitOptions};use std::{error::Error, time::Duration};
type ExampleError = Box<dyn Error>;
async fn work(server: &Server) -> Result<(), ExampleError> { let session = server.new_session("demo").await?;
// Lay out the session: name its window, split it, add a second window. let mut editor = session.active_window().await?.ok_or("missing window")?; editor.rename("editor").await?; let left = editor.active_pane().await?.ok_or("missing pane")?; let mut right = left.split(SplitOptions::new(SplitDirection::Right)).await?; let mut logs = session.new_window("logs").await?;
// Type a command into the new pane and wait for what it prints. right.send_line("printf 'hello from %s\\n' tmux").await?; let seen = right .wait_for_text("hello from tmux", Duration::from_secs(5)) .await?; if seen != PaneWait::Arrived { return Err("The pane did not print hello from tmux".into()); }
// Move the focus an attached client sees: the pane, then the window. right.select().await?; logs.select().await?;
// Walk the objects: down from the server, then up from one pane. let sessions = server.sessions().await?; for each in sessions { println!("session {}", each.name().to_string_lossy()); let windows = each.windows().await?; for window in windows { let name = window.name().to_string_lossy(); print!(" window {}:{}:", window.index(), name); let panes = window.panes().await?; for pane in panes { print!(" {}", pane.id()); } println!(); } } let window = right.window().await?.ok_or("missing window")?; let owner = window.session().await?.ok_or("missing session")?; println!( "{} is in window {} of session {}", right.id(), window.name().to_string_lossy(), owner.name().to_string_lossy(), ); Ok(())}
#[tokio::main(flavor = "current_thread")]async fn main() -> Result<(), ExampleError> { let root = std::path::Path::new("/tmp/libtmux-rs-dev"); std::fs::create_dir_all(root)?; let directory = tempfile::Builder::new().prefix("home-").tempdir_in(root)?.keep();
let server = Server::builder() .socket_path(directory.join("tmux.sock")) .config_file("/dev/null") .default_timeout(Duration::from_secs(5)) .build()?;
let outcome = tokio::time::timeout(Duration::from_secs(10), work(&server)) .await;
let closed = server.shutdown().await; let mut failures = Vec::new(); match outcome { Ok(Ok(())) => {} Ok(Err(error)) => failures.push(format!("work: {error}")), Err(error) => failures.push(format!("deadline: {error}")), } if let Err(error) = closed { failures.push(format!("close executor: {error}")); }
if failures.is_empty() { Ok(()) } else { Err(failures.join("; ").into()) }}use libtmux::{PaneWait, Server, SplitDirection, SplitOptions};use std::{error::Error, time::Duration};
type ExampleError = Box<dyn Error>;
async fn work(server: &Server) -> Result<(), ExampleError> { let session = server.new_session("demo").await?;
// Lay out the session: name its window, split it, add a second window. let mut editor = session.active_window().await?.ok_or("missing window")?; editor.rename("editor").await?; let left = editor.active_pane().await?.ok_or("missing pane")?; let mut right = left.split(SplitOptions::new(SplitDirection::Right)).await?; let mut logs = session.new_window("logs").await?;
// Type a command into the new pane and wait for what it prints. right.send_line("printf 'hello from %s\\n' tmux").await?; let seen = right .wait_for_text("hello from tmux", Duration::from_secs(5)) .await?; if seen != PaneWait::Arrived { return Err("The pane did not print hello from tmux".into()); }
// Move the focus an attached client sees: the pane, then the window. right.select().await?; logs.select().await?;
// Walk the objects: down from the server, then up from one pane. let sessions = server.sessions().await?; for each in sessions { println!("session {}", each.name().to_string_lossy()); let windows = each.windows().await?; for window in windows { let name = window.name().to_string_lossy(); print!(" window {}:{}:", window.index(), name); let panes = window.panes().await?; for pane in panes { print!(" {}", pane.id()); } println!(); } } let window = right.window().await?.ok_or("missing window")?; let owner = window.session().await?.ok_or("missing session")?; println!( "{} is in window {} of session {}", right.id(), window.name().to_string_lossy(), owner.name().to_string_lossy(), ); Ok(())}
#[tokio::main(flavor = "current_thread")]async fn main() -> Result<(), ExampleError> { let root = std::path::Path::new("/tmp/libtmux-rs-dev"); std::fs::create_dir_all(root)?; let directory = tempfile::Builder::new().prefix("home-").tempdir_in(root)?;
let server = Server::builder() .socket_path(directory.path().join("tmux.sock")) .config_file("/dev/null") .default_timeout(Duration::from_secs(5)) .build()?;
let outcome = tokio::time::timeout(Duration::from_secs(10), work(&server)) .await;
let killed = server.kill().await; let closed = server.shutdown().await; if killed.is_err() || closed.is_err() { directory.keep(); } else { directory.close()?; }
killed?; closed?; outcome??; Ok(())}use libtmux::{PaneWait, Server, SplitDirection, SplitOptions};use std::{error::Error, time::Duration};
type ExampleError = Box<dyn Error>;
async fn work(server: &Server) -> Result<(), ExampleError> { let session = server.new_session("demo").await?;
// Lay out the session: name its window, split it, add a second window. let mut editor = session.active_window().await?.ok_or("missing window")?; editor.rename("editor").await?; let left = editor.active_pane().await?.ok_or("missing pane")?; let mut right = left.split(SplitOptions::new(SplitDirection::Right)).await?; let mut logs = session.new_window("logs").await?;
// Type a command into the new pane and wait for what it prints. right.send_line("printf 'hello from %s\\n' tmux").await?; let seen = right .wait_for_text("hello from tmux", Duration::from_secs(5)) .await?; if seen != PaneWait::Arrived { return Err("The pane did not print hello from tmux".into()); }
// Move the focus an attached client sees: the pane, then the window. right.select().await?; logs.select().await?;
// Walk the objects: down from the server, then up from one pane. let sessions = server.sessions().await?; for each in sessions { println!("session {}", each.name().to_string_lossy()); let windows = each.windows().await?; for window in windows { let name = window.name().to_string_lossy(); print!(" window {}:{}:", window.index(), name); let panes = window.panes().await?; for pane in panes { print!(" {}", pane.id()); } println!(); } } let window = right.window().await?.ok_or("missing window")?; let owner = window.session().await?.ok_or("missing session")?; println!( "{} is in window {} of session {}", right.id(), window.name().to_string_lossy(), owner.name().to_string_lossy(), ); Ok(())}
#[tokio::main(flavor = "current_thread")]async fn main() -> Result<(), ExampleError> { let root = std::path::Path::new("/tmp/libtmux-rs-dev"); std::fs::create_dir_all(root)?; let directory = tempfile::Builder::new().prefix("home-").tempdir_in(root)?;
let server = Server::builder() .socket_path(directory.path().join("tmux.sock")) .config_file("/dev/null") .default_timeout(Duration::from_secs(5)) .build()?;
let outcome = tokio::time::timeout(Duration::from_secs(10), work(&server)) .await;
// kill stops our daemon; shutdown closes this client executor. let killed = server.kill().await; let closed = server.shutdown().await; let cleanup_failed = killed.is_err() || closed.is_err();
let mut failures = Vec::new(); match outcome { Ok(Ok(())) => {} Ok(Err(error)) => failures.push(format!("work: {error}")), Err(error) => failures.push(format!("deadline: {error}")), }
if let Err(error) = killed { failures.push(format!("stop owned daemon: {error}")); } if let Err(error) = closed { failures.push(format!("close executor: {error}")); }
if cleanup_failed { let retained = directory.keep(); failures.push(format!("inspect {}", retained.display())); } else if let Err(error) = directory.close() { failures.push(format!("remove directory: {error}")); }
if failures.is_empty() { Ok(()) } else { Err(failures.join("; ").into()) }}Run this example
POSIX shell, tmux 3.3a or newer, rustup with Rust 1.97.1 (rust-toolchain.toml), and a C linker.
Save the program above as src/main.rs in a new directory, along with the files below.
Cleanup is omitted; the private tmux server and its temporary files may remain. Select Cleanup to remove them when the program finishes. The program stops its private tmux server and removes any temporary files it created when it finishes. Error handling adds diagnostics; every version checks required results and deadlines.
Cargo.toml
[package]name = "libtmux-home-quickstart"version = "0.0.0"edition = "2024"publish = false
[dependencies]libtmux = "0.1.2"tempfile = "3.20"tokio = { version = "1.40", features = ["macros", "rt", "time"] }Cargo.lock
# This file is automatically @generated by Cargo.# It is not intended for manual editing.version = 4
[[package]]name = "aho-corasick"version = "1.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"dependencies = [ "memchr",]
[[package]]name = "bitflags"version = "2.13.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]name = "bytes"version = "1.12.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]name = "caseless"version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8b6fd507454086c8edfd769ca6ada439193cdb209c7681712ef6275cccbfe5d8"dependencies = [ "unicode-normalization",]
[[package]]name = "cfg-if"version = "1.0.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]name = "errno"version = "0.3.14"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"dependencies = [ "libc", "windows-sys",]
[[package]]name = "fastrand"version = "2.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]name = "getrandom"version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"dependencies = [ "cfg-if", "libc", "r-efi",]
[[package]]name = "libc"version = "0.2.191"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]name = "libtmux"version = "0.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a7ec00257bb76e43923acb335470657d5d427a8bc802e7c51b611b268c052ea3"dependencies = [ "caseless", "regex", "rustix", "thiserror", "tokio",]
[[package]]name = "libtmux-home-quickstart"version = "0.0.0"dependencies = [ "libtmux", "tempfile", "tokio",]
[[package]]name = "linux-raw-sys"version = "0.12.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]name = "memchr"version = "2.8.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]name = "mio"version = "1.2.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee"dependencies = [ "libc", "wasi", "windows-sys",]
[[package]]name = "once_cell"version = "1.21.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]name = "pin-project-lite"version = "0.2.17"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]name = "proc-macro2"version = "1.0.107"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"dependencies = [ "unicode-ident",]
[[package]]name = "quote"version = "1.0.47"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"dependencies = [ "proc-macro2",]
[[package]]name = "r-efi"version = "6.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]name = "regex"version = "1.13.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"dependencies = [ "aho-corasick", "memchr", "regex-automata", "regex-syntax",]
[[package]]name = "regex-automata"version = "0.4.18"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"dependencies = [ "aho-corasick", "memchr", "regex-syntax",]
[[package]]name = "regex-syntax"version = "0.8.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]]name = "rustix"version = "1.1.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", "windows-sys",]
[[package]]name = "signal-hook-registry"version = "1.4.8"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"dependencies = [ "errno", "libc",]
[[package]]name = "syn"version = "3.0.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"dependencies = [ "proc-macro2", "quote", "unicode-ident",]
[[package]]name = "tempfile"version = "3.27.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"dependencies = [ "fastrand", "getrandom", "once_cell", "rustix", "windows-sys",]
[[package]]name = "thiserror"version = "2.0.21"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"dependencies = [ "thiserror-impl",]
[[package]]name = "thiserror-impl"version = "2.0.21"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"dependencies = [ "proc-macro2", "quote", "syn",]
[[package]]name = "tinyvec"version = "1.13.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
[[package]]name = "tokio"version = "1.54.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"dependencies = [ "bytes", "libc", "mio", "pin-project-lite", "signal-hook-registry", "tokio-macros", "windows-sys",]
[[package]]name = "tokio-macros"version = "2.7.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"dependencies = [ "proc-macro2", "quote", "syn",]
[[package]]name = "unicode-ident"version = "1.0.27"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]name = "unicode-normalization"version = "0.1.26"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d"dependencies = [ "tinyvec",]
[[package]]name = "wasi"version = "0.11.1+wasi-snapshot-preview1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]name = "windows-link"version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]name = "windows-sys"version = "0.61.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"dependencies = [ "windows-link",]rust-toolchain.toml
[toolchain]channel = "1.97.1"components = ["clippy", "rust-src", "rustfmt"]profile = "minimal"Setup and run
cargo build --locked --jobs 2unset TMUX TMUX_PANEexport ENV=/dev/null BASH_ENV=/dev/null SHELL=/bin/shcargo run --quiet --lockedExpected output
session demo window 0:editor: %0 %1 window 1:logs: %2%1 is in window editor of session demo$ cargo add libtmuxStart with Go
// Command quickstart lays out a tmux session, then walks it as objects.package main
import ( "context" "fmt" "log" "os"
"github.com/libtmux/libtmux-go/tmux")
func main() { if err := run(context.Background()); err != nil { log.Fatal(err) }}
func run(ctx context.Context) error { // A private server: a socket and an empty config of its own, so this // neither touches nor is changed by a tmux you already use. // The process ID in the socket name keeps one run apart from the next. server, err := tmux.NewServer(tmux.ServerOptions{ SocketName: fmt.Sprintf("libtmux-quickstart-%d", os.Getpid()), ConfigFile: os.DevNull, }) if err != nil { return err } session, err := server.NewSession(ctx, tmux.NewSessionRequest{ Name: "demo", }) if err != nil { return err }
// Lay out the session: name its window, split it, add a second window. editor, err := session.ResolveActiveWindow(ctx) if err != nil { return err } editor, err = editor.Rename(ctx, "editor") if err != nil { return err } left, err := editor.ResolveActivePane(ctx) if err != nil { return err } right, err := left.Split(ctx, tmux.SplitPaneRequest{ Direction: tmux.PaneDirectionRight, }) if err != nil { return err } name := "logs" logs, err := session.NewWindow(ctx, tmux.NewWindowRequest{ Name: &name, }) if err != nil { return err }
// Type a command into the new pane and wait for what it prints. command := "printf 'hello from %s\\n' tmux" err = right.SendKeys(ctx, tmux.SendKeysRequest{Command: &command}) if err != nil { return err } _, err = right.WaitForText(ctx, tmux.WaitForTextRequest{ Text: "hello from tmux", }) if err != nil { return err }
// Move the focus an attached client sees: the pane, then the window. _, err = right.Select(ctx, tmux.PaneSelectRequest{}) if err != nil { return err } _, err = logs.Select(ctx) if err != nil { return err }
// Walk the objects: down from the server, then up from one pane. snapshot, err := server.Snapshot(ctx) if err != nil { return err } for _, each := range snapshot.Sessions() { sessionName, _ := each.Name() fmt.Println("session", sessionName) windows, _ := each.Windows() for _, window := range windows { name, _ := window.Name() fmt.Printf(" window %d:%s:", window.Index(), name) panes, _ := window.Panes() for _, pane := range panes { fmt.Print(" ", pane.ID()) } fmt.Println() } } pane, _ := snapshot.PaneByID(right.ID()) window, _ := pane.Window() owner, _ := window.Session() windowName, _ := window.Name() sessionName, _ := owner.Name() fmt.Println(pane.ID(), "is in window", windowName, "of session", sessionName) return nil}// Command quickstart lays out a tmux session, then walks it as objects.package main
import ( "context" "fmt" "log" "os"
"github.com/libtmux/libtmux-go/tmux")
func main() { if err := run(context.Background()); err != nil { log.Fatal(err) }}
func run(ctx context.Context) error { // A private server: a socket and an empty config of its own, so this // neither touches nor is changed by a tmux you already use. // The process ID in the socket name keeps one run apart from the next. server, err := tmux.NewServer(tmux.ServerOptions{ SocketName: fmt.Sprintf("libtmux-quickstart-%d", os.Getpid()), ConfigFile: os.DevNull, }) if err != nil { return fmt.Errorf("configure tmux: %w", err) } session, err := server.NewSession(ctx, tmux.NewSessionRequest{ Name: "demo", }) if err != nil { return fmt.Errorf("create session: %w", err) }
// Lay out the session: name its window, split it, add a second window. editor, err := session.ResolveActiveWindow(ctx) if err != nil { return fmt.Errorf("find window: %w", err) } editor, err = editor.Rename(ctx, "editor") if err != nil { return fmt.Errorf("rename window: %w", err) } left, err := editor.ResolveActivePane(ctx) if err != nil { return fmt.Errorf("find pane: %w", err) } right, err := left.Split(ctx, tmux.SplitPaneRequest{ Direction: tmux.PaneDirectionRight, }) if err != nil { return fmt.Errorf("split pane: %w", err) } name := "logs" logs, err := session.NewWindow(ctx, tmux.NewWindowRequest{ Name: &name, }) if err != nil { return fmt.Errorf("add window: %w", err) }
// Type a command into the new pane and wait for what it prints. command := "printf 'hello from %s\\n' tmux" err = right.SendKeys(ctx, tmux.SendKeysRequest{Command: &command}) if err != nil { return fmt.Errorf("send keys: %w", err) } _, err = right.WaitForText(ctx, tmux.WaitForTextRequest{ Text: "hello from tmux", }) if err != nil { return fmt.Errorf("wait for output: %w", err) }
// Move the focus an attached client sees: the pane, then the window. _, err = right.Select(ctx, tmux.PaneSelectRequest{}) if err != nil { return fmt.Errorf("select pane: %w", err) } _, err = logs.Select(ctx) if err != nil { return fmt.Errorf("select window: %w", err) }
// Walk the objects: down from the server, then up from one pane. snapshot, err := server.Snapshot(ctx) if err != nil { return fmt.Errorf("read tmux: %w", err) } for _, each := range snapshot.Sessions() { sessionName, _ := each.Name() fmt.Println("session", sessionName) windows, _ := each.Windows() for _, window := range windows { name, _ := window.Name() fmt.Printf(" window %d:%s:", window.Index(), name) panes, _ := window.Panes() for _, pane := range panes { fmt.Print(" ", pane.ID()) } fmt.Println() } } pane, _ := snapshot.PaneByID(right.ID()) window, _ := pane.Window() owner, _ := window.Session() windowName, _ := window.Name() sessionName, _ := owner.Name() fmt.Println(pane.ID(), "is in window", windowName, "of session", sessionName) return nil}// Command quickstart lays out a tmux session, then walks it as objects.package main
import ( "context" "errors" "fmt" "log" "os"
"github.com/libtmux/libtmux-go/tmux")
func main() { if err := run(context.Background()); err != nil { log.Fatal(err) }}
func run(ctx context.Context) (err error) { // A private server: a socket and an empty config of its own, so this // neither touches nor is changed by a tmux you already use. // The process ID in the socket name keeps one run apart from the next. server, err := tmux.NewServer(tmux.ServerOptions{ SocketName: fmt.Sprintf("libtmux-quickstart-%d", os.Getpid()), ConfigFile: os.DevNull, }) if err != nil { return err } session, err := server.NewSession(ctx, tmux.NewSessionRequest{ Name: "demo", }) if err != nil { return err } // Cleanup runs even when ctx is the reason the program is leaving. defer func() { err = errors.Join(err, server.Kill(context.WithoutCancel(ctx))) }()
// Lay out the session: name its window, split it, add a second window. editor, err := session.ResolveActiveWindow(ctx) if err != nil { return err } editor, err = editor.Rename(ctx, "editor") if err != nil { return err } left, err := editor.ResolveActivePane(ctx) if err != nil { return err } right, err := left.Split(ctx, tmux.SplitPaneRequest{ Direction: tmux.PaneDirectionRight, }) if err != nil { return err } name := "logs" logs, err := session.NewWindow(ctx, tmux.NewWindowRequest{ Name: &name, }) if err != nil { return err }
// Type a command into the new pane and wait for what it prints. command := "printf 'hello from %s\\n' tmux" err = right.SendKeys(ctx, tmux.SendKeysRequest{Command: &command}) if err != nil { return err } _, err = right.WaitForText(ctx, tmux.WaitForTextRequest{ Text: "hello from tmux", }) if err != nil { return err }
// Move the focus an attached client sees: the pane, then the window. _, err = right.Select(ctx, tmux.PaneSelectRequest{}) if err != nil { return err } _, err = logs.Select(ctx) if err != nil { return err }
// Walk the objects: down from the server, then up from one pane. snapshot, err := server.Snapshot(ctx) if err != nil { return err } for _, each := range snapshot.Sessions() { sessionName, _ := each.Name() fmt.Println("session", sessionName) windows, _ := each.Windows() for _, window := range windows { name, _ := window.Name() fmt.Printf(" window %d:%s:", window.Index(), name) panes, _ := window.Panes() for _, pane := range panes { fmt.Print(" ", pane.ID()) } fmt.Println() } } pane, _ := snapshot.PaneByID(right.ID()) window, _ := pane.Window() owner, _ := window.Session() windowName, _ := window.Name() sessionName, _ := owner.Name() fmt.Println(pane.ID(), "is in window", windowName, "of session", sessionName) return nil}// Command quickstart lays out a tmux session, then walks it as objects.package main
import ( "context" "errors" "fmt" "log" "os"
"github.com/libtmux/libtmux-go/tmux")
func main() { if err := run(context.Background()); err != nil { log.Fatal(err) }}
func run(ctx context.Context) (err error) { // A private server: a socket and an empty config of its own, so this // neither touches nor is changed by a tmux you already use. // The process ID in the socket name keeps one run apart from the next. server, err := tmux.NewServer(tmux.ServerOptions{ SocketName: fmt.Sprintf("libtmux-quickstart-%d", os.Getpid()), ConfigFile: os.DevNull, }) if err != nil { return fmt.Errorf("configure tmux: %w", err) } session, err := server.NewSession(ctx, tmux.NewSessionRequest{ Name: "demo", }) if err != nil { return fmt.Errorf("create session: %w", err) } // Cleanup runs even when ctx is the reason the program is leaving. defer func() { err = errors.Join(err, server.Kill(context.WithoutCancel(ctx))) }()
// Lay out the session: name its window, split it, add a second window. editor, err := session.ResolveActiveWindow(ctx) if err != nil { return fmt.Errorf("find window: %w", err) } editor, err = editor.Rename(ctx, "editor") if err != nil { return fmt.Errorf("rename window: %w", err) } left, err := editor.ResolveActivePane(ctx) if err != nil { return fmt.Errorf("find pane: %w", err) } right, err := left.Split(ctx, tmux.SplitPaneRequest{ Direction: tmux.PaneDirectionRight, }) if err != nil { return fmt.Errorf("split pane: %w", err) } name := "logs" logs, err := session.NewWindow(ctx, tmux.NewWindowRequest{ Name: &name, }) if err != nil { return fmt.Errorf("add window: %w", err) }
// Type a command into the new pane and wait for what it prints. command := "printf 'hello from %s\\n' tmux" err = right.SendKeys(ctx, tmux.SendKeysRequest{Command: &command}) if err != nil { return fmt.Errorf("send keys: %w", err) } _, err = right.WaitForText(ctx, tmux.WaitForTextRequest{ Text: "hello from tmux", }) if err != nil { return fmt.Errorf("wait for output: %w", err) }
// Move the focus an attached client sees: the pane, then the window. _, err = right.Select(ctx, tmux.PaneSelectRequest{}) if err != nil { return fmt.Errorf("select pane: %w", err) } _, err = logs.Select(ctx) if err != nil { return fmt.Errorf("select window: %w", err) }
// Walk the objects: down from the server, then up from one pane. snapshot, err := server.Snapshot(ctx) if err != nil { return fmt.Errorf("read tmux: %w", err) } for _, each := range snapshot.Sessions() { sessionName, _ := each.Name() fmt.Println("session", sessionName) windows, _ := each.Windows() for _, window := range windows { name, _ := window.Name() fmt.Printf(" window %d:%s:", window.Index(), name) panes, _ := window.Panes() for _, pane := range panes { fmt.Print(" ", pane.ID()) } fmt.Println() } } pane, _ := snapshot.PaneByID(right.ID()) window, _ := pane.Window() owner, _ := window.Session() windowName, _ := window.Name() sessionName, _ := owner.Name() fmt.Println(pane.ID(), "is in window", windowName, "of session", sessionName) return nil}Run this example
POSIX shell, tmux 3.3a or newer and Go 1.26.5.
Save the program above as quickstart.go in a new directory, along with the files below.
Cleanup is omitted; the private tmux server and its temporary files may remain. Select Cleanup to remove them when the program finishes. The program stops its private tmux server and removes any temporary files it created when it finishes. Error handling adds diagnostics; every version checks required results and deadlines.
go.mod
module example.com/libtmux-home
go 1.26.0
require github.com/libtmux/libtmux-go v0.1.2Setup and run
go mod tidygo build -p 2 -o quickstart quickstart.gounset TMUX TMUX_PANEexport ENV=/dev/null BASH_ENV=/dev/null SHELL=/bin/sh./quickstartExpected output
session demo window 0:editor: %0 %1 window 1:logs: %2%1 is in window editor of session demo$ go get github.com/libtmux/libtmux-go/tmux@latestStart with Java
import io.github.libtmux.Server;import io.github.libtmux.ServerConfig;import io.github.libtmux.ServerEndpoint;import io.github.libtmux.TextOutcome;import java.nio.file.Path;import java.time.Duration;import java.util.UUID;
public final class Main { public static void main(String[] args) throws Exception { var socket = "libtmux-home-" + UUID.randomUUID(); var config = ServerConfig.builder() .endpoint(ServerEndpoint.namedSocket(socket)) .configFile(Path.of("/dev/null")) .defaultTimeout(Duration.ofSeconds(5)) .build();
try (Server server = Server.open(config)) { var session = server.newSession("demo");
// Lay out the session: name its window, split it, add another. var first = session.activeWindow().orElseThrow(); var editor = first.rename("editor"); var left = editor.activePane().orElseThrow(); var right = left.split(spec -> spec.toRight().detached()); var logs = session.newWindow( spec -> spec.named("logs").detached());
// Type a command into the new pane and wait for what it prints. right.sendLine("printf 'hello from %s\\n' tmux"); var seen = right.awaitText( "hello from tmux", Duration.ofSeconds(5)); if (seen == TextOutcome.TIMED_OUT) { throw new IllegalStateException("output did not arrive"); }
// Move the focus an attached client sees: pane, then window. right.select(); logs.select();
// Walk the objects: down from the server, up from one pane. var snapshot = server.snapshot(); var sessions = snapshot.sessions(); for (var each : sessions) { System.out.println("session " + each.name()); var windows = snapshot.windowsOf(each.id()); for (var win : windows) { var index = win.context().index(); System.out.printf(" window %s:%s:", index, win.name()); var panes = snapshot.panesOf(win.context()); for (var pane : panes) { System.out.print(" " + pane.id()); } System.out.println(); } } var window = right.window(); var owner = window.session(); System.out.println( right.id() + " is in window " + window.name() + " of session " + owner.name()); } }}import io.github.libtmux.Server;import io.github.libtmux.ServerConfig;import io.github.libtmux.ServerEndpoint;import io.github.libtmux.TextOutcome;import java.nio.file.Path;import java.time.Duration;import java.util.UUID;
public final class Main { public static void main(String[] args) throws Exception { var socket = "libtmux-home-" + UUID.randomUUID(); var config = ServerConfig.builder() .endpoint(ServerEndpoint.namedSocket(socket)) .configFile(Path.of("/dev/null")) .defaultTimeout(Duration.ofSeconds(5)) .build();
try (Server server = Server.open(config)) { try { var session = server.newSession("demo");
// Lay out the session: name its window, split it, add another. var first = session.activeWindow().orElseThrow(); var editor = first.rename("editor"); var left = editor.activePane().orElseThrow(); var right = left.split(spec -> spec.toRight().detached()); var logs = session.newWindow( spec -> spec.named("logs").detached());
// Type a command into the new pane and wait for what it prints. right.sendLine("printf 'hello from %s\\n' tmux"); var seen = right.awaitText( "hello from tmux", Duration.ofSeconds(5)); if (seen == TextOutcome.TIMED_OUT) { throw new IllegalStateException("output did not arrive"); }
// Move the focus an attached client sees: pane, then window. right.select(); logs.select();
// Walk the objects: down from the server, up from one pane. var snapshot = server.snapshot(); var sessions = snapshot.sessions(); for (var each : sessions) { System.out.println("session " + each.name()); var windows = snapshot.windowsOf(each.id()); for (var win : windows) { var index = win.context().index(); System.out.printf(" window %s:%s:", index, win.name()); var panes = snapshot.panesOf(win.context()); for (var pane : panes) { System.out.print(" " + pane.id()); } System.out.println(); } } var window = right.window(); var owner = window.session(); System.out.println( right.id() + " is in window " + window.name() + " of session " + owner.name()); } catch (Exception error) { throw new IllegalStateException( "tmux quickstart failed", error); } } }}import io.github.libtmux.Server;import io.github.libtmux.ServerConfig;import io.github.libtmux.ServerEndpoint;import io.github.libtmux.TextOutcome;import java.nio.file.Path;import java.time.Duration;import java.util.UUID;
public final class Main { public static void main(String[] args) throws Exception { var socket = "libtmux-home-" + UUID.randomUUID(); var config = ServerConfig.builder() .endpoint(ServerEndpoint.namedSocket(socket)) .configFile(Path.of("/dev/null")) .defaultTimeout(Duration.ofSeconds(5)) .build();
try (Server server = Server.open(config)) { try { var session = server.newSession("demo");
// Lay out the session: name its window, split it, add another. var first = session.activeWindow().orElseThrow(); var editor = first.rename("editor"); var left = editor.activePane().orElseThrow(); var right = left.split(spec -> spec.toRight().detached()); var logs = session.newWindow( spec -> spec.named("logs").detached());
// Type a command into the new pane and wait for what it prints. right.sendLine("printf 'hello from %s\\n' tmux"); var seen = right.awaitText( "hello from tmux", Duration.ofSeconds(5)); if (seen == TextOutcome.TIMED_OUT) { throw new IllegalStateException("output did not arrive"); }
// Move the focus an attached client sees: pane, then window. right.select(); logs.select();
// Walk the objects: down from the server, up from one pane. var snapshot = server.snapshot(); var sessions = snapshot.sessions(); for (var each : sessions) { System.out.println("session " + each.name()); var windows = snapshot.windowsOf(each.id()); for (var win : windows) { var index = win.context().index(); System.out.printf(" window %s:%s:", index, win.name()); var panes = snapshot.panesOf(win.context()); for (var pane : panes) { System.out.print(" " + pane.id()); } System.out.println(); } } var window = right.window(); var owner = window.session(); System.out.println( right.id() + " is in window " + window.name() + " of session " + owner.name()); } finally { server.killServer(); } } }}import io.github.libtmux.Server;import io.github.libtmux.ServerConfig;import io.github.libtmux.ServerEndpoint;import io.github.libtmux.TextOutcome;import java.nio.file.Path;import java.time.Duration;import java.util.UUID;
public final class Main { public static void main(String[] args) throws Exception { var socket = "libtmux-home-" + UUID.randomUUID(); var config = ServerConfig.builder() .endpoint(ServerEndpoint.namedSocket(socket)) .configFile(Path.of("/dev/null")) .defaultTimeout(Duration.ofSeconds(5)) .build();
try (Server server = Server.open(config)) { try { var session = server.newSession("demo");
// Lay out the session: name its window, split it, add another. var first = session.activeWindow().orElseThrow(); var editor = first.rename("editor"); var left = editor.activePane().orElseThrow(); var right = left.split(spec -> spec.toRight().detached()); var logs = session.newWindow( spec -> spec.named("logs").detached());
// Type a command into the new pane and wait for what it prints. right.sendLine("printf 'hello from %s\\n' tmux"); var seen = right.awaitText( "hello from tmux", Duration.ofSeconds(5)); if (seen == TextOutcome.TIMED_OUT) { throw new IllegalStateException("output did not arrive"); }
// Move the focus an attached client sees: pane, then window. right.select(); logs.select();
// Walk the objects: down from the server, up from one pane. var snapshot = server.snapshot(); var sessions = snapshot.sessions(); for (var each : sessions) { System.out.println("session " + each.name()); var windows = snapshot.windowsOf(each.id()); for (var win : windows) { var index = win.context().index(); System.out.printf(" window %s:%s:", index, win.name()); var panes = snapshot.panesOf(win.context()); for (var pane : panes) { System.out.print(" " + pane.id()); } System.out.println(); } } var window = right.window(); var owner = window.session(); System.out.println( right.id() + " is in window " + window.name() + " of session " + owner.name()); } catch (Exception error) { throw new IllegalStateException( "tmux quickstart failed", error); } finally { server.killServer(); } } }}Run this example
JDK 25 and tmux on Linux/macOS
Save the program above as src/main/java/Main.java in a new directory, along with the files below.
Cleanup is omitted; the private tmux server and its temporary files may remain. Select Cleanup to remove them when the program finishes. The program stops its private tmux server and removes any temporary files it created when it finishes. Error handling adds diagnostics; every version checks required results and deadlines.
build.gradle.kts
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")) }settings.gradle.kts
rootProject.name = "api-example"gradle.properties
org.gradle.jvmargs=-Xmx2g -XX:MaxMetaspaceSize=768m -Dfile.encoding=UTF-8kotlin.daemon.jvmargs=-Xmx2gorg.gradle.workers.max=2Setup and run
# Save the files above at their displayed relative paths.git clone https://github.com/libtmux/libtmux-java.git libtmux-sourcegit -C libtmux-source checkout --detach e8a39689d8d60968ac978a1dd2a89c6112333896./libtmux-source/gradlew --project-dir . --console=plain --no-daemon --max-workers=2 \ installDist -PexampleMain=MainSHELL=/bin/sh build/install/api-example/bin/api-exampleExpected output
session demo window 0:editor: %0 %1 window 1:logs: %2%1 is in window editor of session demoThe platform BOM names the version once and every other coordinate follows it, which is what stops a project mixing two releases of modules built against each other.
Start with Clojure
(require '[libtmux.core :as tm] '[libtmux.data :as data])(import '[java.lang ProcessHandle] '[java.nio.file Files Path] '[java.nio.file.attribute FileAttribute] '[java.time Duration] [java.util.concurrent TimeUnit])
(let [attrs (make-array FileAttribute 0) root (Path/of "/tmp/libtmux-java-dev" (make-array String 0)) _ (Files/createDirectories root attrs) directory (Files/createTempDirectory root "clojure-home-" attrs) socket (.resolve directory "tmux.sock") daemon (atom nil)] (try (with-open [server (tm/open! {:socket-path socket :binary (or (System/getenv "TMUX_BIN") "tmux") :config-file "/dev/null"})] (try (let [session (tm/new-session! server {:name "demo" :window-name "work" :command ["/bin/sh"]}) window (data/exactly-one (data/windows session)) pane (data/exactly-one (data/panes window)) _ (reset! daemon (.get (ProcessHandle/of (get-in session [:tmux/identity :tmux/pid]))))] (tm/rename! (:tmux/ref window) "editor") (assert (= "work" (:window/name window))) (tm/split-pane! (:tmux/ref pane) {:direction :right :command ["/bin/cat"]}) (tm/new-window! (:tmux/ref session) {:name "logs" :detached? true :command ["/bin/cat"]}) (tm/send-literal! (:tmux/ref pane) "printf 'hello from %s\\n' Clojure") (tm/send-keys! (:tmux/ref pane) ["Enter"]) (assert (#{:appeared :present-at-entry} (tm/await-text! (:tmux/ref pane) "hello from Clojure" (Duration/ofSeconds 2)))) (let [snapshot (tm/snapshot! server) observed (data/exactly-one (:tmux/sessions snapshot))] (assert (= "demo" (:session/name observed))) (println "session" (:session/name observed)) (doseq [entry (data/windows observed)] (println (str " window " (:window/name entry) ": " (count (data/panes entry)) " panes"))) (assert (some #{"hello from Clojure"} (tm/capture! (:tmux/ref pane)))) (println "output=hello from Clojure"))) (finally (tm/kill-server! server) (when-let [^ProcessHandle process @daemon] (.get (.onExit process) 1 TimeUnit/SECONDS))))) (finally (if-let [^ProcessHandle process @daemon] (when-not (.isAlive process) (Files/deleteIfExists socket) (Files/deleteIfExists directory)) (when-not (Files/exists socket (make-array java.nio.file.LinkOption 0)) (Files/deleteIfExists directory))))))(require '[libtmux.core :as tm] '[libtmux.data :as data])(import '[java.lang ProcessHandle] '[java.nio.file Files Path] '[java.nio.file.attribute FileAttribute] '[java.time Duration] [java.util.concurrent TimeUnit])
(let [attrs (make-array FileAttribute 0) root (Path/of "/tmp/libtmux-java-dev" (make-array String 0)) _ (Files/createDirectories root attrs) directory (Files/createTempDirectory root "clojure-home-" attrs) socket (.resolve directory "tmux.sock") daemon (atom nil)] (try (with-open [server (tm/open! {:socket-path socket :binary (or (System/getenv "TMUX_BIN") "tmux") :config-file "/dev/null"})] (try (let [session (tm/new-session! server {:name "demo" :window-name "work" :command ["/bin/sh"]}) window (data/exactly-one (data/windows session)) pane (data/exactly-one (data/panes window)) _ (reset! daemon (.get (ProcessHandle/of (get-in session [:tmux/identity :tmux/pid]))))] (tm/rename! (:tmux/ref window) "editor") (assert (= "work" (:window/name window))) (tm/split-pane! (:tmux/ref pane) {:direction :right :command ["/bin/cat"]}) (tm/new-window! (:tmux/ref session) {:name "logs" :detached? true :command ["/bin/cat"]}) (tm/send-literal! (:tmux/ref pane) "printf 'hello from %s\\n' Clojure") (tm/send-keys! (:tmux/ref pane) ["Enter"]) (assert (#{:appeared :present-at-entry} (tm/await-text! (:tmux/ref pane) "hello from Clojure" (Duration/ofSeconds 2)))) (let [snapshot (tm/snapshot! server) observed (data/exactly-one (:tmux/sessions snapshot))] (assert (= "demo" (:session/name observed))) (println "session" (:session/name observed)) (doseq [entry (data/windows observed)] (println (str " window " (:window/name entry) ": " (count (data/panes entry)) " panes"))) (assert (some #{"hello from Clojure"} (tm/capture! (:tmux/ref pane)))) (println "output=hello from Clojure"))) (catch Exception failure (throw (ex-info "Clojure tmux quickstart failed" {:tmux/failure (tm/error-summary failure)} failure))) (finally (tm/kill-server! server) (when-let [^ProcessHandle process @daemon] (.get (.onExit process) 1 TimeUnit/SECONDS))))) (finally (if-let [^ProcessHandle process @daemon] (when-not (.isAlive process) (Files/deleteIfExists socket) (Files/deleteIfExists directory)) (when-not (Files/exists socket (make-array java.nio.file.LinkOption 0)) (Files/deleteIfExists directory))))))(require '[libtmux.core :as tm] '[libtmux.data :as data])(import '[java.lang ProcessHandle] '[java.nio.file Files Path] '[java.nio.file.attribute FileAttribute] '[java.time Duration] [java.util.concurrent TimeUnit])
(let [attrs (make-array FileAttribute 0) root (Path/of "/tmp/libtmux-java-dev" (make-array String 0)) _ (Files/createDirectories root attrs) directory (Files/createTempDirectory root "clojure-home-" attrs) socket (.resolve directory "tmux.sock") daemon (atom nil)] (try (with-open [server (tm/open! {:socket-path socket :binary (or (System/getenv "TMUX_BIN") "tmux") :config-file "/dev/null"})] (try (let [session (tm/new-session! server {:name "demo" :window-name "work" :command ["/bin/sh"]}) window (data/exactly-one (data/windows session)) pane (data/exactly-one (data/panes window)) _ (reset! daemon (.get (ProcessHandle/of (get-in session [:tmux/identity :tmux/pid]))))] (tm/rename! (:tmux/ref window) "editor") (assert (= "work" (:window/name window))) (tm/split-pane! (:tmux/ref pane) {:direction :right :command ["/bin/cat"]}) (tm/new-window! (:tmux/ref session) {:name "logs" :detached? true :command ["/bin/cat"]}) (tm/send-literal! (:tmux/ref pane) "printf 'hello from %s\\n' Clojure") (tm/send-keys! (:tmux/ref pane) ["Enter"]) (assert (#{:appeared :present-at-entry} (tm/await-text! (:tmux/ref pane) "hello from Clojure" (Duration/ofSeconds 2)))) (let [snapshot (tm/snapshot! server) observed (data/exactly-one (:tmux/sessions snapshot))] (assert (= "demo" (:session/name observed))) (println "session" (:session/name observed)) (doseq [entry (data/windows observed)] (println (str " window " (:window/name entry) ": " (count (data/panes entry)) " panes"))) (assert (some #{"hello from Clojure"} (tm/capture! (:tmux/ref pane)))) (println "output=hello from Clojure"))) (finally (tm/kill-server! server) (when-let [^ProcessHandle process @daemon] (.get (.onExit process) 1 TimeUnit/SECONDS))))) (finally (if-let [^ProcessHandle process @daemon] (when-not (.isAlive process) (Files/deleteIfExists socket) (Files/deleteIfExists directory)) (when-not (Files/exists socket (make-array java.nio.file.LinkOption 0)) (Files/deleteIfExists directory))))) (assert (not (Files/exists directory (make-array java.nio.file.LinkOption 0)))))(require '[libtmux.core :as tm] '[libtmux.data :as data])(import '[java.lang ProcessHandle] '[java.nio.file Files Path] '[java.nio.file.attribute FileAttribute] '[java.time Duration] [java.util.concurrent TimeUnit])
(let [attrs (make-array FileAttribute 0) root (Path/of "/tmp/libtmux-java-dev" (make-array String 0)) _ (Files/createDirectories root attrs) directory (Files/createTempDirectory root "clojure-home-" attrs) socket (.resolve directory "tmux.sock") daemon (atom nil)] (try (with-open [server (tm/open! {:socket-path socket :binary (or (System/getenv "TMUX_BIN") "tmux") :config-file "/dev/null"})] (try (let [session (tm/new-session! server {:name "demo" :window-name "work" :command ["/bin/sh"]}) window (data/exactly-one (data/windows session)) pane (data/exactly-one (data/panes window)) _ (reset! daemon (.get (ProcessHandle/of (get-in session [:tmux/identity :tmux/pid]))))] (tm/rename! (:tmux/ref window) "editor") (assert (= "work" (:window/name window))) (tm/split-pane! (:tmux/ref pane) {:direction :right :command ["/bin/cat"]}) (tm/new-window! (:tmux/ref session) {:name "logs" :detached? true :command ["/bin/cat"]}) (tm/send-literal! (:tmux/ref pane) "printf 'hello from %s\\n' Clojure") (tm/send-keys! (:tmux/ref pane) ["Enter"]) (assert (#{:appeared :present-at-entry} (tm/await-text! (:tmux/ref pane) "hello from Clojure" (Duration/ofSeconds 2)))) (let [snapshot (tm/snapshot! server) observed (data/exactly-one (:tmux/sessions snapshot))] (assert (= "demo" (:session/name observed))) (println "session" (:session/name observed)) (doseq [entry (data/windows observed)] (println (str " window " (:window/name entry) ": " (count (data/panes entry)) " panes"))) (assert (some #{"hello from Clojure"} (tm/capture! (:tmux/ref pane)))) (println "output=hello from Clojure"))) (catch Exception failure (throw (ex-info "Clojure tmux quickstart failed" {:tmux/failure (tm/error-summary failure)} failure))) (finally (tm/kill-server! server) (when-let [^ProcessHandle process @daemon] (.get (.onExit process) 1 TimeUnit/SECONDS))))) (finally (if-let [^ProcessHandle process @daemon] (when-not (.isAlive process) (Files/deleteIfExists socket) (Files/deleteIfExists directory)) (when-not (Files/exists socket (make-array java.nio.file.LinkOption 0)) (Files/deleteIfExists directory))))) (assert (not (Files/exists directory (make-array java.nio.file.LinkOption 0)))))Run this example
JDK 25 or newer, Clojure CLI 1.12, Git, tmux 3.3a or newer, /bin/sh and /bin/cat on Linux or macOS. The Clojure artifacts are unpublished; install the pinned source into the isolated Maven repository first.
Save the program above as quickstart.clj in a new directory, along with the files below.
Every view closes its client and stops its private server. If shutdown fails, its socket directory stays available for recovery. Cleanup also checks directory removal. The program stops its private tmux server and removes any temporary files it created when it finishes. Error handling adds diagnostics; every version checks required results and deadlines.
deps.edn
{:paths ["."] :mvn/local-repo "m2" :deps {org.clojure/clojure {:mvn/version "1.12.6"} io.github.libtmux/libtmux-clojure {:mvn/version "0.1.2-SNAPSHOT"}}}Setup and run
git clone \ --branch master \ --single-branch \ https://github.com/libtmux/libtmux-java libtmux-source && \ git -C libtmux-source checkout --detach 941f2162062b6d118c68b7d1c23417e0d2cea124 && \ (cd libtmux-source && ./gradlew \ :libtmux:publishToMavenLocal \ :libtmux-clojure:publishToMavenLocal \ --max-workers=1 \ --console=plain \ "-Dmaven.repo.local=$PWD/../m2")clojure -J-Dclojure.main.report=stderr -M quickstart.cljExpected output
session demo window editor: 2 panes window logs: 1 panesoutput=hello from ClojureStart with Kotlin
import io.github.libtmux.ServerConfigimport io.github.libtmux.ServerEndpointimport io.github.libtmux.SplitSpecimport io.github.libtmux.TextOutcomeimport io.github.libtmux.WindowSpecimport io.github.libtmux.kotlin.*import java.nio.file.Pathimport java.time.Durationimport java.util.UUIDimport kotlinx.coroutines.runBlockingimport kotlin.time.Duration.Companion.seconds
fun main() = runBlocking { val socket = "libtmux-home-${UUID.randomUUID()}" val config = ServerConfig.builder() .endpoint(ServerEndpoint.namedSocket(socket)) .configFile(Path.of("/dev/null")) .defaultTimeout(Duration.ofSeconds(5)) .build()
withServer(config) { server -> val session = server.newSession("demo")
// Lay out the session: name its window, split it, // add a second window. val first = session.activeWindow ?: error("no active window") val editor = first.rename("editor") val left = editor.activePane ?: error("no active pane") val side = SplitSpec.builder().toRight().detached().build() val right = left.split(side) val tab = WindowSpec.builder().named("logs").detached().build() val logs = session.newWindow(tab)
// Type a command into the new pane and wait for what it prints. right.sendLine("printf 'hello from %s\\n' tmux") val outcome = right.awaitText( "hello from tmux", timeout = 5.seconds ) check(outcome != TextOutcome.TIMED_OUT)
// Move the focus an attached client sees: // the pane, then the window. right.select() logs.select()
// Walk the objects: down from the server, then up from one pane. val sessions = server.sessions() for (each in sessions) { println("session ${each.name}") for (window in each.windows) { val ids = window.panes.joinToString(" ") { "${it.id}" } println(" window ${window.index}:${window.name}: $ids") } }
val pane = server.pane(right.id) ?: error("no pane ${right.id}") val home = pane.window val owner = home.session println( "${pane.id} is in window ${home.name} of session ${owner.name}" ) }}import io.github.libtmux.ServerConfigimport io.github.libtmux.ServerEndpointimport io.github.libtmux.SplitSpecimport io.github.libtmux.TextOutcomeimport io.github.libtmux.WindowSpecimport io.github.libtmux.kotlin.*import java.nio.file.Pathimport java.time.Durationimport java.util.UUIDimport kotlinx.coroutines.runBlockingimport kotlin.time.Duration.Companion.seconds
fun main() = runBlocking { val socket = "libtmux-home-${UUID.randomUUID()}" val config = ServerConfig.builder() .endpoint(ServerEndpoint.namedSocket(socket)) .configFile(Path.of("/dev/null")) .defaultTimeout(Duration.ofSeconds(5)) .build()
withServer(config) { server -> try { val session = server.newSession("demo")
// Lay out the session: name its window, split it, // add a second window. val first = session.activeWindow ?: error("no active window") val editor = first.rename("editor") val left = editor.activePane ?: error("no active pane") val side = SplitSpec.builder().toRight().detached().build() val right = left.split(side) val tab = WindowSpec.builder().named("logs").detached().build() val logs = session.newWindow(tab)
// Type a command into the new pane and wait for what it prints. right.sendLine("printf 'hello from %s\\n' tmux") val outcome = right.awaitText( "hello from tmux", timeout = 5.seconds ) check(outcome != TextOutcome.TIMED_OUT)
// Move the focus an attached client sees: // the pane, then the window. right.select() logs.select()
// Walk the objects: down from the server, then up from one pane. val sessions = server.sessions() for (each in sessions) { println("session ${each.name}") for (window in each.windows) { val ids = window.panes.joinToString(" ") { "${it.id}" } println(" window ${window.index}:${window.name}: $ids") } }
val pane = server.pane(right.id) ?: error("no pane ${right.id}") val home = pane.window val owner = home.session println( "${pane.id} is in window ${home.name} of session ${owner.name}" ) } catch (error: Exception) { throw IllegalStateException( "tmux quickstart failed", error ) } }}import io.github.libtmux.ServerConfigimport io.github.libtmux.ServerEndpointimport io.github.libtmux.SplitSpecimport io.github.libtmux.TextOutcomeimport io.github.libtmux.WindowSpecimport io.github.libtmux.kotlin.*import java.nio.file.Pathimport java.time.Durationimport java.util.UUIDimport kotlinx.coroutines.NonCancellableimport kotlinx.coroutines.runBlockingimport kotlinx.coroutines.withContextimport kotlin.time.Duration.Companion.seconds
fun main() = runBlocking { val socket = "libtmux-home-${UUID.randomUUID()}" val config = ServerConfig.builder() .endpoint(ServerEndpoint.namedSocket(socket)) .configFile(Path.of("/dev/null")) .defaultTimeout(Duration.ofSeconds(5)) .build()
withServer(config) { server -> try { val session = server.newSession("demo")
// Lay out the session: name its window, split it, // add a second window. val first = session.activeWindow ?: error("no active window") val editor = first.rename("editor") val left = editor.activePane ?: error("no active pane") val side = SplitSpec.builder().toRight().detached().build() val right = left.split(side) val tab = WindowSpec.builder().named("logs").detached().build() val logs = session.newWindow(tab)
// Type a command into the new pane and wait for what it prints. right.sendLine("printf 'hello from %s\\n' tmux") val outcome = right.awaitText( "hello from tmux", timeout = 5.seconds ) check(outcome != TextOutcome.TIMED_OUT)
// Move the focus an attached client sees: // the pane, then the window. right.select() logs.select()
// Walk the objects: down from the server, then up from one pane. val sessions = server.sessions() for (each in sessions) { println("session ${each.name}") for (window in each.windows) { val ids = window.panes.joinToString(" ") { "${it.id}" } println(" window ${window.index}:${window.name}: $ids") } }
val pane = server.pane(right.id) ?: error("no pane ${right.id}") val home = pane.window val owner = home.session println( "${pane.id} is in window ${home.name} of session ${owner.name}" ) } finally { withContext(NonCancellable) { server.killServer() } } }}import io.github.libtmux.ServerConfigimport io.github.libtmux.ServerEndpointimport io.github.libtmux.SplitSpecimport io.github.libtmux.TextOutcomeimport io.github.libtmux.WindowSpecimport io.github.libtmux.kotlin.*import java.nio.file.Pathimport java.time.Durationimport java.util.UUIDimport kotlinx.coroutines.NonCancellableimport kotlinx.coroutines.runBlockingimport kotlinx.coroutines.withContextimport kotlin.time.Duration.Companion.seconds
fun main() = runBlocking { val socket = "libtmux-home-${UUID.randomUUID()}" val config = ServerConfig.builder() .endpoint(ServerEndpoint.namedSocket(socket)) .configFile(Path.of("/dev/null")) .defaultTimeout(Duration.ofSeconds(5)) .build()
withServer(config) { server -> try { val session = server.newSession("demo")
// Lay out the session: name its window, split it, // add a second window. val first = session.activeWindow ?: error("no active window") val editor = first.rename("editor") val left = editor.activePane ?: error("no active pane") val side = SplitSpec.builder().toRight().detached().build() val right = left.split(side) val tab = WindowSpec.builder().named("logs").detached().build() val logs = session.newWindow(tab)
// Type a command into the new pane and wait for what it prints. right.sendLine("printf 'hello from %s\\n' tmux") val outcome = right.awaitText( "hello from tmux", timeout = 5.seconds ) check(outcome != TextOutcome.TIMED_OUT)
// Move the focus an attached client sees: // the pane, then the window. right.select() logs.select()
// Walk the objects: down from the server, then up from one pane. val sessions = server.sessions() for (each in sessions) { println("session ${each.name}") for (window in each.windows) { val ids = window.panes.joinToString(" ") { "${it.id}" } println(" window ${window.index}:${window.name}: $ids") } }
val pane = server.pane(right.id) ?: error("no pane ${right.id}") val home = pane.window val owner = home.session println( "${pane.id} is in window ${home.name} of session ${owner.name}" ) } catch (error: Exception) { throw IllegalStateException( "tmux quickstart failed", error ) } finally { withContext(NonCancellable) { server.killServer() } } }}Run this example
JDK 25 and tmux on Linux/macOS; Gradle resolves Kotlin 2.4.10
Save the program above as src/main/kotlin/Main.kt in a new directory, along with the files below.
Cleanup is omitted; the private tmux server and its temporary files may remain. Select Cleanup to remove them when the program finishes. The program stops its private tmux server and removes any temporary files it created when it finishes. Error handling adds diagnostics; every version checks required results and deadlines.
build.gradle.kts
plugins { kotlin("jvm") version "2.4.10" application}
repositories { mavenCentral() }
dependencies { implementation("io.github.libtmux:libtmux-kotlin:0.1.2")}
java { toolchain { languageVersion.set(JavaLanguageVersion.of(25)) } }kotlin { jvmToolchain(25) }
application { mainClass.set(providers.gradleProperty("exampleMain")) }settings.gradle.kts
rootProject.name = "api-example"gradle.properties
org.gradle.jvmargs=-Xmx2g -XX:MaxMetaspaceSize=768m -Dfile.encoding=UTF-8kotlin.daemon.jvmargs=-Xmx2gorg.gradle.workers.max=2Setup and run
# Save the files above at their displayed relative paths.git clone https://github.com/libtmux/libtmux-java.git libtmux-sourcegit -C libtmux-source checkout --detach e8a39689d8d60968ac978a1dd2a89c6112333896./libtmux-source/gradlew --project-dir . --console=plain --no-daemon --max-workers=2 \ installDist -PexampleMain=MainKtSHELL=/bin/sh build/install/api-example/bin/api-exampleExpected output
session demo window 0:editor: %0 %1 window 1:logs: %2%1 is in window editor of session demoimplementation("io.github.libtmux:libtmux-kotlin:0.1.2")Start with Scala
import io.github.libtmux.{ServerConfig, ServerEndpoint, TextOutcome}import io.github.libtmux.scaladsl.{config => _, *}import java.nio.file.Pathimport java.time.Durationimport java.util.UUIDimport scala.concurrent.duration.DurationIntimport scala.jdk.CollectionConverters.*import scala.util.Using
object Main { def main(args: Array[String]): Unit = { val socket = s"libtmux-home-${UUID.randomUUID()}" val config = ServerConfig.builder() .endpoint(ServerEndpoint.namedSocket(socket)) .configFile(Path.of("/dev/null")) .defaultTimeout(Duration.ofSeconds(5)) .build()
Using.resource(Server.open(config)) { server => val session = server.newSession("demo") val active = session.activeWindow.get val editor = active.rename("editor") val left = editor.activePane.get val right = left.split(_.toRight().detached()) val logs = session.newWindow(_.named("logs").detached())
right.sendLine("printf 'hello from %s\\n' tmux") val seen = right.awaitText("hello from tmux", 5.seconds) assert(seen != TextOutcome.TIMED_OUT)
right.select() logs.select()
val snapshot = server.snapshot() val sessions = snapshot.sessions().asScala for (found <- sessions) { println(s"session ${found.name()}") for (win <- snapshot.windowsOf(found.id()).asScala) { val at = win.context().index().value() val panes = snapshot.panesOf(win.context()).asScala val ids = panes.map(_.id().value()).mkString(" ") println(s" window $at:${win.name()}: $ids") } }
val window = right.window val owner = window.session val id = right.id.value() println(s"$id is in window ${window.name} of session ${owner.name}") } }}import io.github.libtmux.{ServerConfig, ServerEndpoint, TextOutcome}import io.github.libtmux.scaladsl.{config => _, *}import java.nio.file.Pathimport java.time.Durationimport java.util.UUIDimport scala.concurrent.duration.DurationIntimport scala.jdk.CollectionConverters.*import scala.util.Usingimport scala.util.control.NonFatal
object Main { def main(args: Array[String]): Unit = { val socket = s"libtmux-home-${UUID.randomUUID()}" val config = ServerConfig.builder() .endpoint(ServerEndpoint.namedSocket(socket)) .configFile(Path.of("/dev/null")) .defaultTimeout(Duration.ofSeconds(5)) .build()
Using.resource(Server.open(config)) { server => try { val session = server.newSession("demo") val active = session.activeWindow.get val editor = active.rename("editor") val left = editor.activePane.get val right = left.split(_.toRight().detached()) val logs = session.newWindow(_.named("logs").detached())
right.sendLine("printf 'hello from %s\\n' tmux") val seen = right.awaitText("hello from tmux", 5.seconds) assert(seen != TextOutcome.TIMED_OUT)
right.select() logs.select()
val snapshot = server.snapshot() val sessions = snapshot.sessions().asScala for (found <- sessions) { println(s"session ${found.name()}") for (win <- snapshot.windowsOf(found.id()).asScala) { val at = win.context().index().value() val panes = snapshot.panesOf(win.context()).asScala val ids = panes.map(_.id().value()).mkString(" ") println(s" window $at:${win.name()}: $ids") } }
val window = right.window val owner = window.session val id = right.id.value() println(s"$id is in window ${window.name} of session ${owner.name}") } catch { case NonFatal(error) => throw new IllegalStateException( "tmux quickstart failed", error ) } } }}import io.github.libtmux.{ServerConfig, ServerEndpoint, TextOutcome}import io.github.libtmux.scaladsl.{config => _, *}import java.nio.file.Pathimport java.time.Durationimport java.util.UUIDimport scala.concurrent.duration.DurationIntimport scala.jdk.CollectionConverters.*import scala.util.Using
object Main { def main(args: Array[String]): Unit = { val socket = s"libtmux-home-${UUID.randomUUID()}" val config = ServerConfig.builder() .endpoint(ServerEndpoint.namedSocket(socket)) .configFile(Path.of("/dev/null")) .defaultTimeout(Duration.ofSeconds(5)) .build()
Using.resource(Server.open(config)) { server => try { val session = server.newSession("demo") val active = session.activeWindow.get val editor = active.rename("editor") val left = editor.activePane.get val right = left.split(_.toRight().detached()) val logs = session.newWindow(_.named("logs").detached())
right.sendLine("printf 'hello from %s\\n' tmux") val seen = right.awaitText("hello from tmux", 5.seconds) assert(seen != TextOutcome.TIMED_OUT)
right.select() logs.select()
val snapshot = server.snapshot() val sessions = snapshot.sessions().asScala for (found <- sessions) { println(s"session ${found.name()}") for (win <- snapshot.windowsOf(found.id()).asScala) { val at = win.context().index().value() val panes = snapshot.panesOf(win.context()).asScala val ids = panes.map(_.id().value()).mkString(" ") println(s" window $at:${win.name()}: $ids") } }
val window = right.window val owner = window.session val id = right.id.value() println(s"$id is in window ${window.name} of session ${owner.name}") } finally { server.killServer() } } }}import io.github.libtmux.{ServerConfig, ServerEndpoint, TextOutcome}import io.github.libtmux.scaladsl.{config => _, *}import java.nio.file.Pathimport java.time.Durationimport java.util.UUIDimport scala.concurrent.duration.DurationIntimport scala.jdk.CollectionConverters.*import scala.util.Usingimport scala.util.control.NonFatal
object Main { def main(args: Array[String]): Unit = { val socket = s"libtmux-home-${UUID.randomUUID()}" val config = ServerConfig.builder() .endpoint(ServerEndpoint.namedSocket(socket)) .configFile(Path.of("/dev/null")) .defaultTimeout(Duration.ofSeconds(5)) .build()
Using.resource(Server.open(config)) { server => try { val session = server.newSession("demo") val active = session.activeWindow.get val editor = active.rename("editor") val left = editor.activePane.get val right = left.split(_.toRight().detached()) val logs = session.newWindow(_.named("logs").detached())
right.sendLine("printf 'hello from %s\\n' tmux") val seen = right.awaitText("hello from tmux", 5.seconds) assert(seen != TextOutcome.TIMED_OUT)
right.select() logs.select()
val snapshot = server.snapshot() val sessions = snapshot.sessions().asScala for (found <- sessions) { println(s"session ${found.name()}") for (win <- snapshot.windowsOf(found.id()).asScala) { val at = win.context().index().value() val panes = snapshot.panesOf(win.context()).asScala val ids = panes.map(_.id().value()).mkString(" ") println(s" window $at:${win.name()}: $ids") } }
val window = right.window val owner = window.session val id = right.id.value() println(s"$id is in window ${window.name} of session ${owner.name}") } catch { case NonFatal(error) => throw new IllegalStateException( "tmux quickstart failed", error ) } finally { server.killServer() } } }}Run this example
JDK 25 and tmux on Linux/macOS; Scala 3.9.0 Direct facade
Save the program above as src/main/scala/Main.scala in a new directory, along with the files below.
Cleanup is omitted; the private tmux server and its temporary files may remain. Select Cleanup to remove them when the program finishes. The program stops its private tmux server and removes any temporary files it created when it finishes. Error handling adds diagnostics; every version checks required results and deadlines.
build.gradle.kts
plugins { scala application}
repositories { mavenCentral() }
dependencies { implementation("io.github.libtmux:libtmux-scala_3:0.1.2") implementation("org.scala-lang:scala3-library_3:3.9.0")}
java { toolchain { languageVersion.set(JavaLanguageVersion.of(25)) } }
application { mainClass.set(providers.gradleProperty("exampleMain")) }settings.gradle.kts
rootProject.name = "api-example"gradle.properties
org.gradle.jvmargs=-Xmx2g -XX:MaxMetaspaceSize=768m -Dfile.encoding=UTF-8kotlin.daemon.jvmargs=-Xmx2gorg.gradle.workers.max=2Setup and run
# Save the files above at their displayed relative paths.git clone https://github.com/libtmux/libtmux-java.git libtmux-sourcegit -C libtmux-source checkout --detach e8a39689d8d60968ac978a1dd2a89c6112333896./libtmux-source/gradlew --project-dir . --console=plain --no-daemon --max-workers=2 \ installDist -PexampleMain=MainSHELL=/bin/sh build/install/api-example/bin/api-exampleExpected output
session demo window 0:editor: %0 %1 window 1:logs: %2%1 is in window editor of session demolibraryDependencies += "io.github.libtmux" %% "libtmux-scala" % "0.1.2"implementation("io.github.libtmux:libtmux-scala_3:0.1.2")Start with C#
using System;using System.Linq;using System.Threading;using System.Runtime.Versioning;using LibTmux;
[assembly: UnsupportedOSPlatform("windows")]
if (OperatingSystem.IsWindows()){ throw new PlatformNotSupportedException( "This example requires tmux on Unix.");}
using var deadline = new CancellationTokenSource( TimeSpan.FromSeconds(30));var token = deadline.Token;// A private server: a socket and an empty config of its own, so this// neither touches nor is changed by a tmux you already use.var options = new ServerConnectionOptions{ SocketName = "quickstart-" + Guid.NewGuid().ToString("N"), ConfigurationFile = "/dev/null", TmuxBinaryPath = Environment.GetEnvironmentVariable("LIBTMUX_TMUX") ?? "tmux",};
var owned = await Server.CreateOwnedAsync(options, token);Server server = owned.Value;
Session session = await server.CreateSessionAsync( new NewSessionRequest { Name = "demo", Command = "/bin/sh" }, token);
// Lay out the session: name its window, split it, add a second window.// Neither the split nor the new window takes the focus.Window editor = (await session.GetWindowsAsync(token))[0];editor = await editor.RenameAsync("editor", token);Pane left = await editor.GetActivePaneAsync(token);Pane right = await left.SplitAsync( new SplitPaneRequest { Direction = PaneDirection.Right, Command = "/bin/sh", }, token);Window logs = await session.CreateWindowAsync( new NewWindowRequest { Name = "logs", Command = "/bin/sh" }, token);
// Type a command into the new pane and wait for what it prints.await right.SendTextAsync( "printf 'hello from %s\\n' tmux", cancellationToken: token);await TmuxWait.UntilAsync( async cancellation => await right.CaptureAsync( cancellationToken: cancellation), output => output.Any(line => line.Contains("hello from tmux")), TimeSpan.FromSeconds(10), TimeSpan.FromMilliseconds(20), token);
// Move the focus an attached client sees: the pane, then the window.right = await right.SelectAsync(cancellationToken: token);logs = await logs.SelectAsync(token);
// Walk the objects: down from the server, then up from one pane.Server snapshot = await server.CaptureSnapshotAsync( cancellationToken: token);var sessions = snapshot.Sessions;foreach (var each in sessions){ Console.WriteLine("session " + each.Name); var windows = each.Windows; foreach (var placed in windows) { var panes = placed.Panes; Console.WriteLine( $" window {placed.Index}:{placed.Name}: " + string.Join(" ", panes.Select(pane => pane.Id))); }}Pane found = snapshot.Panes.Single(pane => pane.Id == right.Id);Window window = found.Window;Session owner = window.Session;Console.WriteLine( $"{found.Id} is in window {window.Name} of session {owner.Name}");using System;using System.Linq;using System.Threading;using System.Runtime.Versioning;using LibTmux;
[assembly: UnsupportedOSPlatform("windows")]
if (OperatingSystem.IsWindows()){ throw new PlatformNotSupportedException( "This example requires tmux on Unix.");}
using var deadline = new CancellationTokenSource( TimeSpan.FromSeconds(30));var token = deadline.Token;// A private server: a socket and an empty config of its own, so this// neither touches nor is changed by a tmux you already use.var options = new ServerConnectionOptions{ SocketName = "quickstart-" + Guid.NewGuid().ToString("N"), ConfigurationFile = "/dev/null", TmuxBinaryPath = Environment.GetEnvironmentVariable("LIBTMUX_TMUX") ?? "tmux",};
var owned = await Server.CreateOwnedAsync(options, token);Server server = owned.Value;
try{ Session session = await server.CreateSessionAsync( new NewSessionRequest { Name = "demo", Command = "/bin/sh" }, token);
// Lay out the session: name its window, split it, add a second window. // Neither the split nor the new window takes the focus. Window editor = (await session.GetWindowsAsync(token))[0]; editor = await editor.RenameAsync("editor", token); Pane left = await editor.GetActivePaneAsync(token); Pane right = await left.SplitAsync( new SplitPaneRequest { Direction = PaneDirection.Right, Command = "/bin/sh", }, token); Window logs = await session.CreateWindowAsync( new NewWindowRequest { Name = "logs", Command = "/bin/sh" }, token);
// Type a command into the new pane and wait for what it prints. await right.SendTextAsync( "printf 'hello from %s\\n' tmux", cancellationToken: token); await TmuxWait.UntilAsync( async cancellation => await right.CaptureAsync( cancellationToken: cancellation), output => output.Any(line => line.Contains("hello from tmux")), TimeSpan.FromSeconds(10), TimeSpan.FromMilliseconds(20), token);
// Move the focus an attached client sees: the pane, then the window. right = await right.SelectAsync(cancellationToken: token); logs = await logs.SelectAsync(token);
// Walk the objects: down from the server, then up from one pane. Server snapshot = await server.CaptureSnapshotAsync( cancellationToken: token); var sessions = snapshot.Sessions; foreach (var each in sessions) { Console.WriteLine("session " + each.Name); var windows = each.Windows; foreach (var placed in windows) { var panes = placed.Panes; Console.WriteLine( $" window {placed.Index}:{placed.Name}: " + string.Join(" ", panes.Select(pane => pane.Id))); } } Pane found = snapshot.Panes.Single(pane => pane.Id == right.Id); Window window = found.Window; Session owner = window.Session; Console.WriteLine( $"{found.Id} is in window {window.Name} of session {owner.Name}");}catch (Exception error){ throw new InvalidOperationException( "tmux quickstart failed", error);}using System;using System.Linq;using System.Threading;using System.Runtime.Versioning;using LibTmux;
[assembly: UnsupportedOSPlatform("windows")]
if (OperatingSystem.IsWindows()){ throw new PlatformNotSupportedException( "This example requires tmux on Unix.");}
using var deadline = new CancellationTokenSource( TimeSpan.FromSeconds(30));var token = deadline.Token;// A private server: a socket and an empty config of its own, so this// neither touches nor is changed by a tmux you already use.var options = new ServerConnectionOptions{ SocketName = "quickstart-" + Guid.NewGuid().ToString("N"), ConfigurationFile = "/dev/null", TmuxBinaryPath = Environment.GetEnvironmentVariable("LIBTMUX_TMUX") ?? "tmux",};
await using var owned = await Server.CreateOwnedAsync(options, token);Server server = owned.Value;
Session session = await server.CreateSessionAsync( new NewSessionRequest { Name = "demo", Command = "/bin/sh" }, token);
// Lay out the session: name its window, split it, add a second window.// Neither the split nor the new window takes the focus.Window editor = (await session.GetWindowsAsync(token))[0];editor = await editor.RenameAsync("editor", token);Pane left = await editor.GetActivePaneAsync(token);Pane right = await left.SplitAsync( new SplitPaneRequest { Direction = PaneDirection.Right, Command = "/bin/sh", }, token);Window logs = await session.CreateWindowAsync( new NewWindowRequest { Name = "logs", Command = "/bin/sh" }, token);
// Type a command into the new pane and wait for what it prints.await right.SendTextAsync( "printf 'hello from %s\\n' tmux", cancellationToken: token);await TmuxWait.UntilAsync( async cancellation => await right.CaptureAsync( cancellationToken: cancellation), output => output.Any(line => line.Contains("hello from tmux")), TimeSpan.FromSeconds(10), TimeSpan.FromMilliseconds(20), token);
// Move the focus an attached client sees: the pane, then the window.right = await right.SelectAsync(cancellationToken: token);logs = await logs.SelectAsync(token);
// Walk the objects: down from the server, then up from one pane.Server snapshot = await server.CaptureSnapshotAsync( cancellationToken: token);var sessions = snapshot.Sessions;foreach (var each in sessions){ Console.WriteLine("session " + each.Name); var windows = each.Windows; foreach (var placed in windows) { var panes = placed.Panes; Console.WriteLine( $" window {placed.Index}:{placed.Name}: " + string.Join(" ", panes.Select(pane => pane.Id))); }}Pane found = snapshot.Panes.Single(pane => pane.Id == right.Id);Window window = found.Window;Session owner = window.Session;Console.WriteLine( $"{found.Id} is in window {window.Name} of session {owner.Name}");using System;using System.Linq;using System.Threading;using System.Runtime.Versioning;using LibTmux;
[assembly: UnsupportedOSPlatform("windows")]
if (OperatingSystem.IsWindows()){ throw new PlatformNotSupportedException( "This example requires tmux on Unix.");}
using var deadline = new CancellationTokenSource( TimeSpan.FromSeconds(30));var token = deadline.Token;// A private server: a socket and an empty config of its own, so this// neither touches nor is changed by a tmux you already use.var options = new ServerConnectionOptions{ SocketName = "quickstart-" + Guid.NewGuid().ToString("N"), ConfigurationFile = "/dev/null", TmuxBinaryPath = Environment.GetEnvironmentVariable("LIBTMUX_TMUX") ?? "tmux",};
await using var owned = await Server.CreateOwnedAsync(options, token);Server server = owned.Value;
try{ Session session = await server.CreateSessionAsync( new NewSessionRequest { Name = "demo", Command = "/bin/sh" }, token);
// Lay out the session: name its window, split it, add a second window. // Neither the split nor the new window takes the focus. Window editor = (await session.GetWindowsAsync(token))[0]; editor = await editor.RenameAsync("editor", token); Pane left = await editor.GetActivePaneAsync(token); Pane right = await left.SplitAsync( new SplitPaneRequest { Direction = PaneDirection.Right, Command = "/bin/sh", }, token); Window logs = await session.CreateWindowAsync( new NewWindowRequest { Name = "logs", Command = "/bin/sh" }, token);
// Type a command into the new pane and wait for what it prints. await right.SendTextAsync( "printf 'hello from %s\\n' tmux", cancellationToken: token); await TmuxWait.UntilAsync( async cancellation => await right.CaptureAsync( cancellationToken: cancellation), output => output.Any(line => line.Contains("hello from tmux")), TimeSpan.FromSeconds(10), TimeSpan.FromMilliseconds(20), token);
// Move the focus an attached client sees: the pane, then the window. right = await right.SelectAsync(cancellationToken: token); logs = await logs.SelectAsync(token);
// Walk the objects: down from the server, then up from one pane. Server snapshot = await server.CaptureSnapshotAsync( cancellationToken: token); var sessions = snapshot.Sessions; foreach (var each in sessions) { Console.WriteLine("session " + each.Name); var windows = each.Windows; foreach (var placed in windows) { var panes = placed.Panes; Console.WriteLine( $" window {placed.Index}:{placed.Name}: " + string.Join(" ", panes.Select(pane => pane.Id))); } } Pane found = snapshot.Panes.Single(pane => pane.Id == right.Id); Window window = found.Window; Session owner = window.Session; Console.WriteLine( $"{found.Id} is in window {window.Name} of session {owner.Name}");}catch (Exception error){ throw new InvalidOperationException( "tmux quickstart failed", error);}Run this example
.NET SDK 10.0.303, .NET 8 and 10 runtimes, tmux on Linux/macOS
Save the program above as app/Program.cs in a new directory, along with the files below.
Cleanup is omitted; the private tmux server and its temporary files may remain. Select Cleanup to remove them when the program finishes. The program stops its private tmux server and removes any temporary files it created when it finishes. Error handling adds diagnostics; every version checks required results and deadlines.
app/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>app/global.json
{ "sdk": { "version": "10.0.303", "rollForward": "disable", "allowPrerelease": false }, "test": { "runner": "Microsoft.Testing.Platform" }}Setup and run
# Save the files above at their displayed relative paths.cd appdotnet restore Example.csprojdotnet build Example.csproj -c Release --no-restore --warnaserrorexport TMUX_TMPDIR=/tmp/libtmux-dotnet-devmkdir -p "$TMUX_TMPDIR"unset TMUX TMUX_PANEdotnet bin/Release/net8.0/Example.dlldotnet bin/Release/net10.0/Example.dllExpected output
session demo window 0:editor: %0 %1 window 1:logs: %2%1 is in window editor of session demo$ dotnet package add LibTmux.NET 10 SDK: run in your project directory. On .NET 8 or 9, use dotnet add package with the same arguments.
NuGet\Install-Package LibTmux -Version 0.1.1Run in Visual Studio on Windows, in Tools > NuGet Package Manager > Package Manager Console. Choose the target project in that console.
<PackageReference Include="LibTmux" Version="0.1.1" />Add this inside an ItemGroup in your .csproj or .fsproj, then run dotnet restore. For central version management, use the CPM tab.
Directory.Packages.props
Project file (.csproj or .fsproj)
<PackageReference Include="LibTmux" />Save Directory.Packages.props at the solution root, or merge these settings into the existing file. Add the versionless reference inside the project’s ItemGroup, then run dotnet restore.
$ paket add LibTmux --version 0.1.1 --interactiveRequires Paket and a solution initialized with paket init. The interactive prompt selects the projects that should reference the package.
#r "nuget: LibTmux, 0.1.1"Use in an F# .fsx script, dotnet fsi, or a Polyglot Notebook with NuGet support, on .NET 8 or later. This is not a directive for an ordinary compiled project.
#:package LibTmux@0.1.1C# file-based apps require the .NET 10 SDK. Place this at the top of a .cs file, before code, then run dotnet run app.cs. F# scripts use the Script & Interactive tab.
#addin nuget:?package=LibTmux&version=0.1.1&loaddependencies=trueUse Cake.Tool 6 or later for a .cake script on .NET 8 or later, with Cake’s in-process NuGet client enabled. This loads the library and its dependencies; it has no Cake task aliases or executable tool. Cake Frosting projects use PackageReference.
Start with F#
open Systemopen System.Threadingopen LibTmuxopen LibTmux.FSharp
let runAsync () = task { use deadline = new CancellationTokenSource(TimeSpan.FromSeconds 30.) let token = deadline.Token
let options = ServerConnectionOptions( SocketName = "fsharp-" + Guid.NewGuid().ToString("N"), ConfigurationFile = "/dev/null", TmuxBinaryPath = (Environment.GetEnvironmentVariable "LIBTMUX_TMUX" |> Option.ofObj |> Option.defaultValue "tmux") )
let! owned = LibTmux.Server.CreateOwnedAsync(options, token)
let! session = owned.Value.CreateSessionAsync( NewSessionRequest(Name = "demo", Command = "/bin/sh"), token )
// The new session's active window is its first; name it. let! active = session |> Session.windows |> Query.where (WindowFields.active |> Filter.eq true) |> Query.list token
let! editor = active[0] |> Window.rename token "editor"
// Split its active pane; the new pane is on the right and stays // in the background, so the left pane is still active. let! left = editor |> Window.activePane token
let! right = left |> Pane.split token (SplitPaneRequest(Direction = PaneDirection.Right))
// A second window, also left in the background. let! logs = session |> Session.newWindow token (NewWindowRequest(Name = "logs"))
// Type a command and wait for what it prints, not for its echo. let! waited = right |> Pane.sendAndWait token (TimeSpan.FromSeconds 10.) "printf 'hello from %s\\n' tmux" "hello from tmux"
// Select the right pane, then the logs window. let! selected = right |> Pane.select token let! current = logs |> Window.select token
// Walk a snapshot down from the server: sessions, windows, panes. let! server = LibTmux.Server.ConnectAsync(options, token) let! snapshot = server |> Server.capture token SnapshotDepth.Panes let sessions = snapshot.Sessions
for session in sessions do printfn "session %s" session.Name let windows = session.Windows
for window in windows do let panes = window.Panes let ids = [ for pane in panes -> string pane.Id ]
printfn " window %d:%s: %s" window.Index window.Name (String.Join(" ", ids))
// Then up from one pane to its window and session. let pane = snapshot.Panes |> Seq.find (fun pane -> pane.Id = right.Id) let window = pane.Window let owner = window.Session
printfn "%O is in window %s of session %s" pane.Id window.Name owner.Name }
runAsync().GetAwaiter().GetResult()open Systemopen System.Threadingopen LibTmuxopen LibTmux.FSharp
let runAsync () = task { use deadline = new CancellationTokenSource(TimeSpan.FromSeconds 30.) let token = deadline.Token
let options = ServerConnectionOptions( SocketName = "fsharp-" + Guid.NewGuid().ToString("N"), ConfigurationFile = "/dev/null", TmuxBinaryPath = (Environment.GetEnvironmentVariable "LIBTMUX_TMUX" |> Option.ofObj |> Option.defaultValue "tmux") )
let! owned = LibTmux.Server.CreateOwnedAsync(options, token)
let! session = owned.Value.CreateSessionAsync( NewSessionRequest(Name = "demo", Command = "/bin/sh"), token )
// The new session's active window is its first; name it. let! active = session |> Session.windows |> Query.where (WindowFields.active |> Filter.eq true) |> Query.list token
let! editor = active[0] |> Window.rename token "editor"
// Split its active pane; the new pane is on the right and stays // in the background, so the left pane is still active. let! left = editor |> Window.activePane token
let! right = left |> Pane.split token (SplitPaneRequest(Direction = PaneDirection.Right))
// A second window, also left in the background. let! logs = session |> Session.newWindow token (NewWindowRequest(Name = "logs"))
// Type a command and wait for what it prints, not for its echo. let! waited = right |> Pane.sendAndWait token (TimeSpan.FromSeconds 10.) "printf 'hello from %s\\n' tmux" "hello from tmux"
// Select the right pane, then the logs window. let! selected = right |> Pane.select token let! current = logs |> Window.select token
// Walk a snapshot down from the server: sessions, windows, panes. let! server = LibTmux.Server.ConnectAsync(options, token) let! snapshot = server |> Server.capture token SnapshotDepth.Panes let sessions = snapshot.Sessions
for session in sessions do printfn "session %s" session.Name let windows = session.Windows
for window in windows do let panes = window.Panes let ids = [ for pane in panes -> string pane.Id ]
printfn " window %d:%s: %s" window.Index window.Name (String.Join(" ", ids))
// Then up from one pane to its window and session. let pane = snapshot.Panes |> Seq.find (fun pane -> pane.Id = right.Id) let window = pane.Window let owner = window.Session
printfn "%O is in window %s of session %s" pane.Id window.Name owner.Name }
try runAsync().GetAwaiter().GetResult()with error -> raise (InvalidOperationException( "tmux quickstart failed", error))open Systemopen System.Threadingopen LibTmuxopen LibTmux.FSharp
let runAsync () = task { use deadline = new CancellationTokenSource(TimeSpan.FromSeconds 30.) let token = deadline.Token
let options = ServerConnectionOptions( SocketName = "fsharp-" + Guid.NewGuid().ToString("N"), ConfigurationFile = "/dev/null", TmuxBinaryPath = (Environment.GetEnvironmentVariable "LIBTMUX_TMUX" |> Option.ofObj |> Option.defaultValue "tmux") )
use! owned = LibTmux.Server.CreateOwnedAsync(options, token)
let! session = owned.Value.CreateSessionAsync( NewSessionRequest(Name = "demo", Command = "/bin/sh"), token )
// The new session's active window is its first; name it. let! active = session |> Session.windows |> Query.where (WindowFields.active |> Filter.eq true) |> Query.list token
let! editor = active[0] |> Window.rename token "editor"
// Split its active pane; the new pane is on the right and stays // in the background, so the left pane is still active. let! left = editor |> Window.activePane token
let! right = left |> Pane.split token (SplitPaneRequest(Direction = PaneDirection.Right))
// A second window, also left in the background. let! logs = session |> Session.newWindow token (NewWindowRequest(Name = "logs"))
// Type a command and wait for what it prints, not for its echo. let! waited = right |> Pane.sendAndWait token (TimeSpan.FromSeconds 10.) "printf 'hello from %s\\n' tmux" "hello from tmux"
// Select the right pane, then the logs window. let! selected = right |> Pane.select token let! current = logs |> Window.select token
// Walk a snapshot down from the server: sessions, windows, panes. let! server = LibTmux.Server.ConnectAsync(options, token) let! snapshot = server |> Server.capture token SnapshotDepth.Panes let sessions = snapshot.Sessions
for session in sessions do printfn "session %s" session.Name let windows = session.Windows
for window in windows do let panes = window.Panes let ids = [ for pane in panes -> string pane.Id ]
printfn " window %d:%s: %s" window.Index window.Name (String.Join(" ", ids))
// Then up from one pane to its window and session. let pane = snapshot.Panes |> Seq.find (fun pane -> pane.Id = right.Id) let window = pane.Window let owner = window.Session
printfn "%O is in window %s of session %s" pane.Id window.Name owner.Name }
runAsync().GetAwaiter().GetResult()open Systemopen System.Threadingopen LibTmuxopen LibTmux.FSharp
let runAsync () = task { use deadline = new CancellationTokenSource(TimeSpan.FromSeconds 30.) let token = deadline.Token
let options = ServerConnectionOptions( SocketName = "fsharp-" + Guid.NewGuid().ToString("N"), ConfigurationFile = "/dev/null", TmuxBinaryPath = (Environment.GetEnvironmentVariable "LIBTMUX_TMUX" |> Option.ofObj |> Option.defaultValue "tmux") )
use! owned = LibTmux.Server.CreateOwnedAsync(options, token)
let! session = owned.Value.CreateSessionAsync( NewSessionRequest(Name = "demo", Command = "/bin/sh"), token )
// The new session's active window is its first; name it. let! active = session |> Session.windows |> Query.where (WindowFields.active |> Filter.eq true) |> Query.list token
let! editor = active[0] |> Window.rename token "editor"
// Split its active pane; the new pane is on the right and stays // in the background, so the left pane is still active. let! left = editor |> Window.activePane token
let! right = left |> Pane.split token (SplitPaneRequest(Direction = PaneDirection.Right))
// A second window, also left in the background. let! logs = session |> Session.newWindow token (NewWindowRequest(Name = "logs"))
// Type a command and wait for what it prints, not for its echo. let! waited = right |> Pane.sendAndWait token (TimeSpan.FromSeconds 10.) "printf 'hello from %s\\n' tmux" "hello from tmux"
// Select the right pane, then the logs window. let! selected = right |> Pane.select token let! current = logs |> Window.select token
// Walk a snapshot down from the server: sessions, windows, panes. let! server = LibTmux.Server.ConnectAsync(options, token) let! snapshot = server |> Server.capture token SnapshotDepth.Panes let sessions = snapshot.Sessions
for session in sessions do printfn "session %s" session.Name let windows = session.Windows
for window in windows do let panes = window.Panes let ids = [ for pane in panes -> string pane.Id ]
printfn " window %d:%s: %s" window.Index window.Name (String.Join(" ", ids))
// Then up from one pane to its window and session. let pane = snapshot.Panes |> Seq.find (fun pane -> pane.Id = right.Id) let window = pane.Window let owner = window.Session
printfn "%O is in window %s of session %s" pane.Id window.Name owner.Name }
try runAsync().GetAwaiter().GetResult()with error -> raise (InvalidOperationException( "tmux quickstart failed", error))Run this example
.NET SDK 10.0.303, .NET 8 and 10 runtimes, tmux 3.4 or newer on Linux/macOS
Save the program above as app/Program.fs in a new directory, along with the files below.
Cleanup is omitted; the private tmux server and its temporary files may remain. Select Cleanup to remove them when the program finishes. The program stops its private tmux server and removes any temporary files it created when it finishes. Error handling adds diagnostics; every version checks required results and deadlines.
app/Example.fsproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFrameworks>net8.0;net10.0</TargetFrameworks> <LangVersion>10.0</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <DisableImplicitFSharpCoreReference>true</DisableImplicitFSharpCoreReference> <DisableImplicitLibraryPacksFolder>true</DisableImplicitLibraryPacksFolder> </PropertyGroup> <ItemGroup> <Compile Include="Program.fs" /> <PackageReference Include="FSharp.Core" Version="[10.1.303]" /> <PackageReference Include="LibTmux.FSharp" Version="[0.1.1]" /> </ItemGroup></Project>app/global.json
{ "sdk": { "version": "10.0.303", "rollForward": "disable", "allowPrerelease": false }, "test": { "runner": "Microsoft.Testing.Platform" }}Setup and run
# Save the files above at their displayed relative paths.cd appdotnet restore Example.fsprojdotnet build Example.fsproj -c Release --no-restore --warnaserrorexport TMUX_TMPDIR=/tmp/libtmux-dotnet-devmkdir -p "$TMUX_TMPDIR"unset TMUX TMUX_PANEdotnet bin/Release/net8.0/Example.dlldotnet bin/Release/net10.0/Example.dllExpected output
session demo window 0:editor: %0 %1 window 1:logs: %2%1 is in window editor of session demo$ dotnet package add LibTmux.FSharp --version 0.0.0-alpha.18.NET 10 SDK: run in your project directory. On .NET 8 or 9, use dotnet add package with the same arguments.
NuGet\Install-Package LibTmux.FSharp -Version 0.0.0-alpha.18Run in Visual Studio on Windows, in Tools > NuGet Package Manager > Package Manager Console. Choose the target project in that console.
<PackageReference Include="LibTmux.FSharp" Version="0.0.0-alpha.18" />Add this inside an ItemGroup in your .csproj or .fsproj, then run dotnet restore. For central version management, use the CPM tab.
Directory.Packages.props
Project file (.csproj or .fsproj)
<PackageReference Include="LibTmux.FSharp" />Save Directory.Packages.props at the solution root, or merge these settings into the existing file. Add the versionless reference inside the project’s ItemGroup, then run dotnet restore.
$ paket add LibTmux.FSharp --version 0.0.0-alpha.18 --interactiveRequires Paket and a solution initialized with paket init. The interactive prompt selects the projects that should reference the package.
#r "nuget: LibTmux.FSharp, 0.0.0-alpha.18"Use in an F# .fsx script, dotnet fsi, or a Polyglot Notebook with NuGet support, on .NET 8 or later. This is not a directive for an ordinary compiled project.
#:package LibTmux.FSharp@0.0.0-alpha.18C# file-based apps require the .NET 10 SDK. Place this at the top of a .cs file, before code, then run dotnet run app.cs. F# scripts use the Script & Interactive tab.
#addin nuget:?package=LibTmux.FSharp&version=0.0.0-alpha.18&loaddependencies=trueUse Cake.Tool 6 or later for a .cake script on .NET 8 or later, with Cake’s in-process NuGet client enabled. This loads the library and its dependencies; it has no Cake task aliases or executable tool. Cake Frosting projects use PackageReference.
Start with C++
#include <chrono>#include <cstdio>#include <cstdlib>#include <filesystem>#include <iostream>#include <stdexcept>#include <libtmux/libtmux.hpp>
int main() { char directory[] = "/tmp/ltx-cxx-home-XXXXXX"; if (!mkdtemp(directory)) { std::perror("create temporary directory"); return 1; }
const auto socket = std::filesystem::path(directory) / "tmux.sock"; const auto server = libtmux::Server::startable_at_socket_path( socket, "/dev/null", {}, {.timeout = std::chrono::seconds{5}}).value();
const auto work = [&] { const auto session = server.new_session({ .name = "demo", .shell_command = "/bin/sh", }).value();
// Lay out the session: name its window, split it, add a second window. const auto editor = session.active_window().value(); editor.rename("editor").value(); const auto left = editor.active_pane().value(); const auto right = left.split({ .horizontal = true, .shell_command = "/bin/sh", }).value(); const auto logs = session.new_window({ .name = "logs", .shell_command = "/bin/sh", }).value();
// Type a command into the new pane and wait for what it prints. right.send_line("printf 'hello from %s\\n' tmux").value(); const auto ready = right.wait_for_text( "hello from tmux", {.timeout = std::chrono::seconds{5}}).value(); if (!ready.matched) throw std::runtime_error("output did not arrive");
// Move the focus an attached client sees: the pane, then the window. right.select().value(); logs.select().value();
// Walk the objects: down from the server, then up from one pane. const auto sessions = server.sessions().value(); for (const auto& each : sessions) { std::cout << "session " << each.name() << '\n'; const auto windows = each.windows().value(); for (const auto& window : windows) { std::cout << " window " << window.index() << ':' << window.name() << ':'; const auto panes = window.panes().value(); for (const auto& pane : panes) { std::cout << ' ' << pane.id().value(); } std::cout << '\n'; } } const auto window = right.window().value(); const auto owner = window.session().value(); std::cout << right.id().value() << " is in window " << window.name() << " of session " << owner.name() << '\n'; };
work();}#include <chrono>#include <cstdio>#include <cstdlib>#include <filesystem>#include <iostream>#include <stdexcept>#include <utility>#include <libtmux/libtmux.hpp>
int main() { char directory[] = "/tmp/ltx-cxx-home-XXXXXX"; if (!mkdtemp(directory)) { std::perror("create temporary directory"); return 1; }
const auto checked = [](auto result) { if (!result) throw std::runtime_error(result.error().diagnostic); return std::move(result).value(); };
const auto socket = std::filesystem::path(directory) / "tmux.sock"; const auto server = checked(libtmux::Server::startable_at_socket_path( socket, "/dev/null", {}, {.timeout = std::chrono::seconds{5}}));
const auto work = [&] { const auto session = checked(server.new_session({ .name = "demo", .shell_command = "/bin/sh", }));
// Lay out the session: name its window, split it, add a second window. const auto editor = checked(session.active_window()); checked(editor.rename("editor")); const auto left = checked(editor.active_pane()); const auto right = checked(left.split({ .horizontal = true, .shell_command = "/bin/sh", })); const auto logs = checked(session.new_window({ .name = "logs", .shell_command = "/bin/sh", }));
// Type a command into the new pane and wait for what it prints. checked(right.send_line("printf 'hello from %s\\n' tmux")); const auto ready = checked(right.wait_for_text( "hello from tmux", {.timeout = std::chrono::seconds{5}})); if (!ready.matched) throw std::runtime_error("output did not arrive");
// Move the focus an attached client sees: the pane, then the window. checked(right.select()); checked(logs.select());
// Walk the objects: down from the server, then up from one pane. const auto sessions = checked(server.sessions()); for (const auto& each : sessions) { std::cout << "session " << each.name() << '\n'; const auto windows = checked(each.windows()); for (const auto& window : windows) { std::cout << " window " << window.index() << ':' << window.name() << ':'; const auto panes = checked(window.panes()); for (const auto& pane : panes) { std::cout << ' ' << pane.id().value(); } std::cout << '\n'; } } const auto window = checked(right.window()); const auto owner = checked(window.session()); std::cout << right.id().value() << " is in window " << window.name() << " of session " << owner.name() << '\n'; };
int status = 0; try { work(); } catch (const std::exception& error) { std::fprintf(stderr, "%s\n", error.what()); status = 1; } return status;}#include <chrono>#include <cstdio>#include <cstdlib>#include <filesystem>#include <iostream>#include <stdexcept>#include <utility>#include <libtmux/libtmux.hpp>
int main() { char directory[] = "/tmp/ltx-cxx-home-XXXXXX"; if (!mkdtemp(directory)) { std::perror("create temporary directory"); return 1; }
const auto socket = std::filesystem::path(directory) / "tmux.sock"; auto created = libtmux::Server::startable_at_socket_path( socket, "/dev/null", {}, {.timeout = std::chrono::seconds{5}}); if (!created) { std::fprintf(stderr, "%s\n", created.error().diagnostic.c_str()); std::filesystem::remove_all(directory); return 1; } const auto server = std::move(created).value();
const auto work = [&] { const auto session = server.new_session({ .name = "demo", .shell_command = "/bin/sh", }).value();
// Lay out the session: name its window, split it, add a second window. const auto editor = session.active_window().value(); editor.rename("editor").value(); const auto left = editor.active_pane().value(); const auto right = left.split({ .horizontal = true, .shell_command = "/bin/sh", }).value(); const auto logs = session.new_window({ .name = "logs", .shell_command = "/bin/sh", }).value();
// Type a command into the new pane and wait for what it prints. right.send_line("printf 'hello from %s\\n' tmux").value(); const auto ready = right.wait_for_text( "hello from tmux", {.timeout = std::chrono::seconds{5}}).value(); if (!ready.matched) throw std::runtime_error("output did not arrive");
// Move the focus an attached client sees: the pane, then the window. right.select().value(); logs.select().value();
// Walk the objects: down from the server, then up from one pane. const auto sessions = server.sessions().value(); for (const auto& each : sessions) { std::cout << "session " << each.name() << '\n'; const auto windows = each.windows().value(); for (const auto& window : windows) { std::cout << " window " << window.index() << ':' << window.name() << ':'; const auto panes = window.panes().value(); for (const auto& pane : panes) { std::cout << ' ' << pane.id().value(); } std::cout << '\n'; } } const auto window = right.window().value(); const auto owner = window.session().value(); std::cout << right.id().value() << " is in window " << window.name() << " of session " << owner.name() << '\n'; };
int status = 0; try { work(); } catch (const std::exception& error) { std::fprintf(stderr, "%s\n", error.what()); status = 1; }
if (std::filesystem::exists(socket)) { server.kill().value(); } std::filesystem::remove_all(directory); return status;}#include <chrono>#include <cstdio>#include <cstdlib>#include <filesystem>#include <iostream>#include <stdexcept>#include <utility>#include <libtmux/libtmux.hpp>
int main() { char directory[] = "/tmp/ltx-cxx-home-XXXXXX"; if (!mkdtemp(directory)) { std::perror("create temporary directory"); return 1; }
const auto checked = [](auto result) { if (!result) throw std::runtime_error(result.error().diagnostic); return std::move(result).value(); };
const auto socket = std::filesystem::path(directory) / "tmux.sock"; auto created = libtmux::Server::startable_at_socket_path( socket, "/dev/null", {}, {.timeout = std::chrono::seconds{5}}); if (!created) { std::fprintf(stderr, "%s\n", created.error().diagnostic.c_str()); std::filesystem::remove_all(directory); return 1; } const auto server = std::move(created).value();
const auto work = [&] { const auto session = checked(server.new_session({ .name = "demo", .shell_command = "/bin/sh", }));
// Lay out the session: name its window, split it, add a second window. const auto editor = checked(session.active_window()); checked(editor.rename("editor")); const auto left = checked(editor.active_pane()); const auto right = checked(left.split({ .horizontal = true, .shell_command = "/bin/sh", })); const auto logs = checked(session.new_window({ .name = "logs", .shell_command = "/bin/sh", }));
// Type a command into the new pane and wait for what it prints. checked(right.send_line("printf 'hello from %s\\n' tmux")); const auto ready = checked(right.wait_for_text( "hello from tmux", {.timeout = std::chrono::seconds{5}})); if (!ready.matched) throw std::runtime_error("output did not arrive");
// Move the focus an attached client sees: the pane, then the window. checked(right.select()); checked(logs.select());
// Walk the objects: down from the server, then up from one pane. const auto sessions = checked(server.sessions()); for (const auto& each : sessions) { std::cout << "session " << each.name() << '\n'; const auto windows = checked(each.windows()); for (const auto& window : windows) { std::cout << " window " << window.index() << ':' << window.name() << ':'; const auto panes = checked(window.panes()); for (const auto& pane : panes) { std::cout << ' ' << pane.id().value(); } std::cout << '\n'; } } const auto window = checked(right.window()); const auto owner = checked(window.session()); std::cout << right.id().value() << " is in window " << window.name() << " of session " << owner.name() << '\n'; };
int status = 0; try { work(); } catch (const std::exception& error) { std::fprintf(stderr, "%s\n", error.what()); status = 1; }
if (std::filesystem::exists(socket)) { server.kill().value(); } std::filesystem::remove_all(directory); return status;}Run this example
CMake 3.25+, Clang 18 with matching libc++ development files, C++23, tmux on Linux/macOS
Save the program above as main.cpp in a new directory, along with the files below.
Cleanup is omitted; the private tmux server and its temporary files may remain. Select Cleanup to remove them when the program finishes. The program stops its private tmux server and removes any temporary files it created when it finishes. Error handling adds diagnostics; every version checks required results and deadlines.
CMakeLists.txt
cmake_minimum_required(VERSION 3.25)project(libtmux_api_example LANGUAGES CXX)
find_package(libtmux REQUIRED)
add_executable(api_example main.cpp)target_link_libraries(api_example PRIVATE libtmux::libtmux)Setup and run
# Save the files above at their displayed relative paths.git clone https://github.com/libtmux/libtmux-cxx.git libtmux-sourcegit -C libtmux-source checkout --detach 888167d2d908e7f1c0e6969f96c5582edd4ac8f2cmake -S libtmux-source -B library \ -DCMAKE_TOOLCHAIN_FILE="$PWD/libtmux-source/cmake/toolchains/clang-libcxx.cmake" \ -DCMAKE_BUILD_TYPE=Release -DLIBTMUX_BUILD_TESTS=OFF -DLIBTMUX_BUILD_EXAMPLES=OFF \ -DLIBTMUX_BUILD_TESTING_LIBRARY=OFF -DLIBTMUX_CXX_STANDARD=23 \ -DCMAKE_CXX_COMPILER=clang++cmake --build library -j 2cmake --install library --prefix "$PWD/prefix"cmake -S . -B build -DCMAKE_PREFIX_PATH="$PWD/prefix" -DCMAKE_CXX_COMPILER=clang++ \ -DCMAKE_CXX_FLAGS=-stdlib=libc++ -DCMAKE_CXX_STANDARD=23cmake --build build -j 2build/api_exampleExpected output
session demo window 0:editor: %0 %1 window 1:logs: %2%1 is in window editor of session demoName a tag or a commit, never a moving branch. Built this way the library brings nothing else: its tests, examples and MCP server all default off when it is not the top-level project.
This repository is a vcpkg git registry, not a curated-registry port. Put this in vcpkg-configuration.json, add "libtmux" to your manifest, and run vcpkg x-update-baseline to fill the baseline.
Then add_subdirectory(third_party/libtmux) and link libtmux::libtmux.
Start with Swift
import Foundationimport LibTmux
@mainstruct Quickstart { static func main() async throws { let server = try Server( socketName: "libtmux-home-\(UUID().uuidString)", configurationFile: "/dev/null" )
try await work(server) }
static func work(_ server: Server) async throws { let session = try await server.newSession( named: "demo", shell: "/bin/sh" ) let layout = try await server.snapshot() guard let editor = layout.windows(of: session).first, let left = layout.panes(of: editor).first(where: \.isActive) else { throw QuickstartError.missing } try await server.rename(editor, to: "editor") let right = try await server.split( left, direction: .right, shell: "/bin/sh" ) let logs = try await server.newWindow( in: session, named: "logs", shell: "/bin/sh" )
try await server.run("printf 'hello from %s\\n' tmux", in: right) let ready = try RegexPattern("^hello from tmux$") let result = try await server.waitForOutput( in: right, matching: [ready] ) guard result.outcome == .matched else { throw QuickstartError.outputTimedOut }
try await server.select(right) try await server.select(logs.link)
let snapshot = try await server.snapshot() for session in snapshot.sessions { print("session \(session.name)") let windows = snapshot.windows(of: session) let links = snapshot.windowLinks(of: session) for (window, link) in zip(windows, links) { let panes = snapshot.panes(of: window) let ids = panes.map { $0.id.rawValue }.joined(separator: " ") print(" window \(link.index):\(window.name): \(ids)") } }
let home = right.windowID guard let window = snapshot.windows.first(where: { $0.id == home }), let owner = snapshot.sessions(of: window).first else { throw QuickstartError.missing } print("\(right.id.rawValue) is in window \(window.name)" + " of session \(owner.name)") }
enum QuickstartError: Error { case missing case outputTimedOut }}import Foundationimport LibTmux
@mainstruct Quickstart { static func main() async throws { let server = try Server( socketName: "libtmux-home-\(UUID().uuidString)", configurationFile: "/dev/null" )
do { try await work(server) } catch { print("tmux quickstart failed: \(error)") throw error } }
static func work(_ server: Server) async throws { let session = try await server.newSession( named: "demo", shell: "/bin/sh" ) let layout = try await server.snapshot() guard let editor = layout.windows(of: session).first, let left = layout.panes(of: editor).first(where: \.isActive) else { throw QuickstartError.missing } try await server.rename(editor, to: "editor") let right = try await server.split( left, direction: .right, shell: "/bin/sh" ) let logs = try await server.newWindow( in: session, named: "logs", shell: "/bin/sh" )
try await server.run("printf 'hello from %s\\n' tmux", in: right) let ready = try RegexPattern("^hello from tmux$") let result = try await server.waitForOutput( in: right, matching: [ready] ) guard result.outcome == .matched else { throw QuickstartError.outputTimedOut }
try await server.select(right) try await server.select(logs.link)
let snapshot = try await server.snapshot() for session in snapshot.sessions { print("session \(session.name)") let windows = snapshot.windows(of: session) let links = snapshot.windowLinks(of: session) for (window, link) in zip(windows, links) { let panes = snapshot.panes(of: window) let ids = panes.map { $0.id.rawValue }.joined(separator: " ") print(" window \(link.index):\(window.name): \(ids)") } }
let home = right.windowID guard let window = snapshot.windows.first(where: { $0.id == home }), let owner = snapshot.sessions(of: window).first else { throw QuickstartError.missing } print("\(right.id.rawValue) is in window \(window.name)" + " of session \(owner.name)") }
enum QuickstartError: Error { case missing case outputTimedOut }}import Foundationimport LibTmux
@mainstruct Quickstart { static func main() async throws { let server = try Server( socketName: "libtmux-home-\(UUID().uuidString)", configurationFile: "/dev/null" )
do { try await work(server) } catch { if try await server.isRunning() { try await server.killServer() } throw error } try await server.killServer() }
static func work(_ server: Server) async throws { let session = try await server.newSession( named: "demo", shell: "/bin/sh" ) let layout = try await server.snapshot() guard let editor = layout.windows(of: session).first, let left = layout.panes(of: editor).first(where: \.isActive) else { throw QuickstartError.missing } try await server.rename(editor, to: "editor") let right = try await server.split( left, direction: .right, shell: "/bin/sh" ) let logs = try await server.newWindow( in: session, named: "logs", shell: "/bin/sh" )
try await server.run("printf 'hello from %s\\n' tmux", in: right) let ready = try RegexPattern("^hello from tmux$") let result = try await server.waitForOutput( in: right, matching: [ready] ) guard result.outcome == .matched else { throw QuickstartError.outputTimedOut }
try await server.select(right) try await server.select(logs.link)
let snapshot = try await server.snapshot() for session in snapshot.sessions { print("session \(session.name)") let windows = snapshot.windows(of: session) let links = snapshot.windowLinks(of: session) for (window, link) in zip(windows, links) { let panes = snapshot.panes(of: window) let ids = panes.map { $0.id.rawValue }.joined(separator: " ") print(" window \(link.index):\(window.name): \(ids)") } }
let home = right.windowID guard let window = snapshot.windows.first(where: { $0.id == home }), let owner = snapshot.sessions(of: window).first else { throw QuickstartError.missing } print("\(right.id.rawValue) is in window \(window.name)" + " of session \(owner.name)") }
enum QuickstartError: Error { case missing case outputTimedOut }}import Foundationimport LibTmux
@mainstruct Quickstart { static func main() async throws { let server = try Server( socketName: "libtmux-home-\(UUID().uuidString)", configurationFile: "/dev/null" )
do { try await work(server) } catch { print("tmux quickstart failed: \(error)") if try await server.isRunning() { try await server.killServer() } throw error } try await server.killServer() }
static func work(_ server: Server) async throws { let session = try await server.newSession( named: "demo", shell: "/bin/sh" ) let layout = try await server.snapshot() guard let editor = layout.windows(of: session).first, let left = layout.panes(of: editor).first(where: \.isActive) else { throw QuickstartError.missing } try await server.rename(editor, to: "editor") let right = try await server.split( left, direction: .right, shell: "/bin/sh" ) let logs = try await server.newWindow( in: session, named: "logs", shell: "/bin/sh" )
try await server.run("printf 'hello from %s\\n' tmux", in: right) let ready = try RegexPattern("^hello from tmux$") let result = try await server.waitForOutput( in: right, matching: [ready] ) guard result.outcome == .matched else { throw QuickstartError.outputTimedOut }
try await server.select(right) try await server.select(logs.link)
let snapshot = try await server.snapshot() for session in snapshot.sessions { print("session \(session.name)") let windows = snapshot.windows(of: session) let links = snapshot.windowLinks(of: session) for (window, link) in zip(windows, links) { let panes = snapshot.panes(of: window) let ids = panes.map { $0.id.rawValue }.joined(separator: " ") print(" window \(link.index):\(window.name): \(ids)") } }
let home = right.windowID guard let window = snapshot.windows.first(where: { $0.id == home }), let owner = snapshot.sessions(of: window).first else { throw QuickstartError.missing } print("\(right.id.rawValue) is in window \(window.name)" + " of session \(owner.name)") }
enum QuickstartError: Error { case missing case outputTimedOut }}Run this example
Swift 6.2+, tmux on Linux/macOS
Save the program above as Sources/Main.swift in a new directory, along with the files below.
Cleanup is omitted; the private tmux server and its temporary files may remain. Select Cleanup to remove them when the program finishes. The program stops its private tmux server and removes any temporary files it created when it finishes. Error handling adds diagnostics; every version checks required results and deadlines.
Package.swift
// swift-tools-version: 6.2import PackageDescription
let package = Package( name: "ApiExample", platforms: [.macOS(.v13)], dependencies: [ .package( url: "https://github.com/libtmux/libtmux-swift.git", from: "0.1.1" ) ], targets: [ .executableTarget( name: "ApiExample", dependencies: [ .product(name: "LibTmux", package: "libtmux-swift"), ], path: "Sources" ) ])Setup and run
# Save the files above at their displayed relative paths.swift build --jobs 2 --product ApiExampleunset TMUX TMUX_PANEexport ENV=/dev/null BASH_ENV=/dev/null SHELL=/bin/sh.build/debug/ApiExampleExpected output
session demo window 0:editor: %0 %1 window 1:logs: %2%1 is in window editor of session demoA range from 0.1.0 up to the next major version. Any 0.1.N release may change the API, so pin `exact:` instead to avoid a break.
Start with OCaml
open Libtmuxmodule Client = Libtmux_unix.Clientmodule Workspace = Libtmux_unix.Workspacemodule Config = Libtmux_workspace.Configmodule Plan = Libtmux_workspace.Planmodule Execution = Libtmux_workspace.Execution
let get = function | Ok value -> value | Error error -> failwith (Format.asprintf "%a" Error.pp error)
let capture_graph client (initial : Created.t) spawn = let linked = get (Client.create_session client ~name:"linked" ~window_name:"linked-home" ~spawn ()) in let pane = Snapshot.find_pane (get (Client.capture client)) (Pane.Target.id linked.pane) |> Option.get in let text = "showcase ready" in ignore (get (Client.wait_for_text ~timeout:0.5 client pane ~text)); get (Client.link_window client initial.window ~session:linked.session ~index:7); get (Client.capture client)
let print_graph snapshot = Snapshot.sessions snapshot |> Iarray.iter (fun session -> Session.window_links session |> Iarray.iter (fun link -> let window = Window_link.window link in Printf.printf "%s/%d %s: %d pane(s)\n" (Session.name session) (Window_link.index link) (Window.name window) (Iarray.length (Window.panes window)))); print_endline "graph: 2 sessions, 2 windows, 3 links, 2 panes"
let with_demo binary use = let directory = Filename.temp_dir "libtmux-ocaml-showcase-" "" in Fun.protect ~finally:(fun () -> Sys.readdir directory |> Array.iter (fun name -> Sys.remove (Filename.concat directory name)); Unix.rmdir directory) (fun () -> let socket = Filename.concat directory "server" in (* Give this private daemon a lifetime even if startup fails. *) let config_file = Filename.concat directory "tmux.conf" in Out_channel.with_open_text config_file (fun output -> output_string output "set-option -s exit-unattached on\n"); let wrapper = Filename.concat directory "tmux" in Out_channel.with_open_text wrapper (fun output -> Printf.fprintf output "#!/bin/sh\nexec %s -f %s \"$@\"\n" (Filename.quote binary) (Filename.quote config_file)); Unix.chmod wrapper 0o700; let channel = Unix.open_process_args_in binary [| binary; "-V" |] in let version = Fun.protect ~finally:(fun () -> if Unix.close_process_in channel <> Unix.WEXITED 0 then failwith "tmux version discovery failed") (fun () -> String.trim (input_line channel)) in if not (String.starts_with ~prefix:"tmux " version) then failwith "invalid tmux version"; let version = String.sub version 5 (String.length version - 5) in let ready = Filename.concat directory "ready.txt" in Out_channel.with_open_text ready (fun output -> output_string output "showcase ready\n"); let spawn = Spawn.make (Exec { program = "/bin/cat"; args = [ "-u"; ready; "-" ] }) in let config = match Config.make ~directory ~session:"showcase" [ Config.window ~name:"editor" [ Config.pane ~spawn () ] ] with | Ok value -> value | Error error -> failwith (Format.asprintf "%a" Config.pp_error error) in let plan = match Plan.make ~endpoint:(Endpoint.socket_path socket) ~version ~observed:None config with | Ok value -> value | Error error -> failwith (Format.asprintf "%a" Plan.pp_error error) in let operation = get (Workspace.submit_bootstrap ~binary:wrapper plan) in Fun.protect ~finally:(fun () -> get (Workspace.close operation)) (fun () -> let receipt = get (Workspace.await operation) in if receipt.status <> Execution.Succeeded then failwith "workspace setup failed"; let client = Option.get (Workspace.client operation) in let initial = List.hd (Iarray.get receipt.steps 0).created in Printf.printf "socket=%s\n%!" socket; let pane = Snapshot.find_pane (get (Client.capture client)) (Pane.Target.id initial.pane) |> Option.get in ignore (get (Client.wait_for_text ~timeout:0.5 client pane ~text:"showcase ready")); use client initial spawn))
let () = let binary = if Array.length Sys.argv = 2 then Sys.argv.(1) else "tmux" in let snapshot = with_demo binary capture_graph in print_graph snapshotopen Libtmuxmodule Client = Libtmux_unix.Clientmodule Workspace = Libtmux_unix.Workspacemodule Config = Libtmux_workspace.Configmodule Plan = Libtmux_workspace.Planmodule Execution = Libtmux_workspace.Execution
let get = function | Ok value -> value | Error error -> failwith (Format.asprintf "%a" Error.pp error)
let capture_graph client (initial : Created.t) spawn = let linked = get (Client.create_session client ~name:"linked" ~window_name:"linked-home" ~spawn ()) in let pane = Snapshot.find_pane (get (Client.capture client)) (Pane.Target.id linked.pane) |> Option.get in let text = "showcase ready" in ignore (get (Client.wait_for_text ~timeout:0.5 client pane ~text)); get (Client.link_window client initial.window ~session:linked.session ~index:7); get (Client.capture client)
let print_graph snapshot = Snapshot.sessions snapshot |> Iarray.iter (fun session -> Session.window_links session |> Iarray.iter (fun link -> let window = Window_link.window link in Printf.printf "%s/%d %s: %d pane(s)\n" (Session.name session) (Window_link.index link) (Window.name window) (Iarray.length (Window.panes window)))); print_endline "graph: 2 sessions, 2 windows, 3 links, 2 panes"
let with_demo binary use = let directory = Filename.temp_dir "libtmux-ocaml-showcase-" "" in Fun.protect ~finally:(fun () -> Sys.readdir directory |> Array.iter (fun name -> Sys.remove (Filename.concat directory name)); Unix.rmdir directory) (fun () -> let socket = Filename.concat directory "server" in (* Give this private daemon a lifetime even if startup fails. *) let config_file = Filename.concat directory "tmux.conf" in Out_channel.with_open_text config_file (fun output -> output_string output "set-option -s exit-unattached on\n"); let wrapper = Filename.concat directory "tmux" in Out_channel.with_open_text wrapper (fun output -> Printf.fprintf output "#!/bin/sh\nexec %s -f %s \"$@\"\n" (Filename.quote binary) (Filename.quote config_file)); Unix.chmod wrapper 0o700; let channel = Unix.open_process_args_in binary [| binary; "-V" |] in let version = Fun.protect ~finally:(fun () -> if Unix.close_process_in channel <> Unix.WEXITED 0 then failwith "tmux version discovery failed") (fun () -> String.trim (input_line channel)) in if not (String.starts_with ~prefix:"tmux " version) then failwith "invalid tmux version"; let version = String.sub version 5 (String.length version - 5) in let ready = Filename.concat directory "ready.txt" in Out_channel.with_open_text ready (fun output -> output_string output "showcase ready\n"); let spawn = Spawn.make (Exec { program = "/bin/cat"; args = [ "-u"; ready; "-" ] }) in let config = match Config.make ~directory ~session:"showcase" [ Config.window ~name:"editor" [ Config.pane ~spawn () ] ] with | Ok value -> value | Error error -> failwith (Format.asprintf "%a" Config.pp_error error) in let plan = match Plan.make ~endpoint:(Endpoint.socket_path socket) ~version ~observed:None config with | Ok value -> value | Error error -> failwith (Format.asprintf "%a" Plan.pp_error error) in let operation = get (Workspace.submit_bootstrap ~binary:wrapper plan) in Fun.protect ~finally:(fun () -> get (Workspace.close operation)) (fun () -> let receipt = get (Workspace.await operation) in if receipt.status <> Execution.Succeeded then failwith "workspace setup failed"; let client = Option.get (Workspace.client operation) in let initial = List.hd (Iarray.get receipt.steps 0).created in Printf.printf "socket=%s\n%!" socket; let pane = Snapshot.find_pane (get (Client.capture client)) (Pane.Target.id initial.pane) |> Option.get in ignore (get (Client.wait_for_text ~timeout:0.5 client pane ~text:"showcase ready")); use client initial spawn))
let () = let binary = if Array.length Sys.argv = 2 then Sys.argv.(1) else "tmux" in let snapshot = with_demo binary capture_graph in print_graph snapshotopen Libtmuxmodule Client = Libtmux_unix.Clientmodule Workspace = Libtmux_unix.Workspacemodule Config = Libtmux_workspace.Configmodule Plan = Libtmux_workspace.Planmodule Execution = Libtmux_workspace.Execution
let get = function | Ok value -> value | Error error -> failwith (Format.asprintf "%a" Error.pp error)
let capture_graph client (initial : Created.t) spawn = let linked = get (Client.create_session client ~name:"linked" ~window_name:"linked-home" ~spawn ()) in let pane = Snapshot.find_pane (get (Client.capture client)) (Pane.Target.id linked.pane) |> Option.get in let text = "showcase ready" in ignore (get (Client.wait_for_text ~timeout:0.5 client pane ~text)); get (Client.link_window client initial.window ~session:linked.session ~index:7); get (Client.capture client)
let print_graph snapshot = Snapshot.sessions snapshot |> Iarray.iter (fun session -> Session.window_links session |> Iarray.iter (fun link -> let window = Window_link.window link in Printf.printf "%s/%d %s: %d pane(s)\n" (Session.name session) (Window_link.index link) (Window.name window) (Iarray.length (Window.panes window)))); assert (Iarray.length (Snapshot.sessions snapshot) = 2); assert (Iarray.length (Snapshot.windows snapshot) = 2); assert (Iarray.length (Snapshot.window_links snapshot) = 3); assert (Iarray.length (Snapshot.panes snapshot) = 2); print_endline "graph: 2 sessions, 2 windows, 3 links, 2 panes"
let with_demo binary use = let directory = Filename.temp_dir "libtmux-ocaml-showcase-" "" in Fun.protect ~finally:(fun () -> Sys.readdir directory |> Array.iter (fun name -> Sys.remove (Filename.concat directory name)); Unix.rmdir directory) (fun () -> let socket = Filename.concat directory "server" in (* Give this private daemon a lifetime even if startup fails. *) let config_file = Filename.concat directory "tmux.conf" in Out_channel.with_open_text config_file (fun output -> output_string output "set-option -s exit-unattached on\n"); let wrapper = Filename.concat directory "tmux" in Out_channel.with_open_text wrapper (fun output -> Printf.fprintf output "#!/bin/sh\nexec %s -f %s \"$@\"\n" (Filename.quote binary) (Filename.quote config_file)); Unix.chmod wrapper 0o700; let channel = Unix.open_process_args_in binary [| binary; "-V" |] in let version = Fun.protect ~finally:(fun () -> if Unix.close_process_in channel <> Unix.WEXITED 0 then failwith "tmux version discovery failed") (fun () -> String.trim (input_line channel)) in if not (String.starts_with ~prefix:"tmux " version) then failwith "invalid tmux version"; let version = String.sub version 5 (String.length version - 5) in let ready = Filename.concat directory "ready.txt" in Out_channel.with_open_text ready (fun output -> output_string output "showcase ready\n"); let spawn = Spawn.make (Exec { program = "/bin/cat"; args = [ "-u"; ready; "-" ] }) in let config = match Config.make ~directory ~session:"showcase" [ Config.window ~name:"editor" [ Config.pane ~spawn () ] ] with | Ok value -> value | Error error -> failwith (Format.asprintf "%a" Config.pp_error error) in let plan = match Plan.make ~endpoint:(Endpoint.socket_path socket) ~version ~observed:None config with | Ok value -> value | Error error -> failwith (Format.asprintf "%a" Plan.pp_error error) in let operation = get (Workspace.submit_bootstrap ~binary:wrapper plan) in Fun.protect ~finally:(fun () -> get (Workspace.close operation)) (fun () -> let receipt = get (Workspace.await operation) in if receipt.status <> Execution.Succeeded then failwith "workspace setup failed"; let client = Option.get (Workspace.client operation) in let initial = List.hd (Iarray.get receipt.steps 0).created in Printf.printf "socket=%s\n%!" socket; let pane = Snapshot.find_pane (get (Client.capture client)) (Pane.Target.id initial.pane) |> Option.get in ignore (get (Client.wait_for_text ~timeout:0.5 client pane ~text:"showcase ready")); use client initial spawn))
let () = let binary = if Array.length Sys.argv = 2 then Sys.argv.(1) else "tmux" in let snapshot = with_demo binary capture_graph in print_graph snapshotopen Libtmuxmodule Client = Libtmux_unix.Clientmodule Workspace = Libtmux_unix.Workspacemodule Config = Libtmux_workspace.Configmodule Plan = Libtmux_workspace.Planmodule Execution = Libtmux_workspace.Execution
let get = function | Ok value -> value | Error error -> failwith (Format.asprintf "%a" Error.pp error)
let capture_graph client (initial : Created.t) spawn = let linked = get (Client.create_session client ~name:"linked" ~window_name:"linked-home" ~spawn ()) in let pane = Snapshot.find_pane (get (Client.capture client)) (Pane.Target.id linked.pane) |> Option.get in let text = "showcase ready" in ignore (get (Client.wait_for_text ~timeout:0.5 client pane ~text)); get (Client.link_window client initial.window ~session:linked.session ~index:7); get (Client.capture client)
let print_graph snapshot = Snapshot.sessions snapshot |> Iarray.iter (fun session -> Session.window_links session |> Iarray.iter (fun link -> let window = Window_link.window link in Printf.printf "%s/%d %s: %d pane(s)\n" (Session.name session) (Window_link.index link) (Window.name window) (Iarray.length (Window.panes window)))); assert (Iarray.length (Snapshot.sessions snapshot) = 2); assert (Iarray.length (Snapshot.windows snapshot) = 2); assert (Iarray.length (Snapshot.window_links snapshot) = 3); assert (Iarray.length (Snapshot.panes snapshot) = 2); print_endline "graph: 2 sessions, 2 windows, 3 links, 2 panes"
let with_demo binary use = let directory = Filename.temp_dir "libtmux-ocaml-showcase-" "" in Fun.protect ~finally:(fun () -> Sys.readdir directory |> Array.iter (fun name -> Sys.remove (Filename.concat directory name)); Unix.rmdir directory) (fun () -> let socket = Filename.concat directory "server" in (* Give this private daemon a lifetime even if startup fails. *) let config_file = Filename.concat directory "tmux.conf" in Out_channel.with_open_text config_file (fun output -> output_string output "set-option -s exit-unattached on\n"); let wrapper = Filename.concat directory "tmux" in Out_channel.with_open_text wrapper (fun output -> Printf.fprintf output "#!/bin/sh\nexec %s -f %s \"$@\"\n" (Filename.quote binary) (Filename.quote config_file)); Unix.chmod wrapper 0o700; let channel = Unix.open_process_args_in binary [| binary; "-V" |] in let version = Fun.protect ~finally:(fun () -> if Unix.close_process_in channel <> Unix.WEXITED 0 then failwith "tmux version discovery failed") (fun () -> String.trim (input_line channel)) in if not (String.starts_with ~prefix:"tmux " version) then failwith "invalid tmux version"; let version = String.sub version 5 (String.length version - 5) in let ready = Filename.concat directory "ready.txt" in Out_channel.with_open_text ready (fun output -> output_string output "showcase ready\n"); let spawn = Spawn.make (Exec { program = "/bin/cat"; args = [ "-u"; ready; "-" ] }) in let config = match Config.make ~directory ~session:"showcase" [ Config.window ~name:"editor" [ Config.pane ~spawn () ] ] with | Ok value -> value | Error error -> failwith (Format.asprintf "%a" Config.pp_error error) in let plan = match Plan.make ~endpoint:(Endpoint.socket_path socket) ~version ~observed:None config with | Ok value -> value | Error error -> failwith (Format.asprintf "%a" Plan.pp_error error) in let operation = get (Workspace.submit_bootstrap ~binary:wrapper plan) in Fun.protect ~finally:(fun () -> get (Workspace.close operation)) (fun () -> let receipt = get (Workspace.await operation) in if receipt.status <> Execution.Succeeded then failwith "workspace setup failed"; let client = Option.get (Workspace.client operation) in let initial = List.hd (Iarray.get receipt.steps 0).created in Printf.printf "socket=%s\n%!" socket; let pane = Snapshot.find_pane (get (Client.capture client)) (Pane.Target.id initial.pane) |> Option.get in ignore (get (Client.wait_for_text ~timeout:0.5 client pane ~text:"showcase ready")); use client initial spawn))
let () = let binary = if Array.length Sys.argv = 2 then Sys.argv.(1) else "tmux" in let snapshot = with_demo binary capture_graph in print_graph snapshotRun this example
OCaml 5.5.2, Dune 3.24.2, Linux and tmux 3.3a through 3.8. Install libtmux, libtmux-workspace and libtmux-unix in the active opam switch, then save these files at their shown paths.
Save the program above as examples/showcase_graph.ml in a new directory, along with the files below.
Every view retains protected cleanup. A private exit-unattached configuration ends the owned daemon after its clients close. The program stops its private tmux server and removes any temporary files it created when it finishes. Every view already unwraps result values and retains protected cleanup. The detailed view also checks the captured graph cardinalities.
dune-project
(lang dune 3.24)examples/dune
(executable (name showcase_graph) (libraries libtmux libtmux-workspace libtmux-unix unix))Setup and run
opam exec -- dune exec examples/showcase_graph.exeExpected output
graph: 2 sessions, 2 windows, 3 links, 2 panesSource installation; no registry release. Requires OCaml 5.5.2, Linux and tmux 3.3a through 3.8.
Start with Perl
use v5.44;use Config;use FindBin;use lib "$FindBin::Bin/../scripts/lib";use LibTmuxFixture;
# This complete demo owns a Linux child-reaping scope, including tmux panes.BEGIN { die 'Requires Linux x86_64 LP64' unless $^O eq 'linux' && $Config::Config{archname} =~ /x86_64/ && $Config::Config{ptrsize} == 8 && $Config::Config{ivsize} == 8; syscall(157, 36, 1, 0, 0, 0) == 0 or die "subreaper: $!";}
LibTmuxFixture->run( sub ($server, $root) { my $session = $server->new_session( name => 'demo', command => ['/bin/cat'] ); my $editor = $session->window_links->one->window; $server->rename_window(window => $editor, name => 'editor'); my $right = $server->split_pane( pane => $editor->panes->one, horizontal => true, command => ['/bin/cat'] ); my $logs = $server->new_window( session => $session, name => 'logs', command => ['/bin/cat'] ); $server->select_pane(pane => $right); my $snapshot = $server->snapshot; my $link = $snapshot->window_links->one({ window => {-is => {id => $logs->id}} }); $server->select_window(link => $link); $snapshot = $server->snapshot;
for my $entry ($snapshot->sessions->@*) { say 'session ', $entry->name; for my $link ($entry->window_links->@*) { my $window = $link->window; my $ids = join ' ', map { $_->id } $window->panes->@*; my $label = $link->index . ':' . $window->name; say ' window ', $label, ': ', $ids; } } my $panes = $snapshot->windows->one({name => 'editor'})->panes ->where({width => {-gte => 1}}) ->grep(sub ($pane) { $pane->height >= 1 }); my $selected = $panes->one({active => true}); die 'unexpected pane membership' unless $panes->count == 2; my $name = $selected->window->name; say $selected->id, ' is in window ', $name; });use v5.44;use Config;use FindBin;use lib "$FindBin::Bin/../scripts/lib";use LibTmuxFixture;
# This complete demo owns a Linux child-reaping scope, including tmux panes.BEGIN { die 'Requires Linux x86_64 LP64' unless $^O eq 'linux' && $Config::Config{archname} =~ /x86_64/ && $Config::Config{ptrsize} == 8 && $Config::Config{ivsize} == 8; syscall(157, 36, 1, 0, 0, 0) == 0 or die "subreaper: $!";}
try { LibTmuxFixture->run( sub ($server, $root) { my $session = $server->new_session( name => 'demo', command => ['/bin/cat'] ); my $editor = $session->window_links->one->window; $server->rename_window(window => $editor, name => 'editor'); my $right = $server->split_pane( pane => $editor->panes->one, horizontal => true, command => ['/bin/cat'] ); my $logs = $server->new_window( session => $session, name => 'logs', command => ['/bin/cat'] ); $server->select_pane(pane => $right); my $snapshot = $server->snapshot; my $link = $snapshot->window_links->one({ window => {-is => {id => $logs->id}} }); $server->select_window(link => $link); $snapshot = $server->snapshot;
for my $entry ($snapshot->sessions->@*) { say 'session ', $entry->name; for my $link ($entry->window_links->@*) { my $window = $link->window; my $ids = join ' ', map { $_->id } $window->panes->@*; my $label = $link->index . ':' . $window->name; say ' window ', $label, ': ', $ids; } } my $panes = $snapshot->windows->one({name => 'editor'})->panes ->where({width => {-gte => 1}}) ->grep(sub ($pane) { $pane->height >= 1 }); my $selected = $panes->one({active => true}); die 'unexpected pane membership' unless $panes->count == 2; my $name = $selected->window->name; say $selected->id, ' is in window ', $name; } );}catch ($error) { warn "tmux quickstart failed: $error\n"; die $error;}use v5.44;use Config;use FindBin;use lib "$FindBin::Bin/../scripts/lib";use LibTmuxFixture;
# This complete demo owns a Linux child-reaping scope, including tmux panes.BEGIN { die 'Requires Linux x86_64 LP64' unless $^O eq 'linux' && $Config::Config{archname} =~ /x86_64/ && $Config::Config{ptrsize} == 8 && $Config::Config{ivsize} == 8; syscall(157, 36, 1, 0, 0, 0) == 0 or die "subreaper: $!";}
LibTmuxFixture->run( sub ($server, $root) { my $session = $server->new_session( name => 'demo', command => ['/bin/cat'] ); my $failure; try { my $editor = $session->window_links->one->window; $server->rename_window(window => $editor, name => 'editor'); my $right = $server->split_pane( pane => $editor->panes->one, horizontal => true, command => ['/bin/cat'] ); my $logs = $server->new_window( session => $session, name => 'logs', command => ['/bin/cat'] ); $server->select_pane(pane => $right); my $snapshot = $server->snapshot; my $link = $snapshot->window_links->one({ window => {-is => {id => $logs->id}} }); $server->select_window(link => $link); $snapshot = $server->snapshot;
for my $entry ($snapshot->sessions->@*) { say 'session ', $entry->name; for my $link ($entry->window_links->@*) { my $window = $link->window; my $ids = join ' ', map { $_->id } $window->panes->@*; my $label = $link->index . ':' . $window->name; say ' window ', $label, ': ', $ids; } } my $panes = $snapshot->windows->one({name => 'editor'})->panes ->where({width => {-gte => 1}}) ->grep(sub ($pane) { $pane->height >= 1 }); my $selected = $panes->one({active => true}); die 'unexpected pane membership' unless $panes->count == 2; my $name = $selected->window->name; say $selected->id, ' is in window ', $name; } catch ($error) { $failure = $error } $server->kill_session(session => $session); die $failure if defined $failure; });use v5.44;use Config;use FindBin;use lib "$FindBin::Bin/../scripts/lib";use LibTmuxFixture;
# This complete demo owns a Linux child-reaping scope, including tmux panes.BEGIN { die 'Requires Linux x86_64 LP64' unless $^O eq 'linux' && $Config::Config{archname} =~ /x86_64/ && $Config::Config{ptrsize} == 8 && $Config::Config{ivsize} == 8; syscall(157, 36, 1, 0, 0, 0) == 0 or die "subreaper: $!";}
try { LibTmuxFixture->run( sub ($server, $root) { my $session = $server->new_session( name => 'demo', command => ['/bin/cat'] ); my $failure; try { my $editor = $session->window_links->one->window; $server->rename_window(window => $editor, name => 'editor'); my $right = $server->split_pane( pane => $editor->panes->one, horizontal => true, command => ['/bin/cat'] ); my $logs = $server->new_window( session => $session, name => 'logs', command => ['/bin/cat'] ); $server->select_pane(pane => $right); my $snapshot = $server->snapshot; my $link = $snapshot->window_links->one( { window => {-is => {id => $logs->id}} } ); $server->select_window(link => $link); $snapshot = $server->snapshot;
for my $entry ($snapshot->sessions->@*) { say 'session ', $entry->name; for my $link ($entry->window_links->@*) { my $window = $link->window; my $ids = join ' ', map { $_->id } $window->panes->@*; my $label = $link->index . ':' . $window->name; say ' window ', $label, ': ', $ids; } } my $panes = $snapshot->windows->one({name => 'editor'}) ->panes->where({width => {-gte => 1}}) ->grep(sub ($pane) { $pane->height >= 1 }); my $selected = $panes->one({active => true}); die 'unexpected pane membership' unless $panes->count == 2; my $name = $selected->window->name; say $selected->id, ' is in window ', $name; } catch ($error) { $failure = $error } $server->kill_session(session => $session); die $failure if defined $failure; } );}catch ($error) { warn "tmux quickstart failed: $error\n"; die $error;}Run this example
Linux x86_64 LP64, Perl 5.44.0, tmux 3.3a or newer, and the LibTmux core distribution installed from source. Save both files with the displayed directories. No CPAN release is claimed.
Save the program above as examples/quickstart.pl in a new directory, along with the files below.
The included standard-library fixture owns its private socket and verifies child exit. Cleanup also tears down the created session explicitly. The program stops its private tmux server and removes any temporary files it created when it finishes. Error handling adds diagnostics; every version checks required results and deadlines.
scripts/lib/LibTmuxFixture.pm
package LibTmuxFixture;use v5.44;use File::Temp qw(tempdir);use File::Path qw(remove_tree);use LibTmux::Server;use Errno qw(ECHILD EINTR);
sub _children ($pid) { open my $in, '<', "/proc/$pid/task/$pid/children" or return (); my $line = do { local $/; <$in> }; close $in; return grep { length } split /\s+/, $line;}
sub _stamp ($pid) { open my $in, '<', "/proc/$pid/stat" or return undef; my $line = do { local $/; <$in> }; close $in; return undef unless $line =~ /\A[0-9]+ \(.*\) (.*)\z/s; my @fields = split /\s+/, $1; return $fields[19];}
sub _tree ($pid, $owned, $order) { return if exists $owned->{$pid}; my $stamp = _stamp($pid); return unless defined $stamp; $owned->{$pid} = $stamp; push @$order, $pid; _tree($_, $owned, $order) for _children($pid);}
sub run ($class, $code, %args) { my %allowed = map { $_ => true } qw(executable timeout max_output env); die 'fixture selectors/configuration cannot be overridden' if grep { !$allowed{$_} } keys %args; my %baseline = map { $_ => true } _children($$); my $root = tempdir('libtmux-perl-fixture-XXXX', TMPDIR => 1, CLEANUP => 0); my $server = LibTmuxFixture::Server->new( socket_path => "$root/s", config_file => '/dev/null', executable => $ENV{LIBTMUX_TEST_TMUX} // 'tmux', timeout => 0.8, %args ); my ($result, $failure); local $SIG{TERM} = sub { die 'fixture interrupted by TERM' }; local $SIG{INT} = sub { die 'fixture interrupted by INT' }; try { $result = $code->($server, $root) } catch ($error) { $failure = $error } my $cleanup_error; { local $SIG{TERM} = 'IGNORE'; local $SIG{INT} = 'IGNORE'; try { my (%owned, @order); my $pid = $server->{fixture_pid}; if (!$pid && -S "$root/s") { try { $pid = 0 + $server->cmd('display-message', '-p', '#{pid}')->stdout } catch ($error) { die $error unless ref($error) && $error->isa('LibTmux::X::NoServer') } } _tree($pid, \%owned, \@order) if $pid; if (-S "$root/s") { try { $server->kill_server } catch ($error) { die $error unless ref($error) && $error->isa('LibTmux::X::NoServer') } }
# This author fixture runs in an isolated test process. Preserve children # that existed before its scope, including nested/borrowed fixtures. _tree($_, \%owned, \@order) for grep { !$baseline{$_} } _children($$); for my $child (@order) { my $stamp = _stamp($child); kill 'KILL', $child if defined($stamp) && $stamp eq $owned{$child}; } local $SIG{ALRM} = sub { die 'owned fixture child did not exit' }; alarm 1; for my $child (@order) { my $waited; do { $waited = waitpid($child, 0) } while ($waited < 0 && $! == EINTR); my $wait_error = 0 + $!; my $stamp = _stamp($child); die 'owned fixture process remained after teardown' if defined($stamp) && $stamp eq $owned{$child}; die 'fixture child exit was not observed' if $waited < 0 && $wait_error != ECHILD; } alarm 0; } catch ($error) { alarm 0; $cleanup_error = $error } } remove_tree($root); if (defined $failure) { if (ref($failure) && $failure isa LibTmux::X::Creation) { my $cause = $failure->cause; warn "fixture acquisition cause: $cause\n" if defined $cause; } warn "fixture cleanup also failed: $cleanup_error" if defined $cleanup_error; die $failure; } die $cleanup_error if defined $cleanup_error; return $result;}
package LibTmuxFixture::Server;use parent 'LibTmux::Server';
sub new_session ($self, %args) { my $session = $self->SUPER::new_session(%args); $self->{fixture_pid} = 0 + $self->cmd('display-message', '-p', '#{pid}')->stdout unless $self->{fixture_pid}; return $session;}1;Setup and run
perl examples/quickstart.plExpected output
session demo window 0:editor: %0 %1 window 1:logs: %2%1 is in window editorUnpublished development distribution. Requires Perl 5.44.0, Linux x86_64 LP64, and tmux 3.3a or newer.
Start with an agent
Copy this into any coding agent. It installs libtmux in the repository you are in, checks the install against a real tmux server, and points the agent at this site's llms.txt and docs.json so it reads the API rather than guessing it. Use the language selected above, then pick a task.
All prompts, including a plain-text URL per language and task that an agent can fetch.