# Executable examples

For ordinary tasks, begin with [capture and filter](first-task.md).

## Run a complete program

These programs run from a checkout on Linux with tmux 3.3 or later on
`PATH`. Each starts a private server and checks the result before exiting.

| Task | Program | Result |
| --- | --- | --- |
| Navigate the typed graph | [navigate.exs](../examples/navigate.exs) | Session name, window ID and pane ID |
| Watch for a window rename | [watch_window.exs](../examples/watch_window.exs) | The name read after the tmux hook signals |
| Submit text with Enter | [send_keys.exs](../examples/send_keys.exs) | The note received by the pane program |
| Rename a window | [rename_window.exs](../examples/rename_window.exs) | The same window ID with its new name |
| Create a window | [create_window.exs](../examples/create_window.exs) | The new window ID and name |
| Move a window to index 7 | [move_window.exs](../examples/move_window.exs) | The same window ID at its new session index |
| Set a layout | [set_layout.exs](../examples/set_layout.exs) | Two full-height panes of equal width within one cell |

```console
$ mix run examples/navigate.exs
```

The packed example check runs these programs and verifies that their servers
and panes exit.

### Navigate the typed graph

<!-- example: examples/navigate.exs -->

```elixir
alias LibTmux.{Pane, Server, Session, Snapshot, Window}

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

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

  snapshot = Server.snapshot!(server)
  {:ok, %Session{} = session} = Snapshot.fetch(snapshot, :session, session_id)
  windows = Snapshot.related(snapshot, :session, session_id, :windows)
  [%Window{} = window] = windows
  [%Pane{} = pane] = Snapshot.related(snapshot, :window, window.id, :panes)

  location = %{session: session.name, window: window.id, pane: pane.id}
  IO.puts(JSON.encode!(location))
end)
```

<!-- /example -->

### Submit text with Enter

<!-- example: examples/send_keys.exs -->

```elixir
alias LibTmux.{Command, Pane, Ref, Selection, Server, Snapshot}

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

program = ~S"""
stty -echo
"$1" -N -S "$2" wait-for -S ready
IFS= read -r note || exit 1
printf '%s\n' "$note" > "$3"
"$1" -N -S "$2" wait-for -S saved
exec /bin/cat
"""

Server.with_owned([executable: tmux], fn server ->
  receipt = Path.join(Path.dirname(server.socket), "receipt")
  argv = ["/bin/sh", "-c", program, "notes", tmux, server.socket, receipt]
  Server.new_session!(server, "notes", command: {:argv, argv})

  {:ok, _} = Server.run(server, Command.new("wait-for", ["ready"]))
  pane = server |> Server.snapshot!() |> Snapshot.panes() |> Selection.one!()
  {:ok, ref} = Ref.from_observation(pane)

  :ok = Pane.send_text!(server, ref, "first note")
  :ok = Pane.send_keys!(server, ref, ["Enter"])

  {:ok, _} = Server.run(server, Command.new("wait-for", ["saved"]))
  "first note\n" = File.read!(receipt)
  IO.puts(JSON.encode!(%{received: "first note"}))
end)
```

<!-- /example -->

### Rename a window

<!-- example: examples/rename_window.exs -->

```elixir
alias LibTmux.{Ref, Selection, Server, Snapshot, Window}

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

Server.with_owned([executable: tmux], fn server ->
  Server.new_session!(server, "work", command: {:argv, ["/bin/cat"]})
  snapshot = Server.snapshot!(server)
  window = snapshot |> Snapshot.windows() |> Selection.one!()
  {:ok, ref} = Ref.from_observation(window)

  :ok = Window.rename!(server, ref, "editor")

  {:ok, %Window{name: "editor"} = updated} =
    Snapshot.fetch(Server.snapshot!(server), :window, window.id)

  IO.puts(JSON.encode!(%{window: updated.id, name: updated.name}))
end)
```

<!-- /example -->

### Create a window

<!-- example: examples/create_window.exs -->

```elixir
alias LibTmux.{Ref, Server, Session, Snapshot, Window}

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

Server.with_owned([executable: tmux], fn server ->
  command = [command: {:argv, ["/bin/cat"]}]
  %{id: session_id} = Server.new_session!(server, "work", command)
  snapshot = Server.snapshot!(server)
  {:ok, session} = Snapshot.fetch(snapshot, :session, session_id)
  {:ok, ref} = Ref.from_observation(session)

  %{id: window_id} = Session.new_window!(server, ref, "logs", command)

  fresh = Server.snapshot!(server)
  windows = Snapshot.related(fresh, :session, session_id, :windows)
  window = Enum.find(windows, &(&1.id == window_id))
  %Window{name: "logs"} = window

  IO.puts(JSON.encode!(%{window: window.id, name: window.name}))
end)
```

<!-- /example -->

### Watch for a window rename

Install a window-scoped tmux hook before starting the writer. The hook wakes
the waiting client, which reads the window's current name from a fresh
snapshot. Multiple changes can happen between the signal and the snapshot.

<!-- example: examples/watch_window.exs -->

```elixir
alias LibTmux.{Command, Ref, Selection, Server, Snapshot, Window}

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

Server.with_owned([executable: tmux], fn server ->
  Server.new_session!(server, "work", command: {:argv, ["/bin/cat"]})
  snapshot = Server.snapshot!(server)
  window = snapshot |> Snapshot.windows() |> Selection.one!()
  {:ok, ref} = Ref.from_observation(window)
  :ok = Window.rename!(server, ref, "draft")

  # tmux remembers the signal even if the rename happens before the wait.
  hook = ["-w", "-t", window.id, "window-renamed", "wait-for -S renamed"]
  {:ok, _} = Server.run(server, Command.new("set-hook", hook))
  writer = Task.async(fn -> Window.rename!(server, ref, "ready") end)
  {:ok, _} = Server.run(server, Command.new("wait-for", ["renamed"]))
  :ok = Task.await(writer)

  {:ok, %Window{name: "ready"} = changed} =
    Snapshot.fetch(Server.snapshot!(server), :window, window.id)

  IO.puts(JSON.encode!(%{window: changed.id, name: changed.name}))
end)
```

<!-- /example -->

### Move a window to another index

Run tmux's `move-window` on the private session and check its memberships.
The old index disappears and the window keeps its ID.

<!-- example: examples/move_window.exs -->

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

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

Server.with_owned([executable: tmux], fn server ->
  Server.new_session!(server, "work", command: {:argv, ["/bin/cat"]})
  before = Server.snapshot!(server)
  link = before |> Snapshot.window_links() |> Selection.one!()
  source = "#{link.session_id}:#{link.index}"
  destination = "#{link.session_id}:7"
  args = ["-s", source, "-t", destination]
  {:ok, _} = Server.run(server, Command.new("move-window", args))

  after_move = Server.snapshot!(server)
  moved = after_move |> Snapshot.window_links() |> Selection.one!()
  true = moved.id == {link.session_id, 7, link.window_id}
  true = moved.index != link.index

  IO.puts(JSON.encode!(%{window: moved.window_id, from: link.index, to: 7}))
end)
```

<!-- /example -->

### Set a layout

Apply tmux's `even-horizontal` layout to two stacked panes. Read back each
pane's height and width, including the column between the panes.

<!-- example: examples/set_layout.exs -->

```elixir
alias LibTmux.{Command, Pane, Ref, Selection, Server, Snapshot, Window}

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

Server.with_owned([executable: tmux], fn server ->
  command = [command: {:argv, ["/bin/cat"]}]
  Server.new_session!(server, "work", command)
  before = Server.snapshot!(server)
  pane = before |> Snapshot.panes() |> Selection.one!()
  {:ok, ref} = Ref.from_observation(pane)
  Pane.split!(server, ref, Keyword.put(command, :axis, :vertical))

  layout = "even-horizontal"
  args = ["-t", pane.window_id, layout]
  {:ok, _} = Server.run(server, Command.new("select-layout", args))

  after_layout = Server.snapshot!(server)
  {:ok, window} = Snapshot.fetch(after_layout, :window, pane.window_id)
  [left, right] = after_layout |> Window.panes(window) |> Enum.to_list()
  true = left.height == window.height and right.height == window.height
  true = left.width + 1 + right.width == window.width
  true = abs(left.width - right.width) <= 1

  IO.puts(JSON.encode!(%{layout: layout, panes: [left.id, right.id]}))
end)
```

<!-- /example -->

## Local graph and filtering

- Building a graph by hand suits importers and pure application logic.
- `fields` declares what was loaded. `complete` separates a known-empty
  relationship from missing coverage.
- This example declares one session and empty window, link, pane and client
  domains.
- Its matches and misses show cardinality, native predicates and portable
  filter round trips.

<!-- example: examples/query_values.exs -->

```elixir
alias LibTmux.{Filter, Schema, Selection, Session, Snapshot}

{:ok, snapshot} =
  Snapshot.new(%{session: [%{id: "$0", name: "work", attached_count: 2}]},
    server_instance: "example-instance",
    captured_from: 10,
    captured_until: 12,
    complete: Schema.entities(),
    fields: %{
      session: [:id, :name, :attached_count],
      window: [:id],
      window_link: [:id, :session_id, :window_id, :index, :active],
      pane: [:id, :window_id],
      client: [:id, :session_id]
    }
  )

[session] = Snapshot.items(snapshot, Session)
{:ok, ^session} = Snapshot.fetch(snapshot, :session, "$0")
:ok = Snapshot.require_complete!(snapshot, :session)
:ok = Snapshot.require_field!(snapshot, :session, :name)
:ok = Snapshot.require_relation!(snapshot, :session, :panes, ["$0"])
[] = Snapshot.related(snapshot, :session, "$0", :panes)
nil = Snapshot.related(snapshot, :session, "$0", :active_window)

sessions = Snapshot.sessions(snapshot)
^sessions = Selection.new(snapshot, Session)
1 = Selection.size(sessions)
1 = Selection.count(sessions, attached: true)
true = Selection.exists?(sessions, name: "work")
true = Selection.member_id?(sessions, "$0")
{:ok, ^session} = Selection.one(sessions)
^session = Selection.one!(sessions)
{:ok, nil} = Selection.one_or_nil(sessions, name: "missing")
nil = Selection.one_or_nil!(sessions, name: "missing")
["$0"] = sessions |> Selection.where(attached: true) |> Enum.map(& &1.id)

[^session] =
  sessions
  |> Selection.filter(&String.starts_with?(&1.name, "wo"))
  |> Enum.to_list()

0 = Selection.size(Snapshot.windows(snapshot))
0 = Selection.size(Snapshot.window_links(snapshot))
0 = Selection.size(Snapshot.panes(snapshot))
0 = Selection.size(Snapshot.clients(snapshot))

{:ok, filter} = Filter.new(Session, name: [starts_with: "wo"])
^filter = Filter.new!(Session, name: [starts_with: "wo"])
true = Filter.to_predicate(filter, snapshot: snapshot).(session)
wire = Filter.to_wire(filter)
{:ok, ^filter} = Filter.from_wire(Session, wire)
{:ok, ^filter} = Filter.from_json(Session, JSON.encode!(wire))

Session = Schema.module(:session)
:session = Schema.entity(Session)
%{name: metadata} = Schema.fields(:session)
^metadata = Schema.field(:session, :name)
nil = Schema.field(:session, :unknown)
true = :starts_with in Schema.operators(metadata)
%{panes: {:many, :pane}} = Schema.relations(:session)
"activeWindow" = Schema.relation_wire(:active_window)
IO.puts(JSON.encode!(%{query_values: "ok"}))
```

<!-- /example -->

### Choose a native release

Find the tagged releases that declare a command or flag before choosing a
minimum tmux version. Lettered releases appear in order. Use the reported
commit and source file to inspect a command's behavior.

```elixir
alias LibTmux.ReleaseMap

{:ok, ["3.8"]} = ReleaseMap.releases({:command, "switch-mode"})
{:ok, flag} = ReleaseMap.lookup("3.8", {:flag, "resize-pane", "-D"})
%{argument: :optional, source: "cmd-resize-pane.c"} = flag
```

## Encoding and protocol

- The deadline uses explicit local clock samples.
- References use synthetic instance tokens and cannot target a real server.
- Command and format construction, field decoding, parsing and JSON validation
  do no I/O.
- The last two calls run bounded Linux processes, to show that a nonzero
  process exit is still a transport result, including with `run!/3`.

<!-- example: examples/encoding_values.exs -->

```elixir
alias LibTmux.{Codec, Command, Control, Deadline, Format}
alias LibTmux.{Protocol, Ref, Server, Wire}
alias LibTmux.Control.Request
alias LibTmux.Transport.OneShot

server = Server.new(executable: "/unused/tmux", socket: "/unused/socket")
spec_opts = [server: server, session: {:existing, "$0"}, lane: :host_qualified]
%{id: Control, type: :supervisor} = Control.child_spec(spec_opts)

deadline = Deadline.new(100, now: 10)
75 = Deadline.remaining(deadline, now: 35)
0 = Deadline.remaining(deadline, now: 110)
{:ok, ref} = Ref.new(:pane, "%7", "example-instance")
:ok = Ref.validate(ref, "example-instance")
{:error, %{kind: :stale_target}} = Ref.validate(ref, "another-instance")

command = Command.new("display-message", ["-p", Format.literal(~S"#{pid}")])
["display-message", "-p", _literal] = Command.argv(command)
false = String.contains?(Command.render(command), "\n")
true = String.starts_with?(Format.field("pane_title"), "v1:")
escaped = [encoding: :escaped_v1]
{:ok, "hello\n"} = Codec.decode_field("v1:hello\\012\n", :string, escaped)
{:ok, <<0, 255>>} = Codec.decode_output("\\000\\377")

parser = Protocol.new(max_line_bytes: 1024)

{:ok, [{:reply, :ok, {1, 2, 1}, ["v1:hello"]}], parser} =
  Protocol.feed(parser, "%begin 1 2 1\nv1:hello\n%end 1 2 1\n")

:ok = Protocol.finish(parser)
:ok = Request.verify_reply(Request.field("pane_title"), :ok, ["v1:hello"])
set_option = Request.set_user_option("@example", "hello")
:ok = Request.verify_reply(set_option, :ok, [])
{:ok, %{"name" => "work"} = value} = Wire.decode(~s({"name":"work"}))
{:ok, ^value} = Wire.validate(value)

{:ok, %{stdout: "hello\n", exit_status: 0, cleanup: :retired}} =
  OneShot.run("/bin/echo", ["hello"], max_total_bytes: 6)

failed = OneShot.run!("/bin/false", [])
%{stdout: "", exit_status: 1, cleanup: :retired} = failed
IO.puts(JSON.encode!(%{encoding_values: "ok"}))
```

<!-- /example -->

## Supervised control

Use `LibTmux.Control.child_spec/1` when the connection belongs to an
application supervisor. The [executable supervision recipe](supervised-control.md)
shows an application owner, caller access, replacement handles and explicit
recovery after known retirement.

- Unknown cleanup leaves the connection unavailable.
- `LibTmux.Control.reconnect/2` returns a ready replacement only after the old
  epoch is proven retired. A ready handle returns itself. It never replays
  operations.
- `request_close/1` and `Operation.stop/1` only request epoch closure; `close/2`
  waits for proof. A scope owns its enclosing supervisor too.
- The [advanced program](advanced-execution.md) shows local connection and
  operation status, canonical result inspection, close-before-forget and actual
  supervisor exit.
- Control and Operation bang variants raise the same API error and keep failed,
  skipped and unknown outcomes as values to inspect.
- Domain bang actions require command completion and return the completed
  value; see `LibTmux.Action`.
