libtmux for Elixir

libtmux for Elixir

Hex.pm · API reference · HexDocs · Documentation

Core checks libtmux libtmux.org license

Drive tmux from Elixir: capture sessions, windows and panes as an immutable snapshot, filter it with plain data, then rename, split and type through domain actions.

Contents — Installation · Try the examples · Start a server · Choose a server · Find things · Rename · Control · Errors · Guides · Support · Leaves out

Installation

Add the package to your Mix dependencies:

{:libtmux, "~> 0.1"}

Fetch dependencies:

$ mix deps.get

It needs:

The exact floors and tested releases are in Packages and support.

Try the examples

The snippets below form one executable program. It starts a private tmux server and stops it afterward. From this checkout, with tmux on PATH:

$ mix run examples/readme.exs

No checkout? The standalone demo installs the package from Hex.

Start a private server

Server.with_owned/2: a server for one function

It starts a tmux server in a private directory, calls your function with the Server, and stops the server afterward, even when the function raises. Server.new_session!/3 and Session.new_window!/4 create what you work on, and Window.kill!/3 removes it.

alias LibTmux.{Ref, Selection, Server, Session, Snapshot, Window}

tmux = System.find_executable("tmux") || raise "tmux is not on PATH"

Server.with_owned([executable: tmux], fn server ->
  cat = [command: {:argv, ["/bin/cat"]}]
  %{id: session_id} = Server.new_session!(server, "work", cat)

  snapshot = Server.snapshot!(server)
  session = snapshot |> Snapshot.sessions() |> Selection.one!(id: session_id)
  {:ok, session_ref} = Ref.from_observation(session)

  %{id: logs_id} = Session.new_window!(server, session_ref, "logs", cat)

  snapshot = Server.snapshot!(server)
  logs = snapshot |> Snapshot.windows() |> Selection.one!(id: logs_id)
  {:ok, logs_ref} = Ref.from_observation(logs)
  windows = snapshot |> Snapshot.windows() |> Selection.size()

  :ok = Window.kill!(server, logs_ref)

  remaining = Server.snapshot!(server) |> Snapshot.windows() |> Enum.map(& &1.id)

  IO.puts(
    JSON.encode!(%{
      session: session_id,
      created_window: logs_id,
      windows_before_kill: windows,
      remaining_windows: remaining
    })
  )
end)

It prints:

{"session":"$0","created_window":"@1","windows_before_kill":2,"remaining_windows":["@0"]}

More: Own a private server.

Choose the server

Server.new/1: describe a server that already runs

It builds a descriptor with no I/O. Pass :socket for a path or :socket_name for a name; with neither, it reads LIBTMUX_SOCKET_PATH, then LIBTMUX_SOCKET, and otherwise leaves the choice to tmux.

alias LibTmux.Server

tmux = System.find_executable("tmux") || raise "tmux is not on PATH"

by_path = Server.new(executable: tmux, socket: "/run/user/1000/work.sock")
by_name = Server.new(executable: tmux, socket_name: "work")
from_variable = Server.new(executable: tmux, env: %{"LIBTMUX_SOCKET" => "work"})
from_path_variable = Server.new(executable: tmux, env: %{"LIBTMUX_SOCKET_PATH" => "/tmp/w.sock"})
default = Server.new(executable: tmux, env: %{})

%Server{socket: "/run/user/1000/work.sock", socket_name: nil} = by_path
%Server{socket: nil, socket_name: "work"} = by_name
%Server{socket: nil, socket_name: "work"} = from_variable
%Server{socket: "/tmp/w.sock", socket_name: nil} = from_path_variable
%Server{socket: nil, socket_name: nil} = default

IO.puts(
  JSON.encode!(%{
    by_path: by_path.socket,
    by_name: by_name.socket_name,
    from_variable: from_variable.socket_name,
    from_path_variable: from_path_variable.socket,
    default: "tmux chooses"
  })
)

More: Capture an existing server.

Find sessions, windows and panes

Server.snapshot!/2: what tmux has now

The snippets from here on run inside the function that Server.with_owned/2 calls, so server is its private server. One call captures every session, window and pane as an immutable graph. Snapshot.sessions/1, Snapshot.windows/1 and Snapshot.panes/1 pick a type, and Selection.where/2 filters it. None of them calls tmux again.

alias LibTmux.{Selection, Snapshot}

snapshot = Server.snapshot!(server)

active_ids =
  snapshot
  |> Snapshot.panes()
  |> Selection.where(active: true)
  |> Enum.map(& &1.id)

active_ids is ["%0"]: the demo server starts with one pane. Capture again when you need fresh state.

More: Captured state.

Selection.where/2: filter by data

Criteria are keywords or maps, and can test related panes. Filter.from_json/3 reads the same criteria from JSON, so a filter can come from a file or a request. Selection.filter/2 takes an Elixir function instead.

alias LibTmux.{Filter, Pane, Selection, Snapshot}

windows =
  snapshot
  |> Snapshot.windows()
  |> Selection.where(panes: [some: [active: true, current_command: "cat"]])
  |> Enum.map(& &1.id)

json = """
{"version":1,"entity":"pane",
 "where":{"active":true,"currentCommand":{"in":["cat","nvim"]}}}
"""

{:ok, filter} = Filter.from_json(Pane, json)

pane_ids =
  snapshot
  |> Snapshot.panes()
  |> Selection.where(filter)
  |> Enum.map(& &1.id)

windows is ["@0"] and pane_ids is ["%0"]. One pane must meet both conditions inside some.

More: Filtering.

Rename a window

Window.rename!/4: change a window's name

Continue with the same snapshot and server. Selection.one!/2 needs exactly one match, Session.active_window/2 reads the captured link, and Ref.from_observation/1 turns an observation into an action target.

alias LibTmux.{Ref, Selection, Session, Snapshot, Window}

session = snapshot |> Snapshot.sessions() |> Selection.one!(id: session_id)
window = Session.active_window(snapshot, session)
{:ok, session_ref} = Ref.from_observation(session)
{:ok, window_ref} = Ref.from_observation(window)

Window.rename!(server, window_ref, "editor", session: session_ref)

It returns :ok once tmux acknowledges the command. session: names the session whose link to the window to use. The old snapshot keeps the old name.

More: One-shot actions.

Split a pane, send input and read the screen

Control.with_connection/2: one connection for many commands

It attaches a control client to an existing session, runs your callback, and closes the client. Pane.split!/3 returns the new pane's ID and a bound reference. Pane.send_text!/4 sends literal text and Pane.send_keys!/4 sends named keys. After the scope closes, Pane.capture!/3 reads the new pane's screen through the server.

alias LibTmux.{Control, Pane, Ref, Selection, Snapshot}

pane = snapshot |> Snapshot.panes() |> Selection.one!(window_id: window.id, active: true)
{:ok, pane_ref} = Ref.from_observation(pane)

{:ok, {created_id, created}} =
  Control.with_connection(
    [server: server, session: {:existing, session.id}, lane: :host_qualified],
    fn control ->
      %{id: id, ref: created} =
        Pane.split!(control, pane_ref, axis: :horizontal, command: {:argv, ["/bin/cat"]})

      Pane.send_text!(control, created, "hello")
      Pane.send_keys!(control, created, ["Enter"])
      {id, created}
    end
  )

screen = Pane.capture!(server, created, max_bytes: 4096)

The program prints:

{"window":"editor","active_panes":["%0"],"created_pane":"%1","connection_retired":true}

More: Managed control.

Errors and recovery

Action.CompletionError: what went wrong

Actions return {:ok, result} only when the command completes; the bang forms raise instead. A command that times out may still have taken effect, so inspect it before you retry.

More: Recovery, Mental model.

Guides

Support and status

What it leaves out

AI policy

Use these packages with AI tools as you like. When contributing, check what you submit and wait for a maintainer's invitation before preparing a pull request. See the AI policy, also kept as AI_POLICY.md.

Contributing

See Contributing for development setup and checks, and Writing for documentation conventions.

Related projects: libtmux for Python, libtmux ports, and tmux. Artwork. Licensed under the MIT License.