Skip to content

Repository files navigation

libtmux for Julia

libtmux for Julia

Julia libtmux.org license

LibTmux.jl creates tmux sessions, splits panes, sends input and captures terminal output from Julia.

Create a session, capture a pane and read sessions, windows, panes and clients into a snapshot. Then filter it with filter, count and other Julia collection functions. You can also type into a pane and read what it prints.

It suits scripts that drive a terminal program, tests that need a real tmux, and, through the MCP package, agents that share a terminal.

The core uses only Julia standard libraries. Add an experimental companion for MCP or workspace configuration:

Package Use it for
LibTmux Sessions, windows, panes, snapshots and control connections
LibTmuxMCP MCP tools to inspect panes, send keys and wait for output
LibTmuxWorkspace Load and freeze tmuxp-style YAML or JSON workspaces

Quick start

The package is unregistered. From your Julia project's directory, add the core at the v0.1.1 tag:

$ julia \
    --startup-file=no \
    -e 'using Pkg; Pkg.activate(".")' \
    -e 'repo = "https://github.com/libtmux/libtmux-julia.git"' \
    -e 'Pkg.add(Pkg.PackageSpec(url=repo, rev="v0.1.1"))'

It needs Julia 1.13.1 or newer, and tmux 3.3a or newer on your PATH. Open Julia in that project:

$ julia --project=.

Create a private server and split its first window. with_server closes the server when the block returns or throws, and the snapshot stays readable afterwards:

using LibTmux

snap, screen = with_server() do server
    new_session(server; name="demo", command=["/bin/cat"])
    pane = only(panes(snapshot(server))).ref
    split_window(server, pane; direction=:below, command=["/bin/cat"])
    snapshot(server), capture_pane(server, pane)
end

@assert isempty(strip(screen))
println(
    only(sessions(snap)).name,
    ": ",
    length(panes(snap)),
    " panes; blank capture verified",
)
demo: 2 panes; blank capture verified

The block calls new_session, split_window, snapshot and capture_pane. screen holds the pane's UTF-8 text, and the panes run cat, so their screens start blank.

capture_bytes returns the original bytes. examples/owned_capture.jl runs the same flow and checks that the server is gone afterwards.

Find sessions, windows, and panes

snapshot: what tmux has now

snapshot reads the sessions, windows, panes and clients of a server. sessions, windows and panes list what it captured. Continue with snap from the quick start:

using LibTmux

for pane in panes(snap)
    println(string(pane.id), ": ", pane.current_command)
end
%0: cat
%1: cat

A snapshot is a record. It does not change when tmux does, and reading it never contacts tmux. Call snapshot(server) again while the server is open to read fresh state.

PaneWhere: filter without asking tmux again

A closure or a reusable criterion such as PaneWhere filters the captured data. The comparisons come from the Filters module:

filter(pane -> pane.active, panes(snap))

import LibTmux.Filters as F
wide = PaneWhere(active=true, width=F.AtLeast(80))

filter(wide, panes(snap))
count(wide, panes(snap))
any(wide, panes(snap))
[pane.id for pane in Iterators.filter(wide, panes(snap))]

Criteria are callable values. Filtering panes(snap) returns an ordered, read-only Selection. collect gives you a vector, and only requires exactly one result.

windowlinks: a window shared by several sessions

windows and panes list each physical object once. windowlinks and paneoccurrences keep each session's context for a window that belongs to several.

Runnable: examples/shared_windows.jl links one window into two sessions and queries both views.

More: queries and relations · filterable fields · JSON criteria · Tables projections. At the Julia prompt, ?PaneWhere and ?capture_pane show API help.

snapshot: read an object again

A pane you hold is what tmux said when it was read. Julia has no per-object refresh; take another snapshot and index it with the pane's ref. Here set_title changes the pane after it was read:

using LibTmux

with_server() do server
    new_session(server; name="demo", command=["/bin/cat"])
    held = only(panes(snapshot(server)))
    set_title(server, held.ref, "editor")
    held = snapshot(server)[held.ref]

    set_title(server, held.ref, "build")
    fresh = snapshot(server)[held.ref]
    println(held.title, " ", fresh.title)
end
editor build

The same ref indexes a session or a window. The first snapshot keeps what it captured.

Choose which server to use

Server: name the socket, or leave it to tmux

Server describes a tmux endpoint without contacting it. Name at most one of socket_name (tmux's -L) or socket_path (-S). With neither, it picks in this order:

  • LIBTMUX_SOCKET_PATH: a socket path. A relative path resolves against the working directory when the Server is built.
  • LIBTMUX_SOCKET: a socket name. A value with a slash is refused.
  • No socket: tmux picks the server. That is the one TMUX names inside tmux, and its default socket elsewhere.

A socket named in the call leaves both variables unread, and the choice is frozen when the Server is built.

With no socket, commands keep TMUX and TMUX_PANE, so a raw run_command with no target acts on the caller's own pane. The env keyword feeds only the two variables; a command's own environment is the env of run_command.

from_env asks for the TMUX socket as a path, and selects the default socket outside tmux:

julia> using LibTmux

julia> Server(socket_name="work")
Server(socket_name="work", tmux="tmux")

julia> Server(env=Dict("LIBTMUX_SOCKET" => "work"))
Server(socket_name="work", tmux="tmux")

julia> Server(env=Dict{String,String}())
Server(tmux="tmux")

julia> from_env(env=Dict("TMUX" => "/tmp/tmux-1000/default,1234,0"))
Server(socket_path="/tmp/tmux-1000/default", tmux="tmux")

A Server is an immutable value with nothing to close. It borrows the daemon it names. open_server starts a private daemon that you close.

Split and resize panes

split_window: lay out a window

split_window returns the new pane, resize_pane sets a pane's size in cells and resize_window a window's. send_keys types into a pane and capture_pane reads it back:

using LibTmux

top_height, bottom_screen = with_server() do server
    new_session(server; name="layout", command=["/bin/sh"])
    top = only(panes(snapshot(server))).ref
    bottom = split_window(server, top; direction=:below, command=["/bin/sh"])
    resize_pane(server, top; height=6)
    send_keys(server, bottom, "printf 'ready-%s\\n' now", "Enter")
    wait_for_text(server, bottom, "ready-now"; baseline=true)
    snapshot(server)[top].height, capture_pane(server, bottom)
end

@assert occursin("ready-now", bottom_screen)
println("top pane: ", top_height, " rows; the bottom pane printed ready-now")
top pane: 6 rows; the bottom pane printed ready-now

More: kill_pane, kill_window and kill_session remove what you made. set_option and set_hook change tmux options and hooks.

Type into a pane and read what it prints

send_keys: type into a pane

send_keys types into a pane and adds no Enter. observe_output streams the bytes a pane prints from then on, over a control connection. This example needs tmux 3.7 or newer:

using LibTmux

echoed = with_server() do server
    created = new_session(server; name="echo", command=["/bin/cat"])
    pane = only(panes(snapshot(server))).ref
    open_control(server, created) do connection
        observe_output(connection, pane) do stream
            send_keys(server, pane, "hello from Julia"; literal=true)
            bytes = UInt8[]
            while length(bytes) < ncodeunits("hello from Julia")
                append!(bytes, take!(stream; timeout=5).bytes)
            end
            decode_text(bytes)
        end
    end
end

println(echoed)
hello from Julia

The terminal echoes every key, so the stream carries the text you typed. decode_text turns the bytes into a String, and capture_baseline records the screen at a reset point.

Runnable: examples/output_stream.jl. It also reads the cursor with observation_cursor.

wait_for_text: wait for text on the screen

wait_for_text polls the visible screen on every supported tmux release, joins wrapped rows and needs no control connection. watch_screen takes the entry read first, so keys sent inside its block are not counted as already on the screen:

using LibTmux

with_server() do server
    new_session(server; name="shell", command=["/bin/sh"])
    pane = only(panes(snapshot(server))).ref
    watch_screen(server, pane) do screen
        send_keys(server, pane, "printf 'ready-%s\\n' now", "Enter")
        wait_for_text(screen, "ready-now").text
    end
end

A pane or server that ends first raises ScreenWaitEnded with the last screen read. Text that scrolled off is not seen, and typed echo counts, so match on what a command prints.

Send several commands at once

run_group: several commands, one request

run_group joins TmuxCommand values with tmux's ; and sends them in one request. Its sibling run_batch runs independent commands:

using LibTmux

with_server() do server
    new_session(server; name="demo", command=["/bin/cat"])
    group = run_group(server, [
        TmuxCommand("new-window", "-d", "-n", "logs"),
        TmuxCommand("new-window", "-d", "-n", "build"),
    ])
    named = filter(
        window -> window.name in ("logs", "build"),
        windows(snapshot(server)),
    )
    println(
        length(group),
        " commands in one request; ",
        length(named),
        " new windows",
    )
end
2 commands in one request; 2 new windows

A group is not a transaction: the first error skips the rest, and earlier effects stay. A plain Server gets one aggregate reply, so each command's status is :unknown.

run_batch: independent commands, results in order

run_batch keeps going after a failure and returns results in input order. Here the middle command names a session that does not exist:

using LibTmux

with_server() do server
    new_session(server; name="demo", command=["/bin/cat"])
    batch = run_batch(server, [
        TmuxCommand("new-window", "-d", "-n", "logs"),
        TmuxCommand("new-window", "-t", "missing:", "-n", "lost"),
        TmuxCommand("new-window", "-d", "-n", "build"),
    ])
    println(
        count(operation -> operation.acknowledged, batch),
        " of ",
        length(batch),
        " acknowledged",
    )
end
2 of 3 acknowledged

Execution order is unspecified. More: batches, groups and cancellation.

Reuse a control connection

Control connections need tmux 3.7 or newer; older releases raise UnsupportedCapability. Compatibility lists every optional feature and its release.

open_control: persistent clients for repeated commands

A plain server starts a tmux client process for each command. open_control keeps two clients open for repeated operations and cleanup. Both yield during I/O, so Threads.@spawn and fetch overlap calls:

using LibTmux

screens = with_server() do server
    session = new_session(server; name="tasks", command=["/bin/cat"])
    new_window(server, session; name="logs", command=["/bin/cat"])
    open_control(server, session) do connection
        jobs = map(panes(snapshot(connection))) do pane
            Threads.@spawn capture_pane(connection, pane.ref)
        end
        fetch.(jobs)
    end
end

screens holds both pane captures. The inner block closes both clients, and the outer block closes the server.

A control client counts as attached in tmux. Connection loss is terminal, and cancelling a sent operation does not undo it. Ownership and cancellation and output streams cover deadlines and cleanup.

Run the example programs

Each program creates and cleans up its own tmux server:

Task Program
Create a session and capture its screen owned_capture.jl
Query shared windows and their panes shared_windows.jl
Cancel a waiting control operation control_cancel.jl
Send text and subscribe to pane output output_stream.jl
Wait for an explicit command completion marker command_completion.jl

To run the programs, clone the source:

$ git clone \
    https://github.com/libtmux/libtmux-julia.git
$ cd libtmux-julia
$ git checkout v0.1.1
$ julia \
    --project=. \
    examples/shared_windows.jl

The MCP and workspace READMEs carry their own install commands. The workspace example loads a configuration, checks it and cleans up.

Packages

Each heading links to the package's directory on GitHub. None is in the General registry yet, so install from the same source revision, as the quick start does.

LibTmux: the core library

Sessions, windows, panes, snapshots and control connections, using only Julia standard libraries.

API reference · Guides · Examples

A PaneWhere criterion is also plain data. encode_where converts one to a document without contacting tmux:

julia> using LibTmux

julia> import LibTmux.Filters as F

julia> wide = PaneWhere(active=true, width=F.AtLeast(80));

julia> encode_where(wide)["entity"]
"pane"

JSON and Tables extensions: optional integrations

Load JSON to move criteria through JSON text, or Tables to read projected rows as a table. The core imports neither.

Portable criteria · Tables projections

With JSON loaded, write_where_json and read_where_json round trip a criterion:

julia> using LibTmux, JSON

julia> text = write_where_json(PaneWhere(active=true));

julia> encode_where(read_where_json(text)) ==
       encode_where(PaneWhere(active=true))
true

Continue with snap from the quick start. With Tables loaded, project_rows selects the columns of a table:

using Tables

rows = project_rows(panes(snap); columns=(:id, :current_command))
columns = Tables.columntable(rows)
println(join(columns.current_command, ", "))
cat, cat

LibTmuxWorkspace: tmuxp-style workspaces

Read a YAML or JSON workspace, plan it without contacting tmux, apply it to a server and freeze a running session back into a file.

API reference · Guide · Package README

From a checkout, after install_cli creates bin/libtmux-workspace, validate checks the shipped configuration without contacting tmux:

$ bin/libtmux-workspace validate \
    packages/LibTmuxWorkspace/examples/workspace.yaml
valid

LibTmuxMCP: a tmux server for agents

A local stdio MCP server for one tmux server, which a socket option or a variable names and which tmux otherwise picks. Its default tools list panes, capture a pane and send keys.

API reference · Tools · Guide · Package README

The server borrows a tmux server. --start-session work creates the session work first, which starts the server on its socket when none is running.

After install_cli creates bin/libtmux-mcp, add it to Claude Code. Until you enable more tools, the client sees list_panes, capture_pane and send_keys:

$ claude mcp add tmux -- \
    "$PWD/bin/libtmux-mcp" \
    --socket-name agent \
    --start-session work

The MCP README covers other clients and every tool.

What it leaves out

  • Live objects. A snapshot records what tmux reported when it was read. Take a new one, or observe output, to see a change.
  • A terminal emulator. A pane capture returns the screen tmux drew, and observe_output returns the raw bytes a program wrote. Nothing here interprets those bytes.
  • Your tmux configuration. open_server starts a daemon with an empty configuration, and nothing edits ~/.tmux.conf.
  • Remote and native Windows tmux. The core drives a local POSIX tmux. SSH and native Windows tmux are excluded.

Support and status

  • Early. The packages are unregistered and their APIs may change. Pin a tag; Manifest.toml records the revision.
  • Standard library only. The core imports nothing else; the JSON and Tables integrations are optional extensions.
  • Julia 1.13.1 or newer and tmux 3.3a or newer. An older or unreadable tmux is refused before any effect. Compatibility lists features that need a newer one.
  • Linux, including WSL. macOS and psmux are not tested; native Windows tmux is out of scope.
  • Features by release. capabilities.json lists each optional feature and the tmux release it needs.

Reference · Guides · Installation · Troubleshooting · Benchmarks

Changelog · Contributing · AI policy · Citation · MIT License

Part of the libtmux.org family alongside Python libtmux, sibling language ports, and tmux.

Contributors

Languages