# Attaching to tmux

Source: https://libtmux.org/en/elixir/pr-173/guides/attaching-to-tmux/

> Connect to an existing tmux server and find a session with Elixir.

Select an explicit socket, capture the existing server, and find the `work`
session. The program prints its name and leaves the server running. A missing
server or session ends the program with an error.

This controls tmux from Elixir. To open a session in your terminal, use
[`tmux attach-session`](https://libtmux.org/en/tmux/latest/manual/attach-session/); the [shared guide](https://libtmux.org/en/tmux/guides/attaching-to-tmux/)
covers interactive attachment and detaching.

## Connect to an existing server

Save the complete program as `connect.exs`. The environment variable
`LIBTMUX_SOCKET_PATH` selects the existing server, and `print_work` connects
to it and finds `work`. Without the variable, the program starts a private
server of its own in a new temporary directory, creates `work` with
[`new_session!`](<https://libtmux.org/en/elixir/pr-173/reference/libtmux-server-new_session-bang-3/>), and calls `print_work` with that socket through a second
[`Server`](<https://libtmux.org/en/elixir/pr-173/reference/libtmux-server/>) value. The library works on a running server and does not
start one, so the program has `tmux` start the daemon. It stops the private
server with [`Server.run/3`](https://libtmux.org/en/elixir/pr-173/reference/libtmux-server-run-3/) and
removes the directory after success or failure. If the server does not stop,
the program reports the error and keeps the directory.

The first line installs libtmux from Hex. Its requirement, `~> 0.1`, accepts
any release from 0.1.0 up to, but not including, 1.0.0.

```elixir title="connect.exs" role="program"
Mix.install([{:libtmux, "~> 0.1"}])

alias LibTmux.{Command, Selection, Server, Snapshot}

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

print_work = fn socket ->
  server = Server.new(executable: tmux, socket: socket)
  snapshot = Server.snapshot!(server)
  session = snapshot |> Snapshot.sessions() |> Selection.one!(name: "work")
  IO.puts(session.name)
end

case System.get_env("LIBTMUX_SOCKET_PATH") do
  nil ->
    # No server was named: start one this program owns.
    id = Base.encode16(:crypto.strong_rand_bytes(8), case: :lower)
    dir = Path.join(System.tmp_dir!(), "libtmux-attach-" <> id)
    socket = Path.join(dir, "tmux.sock")
    owner = Server.new(executable: tmux, socket: socket)
    File.mkdir!(dir)
    File.chmod!(dir, 0o700)

    try do
      # libtmux works on a running server, so tmux starts the daemon itself.
      start = ~w(start-server ; set-option -s exit-empty off)
      {_, 0} = System.cmd(tmux, ["-S", socket, "-f", "/dev/null" | start])
      Server.new_session!(owner, "work", command: {:argv, ["/bin/cat"]})
      print_work.(socket)
    after
      kill = Command.new("kill-server", [])
      running = File.exists?(socket)
      stopped = not running or match?({:ok, _}, Server.run(owner, kill))

      if stopped do
        File.rm_rf!(dir)
      else
        IO.puts(:stderr, "Cannot stop tmux; kept #{dir}")
        System.halt(1)
      end
    end

  socket ->
    print_work.(socket)
end
```

[`Server.new/1`](https://libtmux.org/en/elixir/pr-173/reference/libtmux-server-new-1/) describes a server that
already exists and performs no I/O. [`Server.snapshot!/2`](https://libtmux.org/en/elixir/pr-173/reference/libtmux-server-snapshot-bang-2/)
reads tmux and returns captured state, or raises the structured capture error.
[`Snapshot.sessions/1`](https://libtmux.org/en/elixir/pr-173/reference/libtmux-snapshot-sessions-1/) selects
sessions from that state without contacting tmux again, and
[`Selection.one!/2`](https://libtmux.org/en/elixir/pr-173/reference/libtmux-selection-one-bang-2/) requires
exactly one match. Reading or filtering captured values does not refresh them.

The server value describes the daemon. It does not own a process to close, and
the program does not destroy the caller's sessions.

## Setup and run

Use an empty directory on Linux with Elixir 1.20.4 or newer, Erlang/OTP 29.1.2
or a newer 29.x release, a C11 compiler, tmux 3.3 or newer, and access to
hex.pm.

```console
$ elixir connect.exs
```

The program prints `work`. To use your own existing server, set
`LIBTMUX_SOCKET_PATH` to its socket before running the program; it prints
`work` and leaves that server running.

## Find or create a session

Reading a session does not reserve its name. If your application creates a
session after an unsuccessful lookup, another client may create the same name
between those operations. Handle the creation error as well as the lookup.

[Mental model](https://libtmux.org/en/elixir/pr-173/concepts/mental-model/) and
[Observations](https://libtmux.org/en/elixir/pr-173/concepts/observations/) explain what a snapshot holds.
[Capture a pane and read it](https://libtmux.org/en/elixir/pr-173/examples/capture-and-read/) is a complete
program that runs against an isolated server.

The [library source revision](https://github.com/libtmux/libtmux-elixir/tree/cac4252bfc52069980d47db2b7803dc9b33f36f1)
records the implementation used by this example.
