# libtmux.Server:snapshot

- **Module:** libtmux
- **Package:** libtmux
- **Language:** Lua
- **Kind:** method
- **Source:** https://github.com/libtmux/libtmux-lua/blob/d68f829fe097e38dcbbf7147e276666fe615f0cf/lua/libtmux/_internal/server.lua#L812
- **Page:** https://libtmux.org/en/lua/v0.1.1/reference/libtmux-server-snapshot/

```
snapshot: fun(
  self: libtmux.Server,
  options?: libtmux.SnapshotOptions,
):libtmux.Request<libtmux.Snapshot>
```

## Examples

List sessions, windows, and panes from one captured server snapshot. Use Lua 5.1 or newer with LuaRocks, tmux 3.3a or newer, and a C compiler and CMake for luv on Linux. In a new directory, install the library and its standalone runtime dependency from LuaRocks:

```console
$ luarocks --tree ./rocks install luv &&
  luarocks --tree ./rocks install libtmux &&
  eval "$(luarocks --tree ./rocks path)"
```

Save this complete launcher as `run.sh`. It starts a private tmux daemon and cleans up after success or failure. A failed daemon shutdown reports and retains its socket directory.

[Source example](https://github.com/libtmux/libtmux-lua/blob/d68f829fe097e38dcbbf7147e276666fe615f0cf/examples/api/run.sh).

```sh
#!/bin/sh
set -eu

program=${1:?Pass the complete Lua example filename}
binary=$(command -v "${TMUX_BIN:-tmux}")
case "$binary" in
    /*) ;;
    *) printf '%s\n' 'tmux must resolve to an absolute path' >&2; exit 1 ;;
esac
# The check that a server stopped connects to its socket, which takes perl.
command -v perl >/dev/null 2>&1 || { printf '%s\n' 'perl is required to confirm that tmux stopped' >&2; exit 1; }
# A socket path must fit sun_path, 104 bytes on macOS. The longest path under
# the directory is the default socket of a program that forgets -S, so a TMPDIR
# that leaves no room for it gives way to /tmp.
root=${TMPDIR:-/tmp}
longest="/libtmux-lua-api.XXXXXX/tmux-$(id -u)/default"
bytes=$(printf '%s%s' "$root" "$longest" | wc -c)
if [ $((bytes)) -gt 100 ]; then
    printf '%s\n' 'TMPDIR is too long for a tmux socket path; using /tmp' >&2
    root=/tmp
fi
directory=$(mktemp -d "$root/libtmux-lua-api.XXXXXX")
socket="$directory/tmux.sock"

# Succeeds only when a connection to the socket is refused or its path is gone.
# Any other outcome leaves a server unproven stopped, including one that a tmux
# client could not talk to.
gone() {
    probed=0
    perl -MSocket -e 'socket(my $s, PF_UNIX, SOCK_STREAM, 0) or exit 0;
        connect($s, sockaddr_un($ARGV[0])) and exit 0;
        exit(($!{ECONNREFUSED} || $!{ENOENT} || $!{ENOTSOCK}) ? 1 : 0)' "$1" || probed=$?
    [ "$probed" -eq 1 ]
}

# Stops the server on a socket, then connects until nothing answers: a server
# leaves a moment after kill-server returns. The client runs in the background
# because it waits for a reply, which a server that never answers does not send.
stop() {
    "$binary" -S "$1" kill-server >/dev/null 2>&1 &
    client=$!
    tries=0
    until gone "$1"; do
        tries=$((tries + 1))
        if [ "$tries" -ge 30 ]; then
            kill "$client" 2>/dev/null || true
            wait "$client" 2>/dev/null || true
            return 1
        fi
        sleep 0.1
    done
    wait "$client" 2>/dev/null || true
}

cleanup() {
    status=$?
    trap - 0 HUP INT TERM
    kept=0
    # A socket anywhere in the directory is a server to stop. Any but the
    # launcher's own is one the program started.
    sockets=$(find "$directory" -type s 2>/dev/null || true)
    while IFS= read -r found; do
        [ -n "$found" ] || continue
        name=${found#"$directory"/}
        if [ "$found" != "$socket" ]; then
            printf 'The program left a tmux socket in the run directory: %s\n' "$name" >&2
            [ "$status" -ne 0 ] || status=1
        fi
        if ! stop "$found"; then
            printf 'tmux still answers at %s\n' "$name" >&2
            kept=1
        fi
    done <<SOCKETS
$sockets
SOCKETS
    if [ "$kept" -ne 0 ]; then
        printf 'Cannot stop tmux; kept %s\n' "${directory##*/}" >&2
        exit 1
    fi
    rm -rf "$directory" || exit 1
    exit "$status"
}
trap cleanup 0
trap 'exit 1' HUP INT TERM

unset TMUX TMUX_PANE LIBTMUX_SOCKET LIBTMUX_SOCKET_PATH LIBTMUX_SOCKET_NAME
export TMUX_BIN="$binary" TMUX_SOCKET="$socket" TMUX_TMPDIR="$directory" ENV=/dev/null BASH_ENV=/dev/null
"$binary" -S "$socket" -f /dev/null new-session -d -s bootstrap -n bootstrap /bin/cat
"${LUA_BIN:-lua}" "$program"
"$binary" -S "$socket" has-session -t '=bootstrap'
```

Save the complete program as `snapshot.lua`. Closing the library connection leaves the daemon running; the launcher owns its lifetime.

[Source example](https://github.com/libtmux/libtmux-lua/blob/d68f829fe097e38dcbbf7147e276666fe615f0cf/examples/api/snapshot.lua).

```lua
local adapter = require("libtmux.runtime.luv")

local function must(value, err)
    if err ~= nil then
        error(tostring(err), 0)
    end
    return value
end

local binary = assert(os.getenv("TMUX_BIN"), "set TMUX_BIN to an absolute tmux executable")
local socket = assert(os.getenv("TMUX_SOCKET"), "set TMUX_SOCKET to the private socket")

must(adapter.run(function(runtime)
    local server = must(runtime:connect({ binary = binary, socket_path = socket }):await())
    must(server
        :new_session({
            name = "demo",
            window_name = "main",
            argv = { "/bin/cat" },
        })
        :await())
    local snapshot = must(server:snapshot({ strict = true }):await())
    local sessions, windows = {}, {}
    for _, session in ipairs(snapshot.sessions) do
        sessions[#sessions + 1] = session.name
    end
    for _, window in ipairs(snapshot.windows) do
        windows[#windows + 1] = window.name
    end
    table.sort(sessions)
    table.sort(windows)
    assert(#snapshot.sessions == 2 and #snapshot.windows == 2 and #snapshot.panes == 2)
    print("sessions: " .. table.concat(sessions, ", "))
    print("windows: " .. table.concat(windows, ", "))
    print("panes: " .. #snapshot.panes)

    must(server:close():await())
    return true
end))
```

Run the saved files. Assertions and operation errors produce a failing exit status:

```console
$ eval "$(luarocks --tree ./rocks path)" &&
  sh run.sh snapshot.lua
```

## Parameters

- `options` (`libtmux.SnapshotOptions?`)

## tmux command

The tmux commands behind `snapshot`.

- [`list-buffers`](/en/tmux/latest/manual/list-buffers/)
- [`list-clients`](/en/tmux/latest/manual/list-clients/)
- [`list-panes`](/en/tmux/latest/manual/list-panes/) `-a` server scope, [`cmd_list_panes_server`](/en/tmux/latest/reference/c-function-cmd-list-panes-c-cmd_list_panes_server/) (source: `lua/libtmux/_internal/server.lua:22`)
- [`list-sessions`](/en/tmux/latest/manual/list-sessions/)
- [`list-windows`](/en/tmux/latest/manual/list-windows/) `-a` server scope, [`cmd_list_windows_exec`](/en/tmux/latest/reference/c-function-cmd-list-windows-c-cmd_list_windows_exec/) (source: `lua/libtmux/_internal/server.lua:21`)

## tmux C API

The C declarations in tmux that implement these commands.

- [`cmd_list_buffers_entry`](/en/tmux/latest/reference/c-variable-cmd_list_buffers_entry/) (attribute)
- [`cmd_list_buffers_exec`](/en/tmux/latest/reference/c-function-cmd-list-buffers-c-cmd_list_buffers_exec/) (function)
- [`cmd_list_clients_entry`](/en/tmux/latest/reference/c-variable-cmd_list_clients_entry/) (attribute)
- [`cmd_list_clients_exec`](/en/tmux/latest/reference/c-function-cmd-list-clients-c-cmd_list_clients_exec/) (function)
- [`cmd_list_panes_entry`](/en/tmux/latest/reference/c-variable-cmd_list_panes_entry/) (attribute)
- [`cmd_list_panes_server`](/en/tmux/latest/reference/c-function-cmd-list-panes-c-cmd_list_panes_server/) (function)
- [`cmd_list_sessions_entry`](/en/tmux/latest/reference/c-variable-cmd_list_sessions_entry/) (attribute)
- [`cmd_list_sessions_exec`](/en/tmux/latest/reference/c-function-cmd-list-sessions-c-cmd_list_sessions_exec/) (function)
- [`cmd_list_windows_entry`](/en/tmux/latest/reference/c-variable-cmd_list_windows_entry/) (attribute)
- [`cmd_list_windows_exec`](/en/tmux/latest/reference/c-function-cmd-list-windows-c-cmd_list_windows_exec/) (function)

## Guides

Pages that discuss `snapshot`.

- [Capture server state](/en/lua/v0.1.1/guides/snapshots/)

## In other ports

Capture the tmux hierarchy

| Language | Equivalent |
| --- | --- |
| Python | no equivalent on `Server` |
| Ruby | [`LibTmux::Server#snapshot`](/en/ruby/latest/reference/libtmux-server-snapshot/) (method) |
| PowerShell | [`LibTmux\Get-TmuxSnapshot`](/en/powershell/latest/reference/libtmux-get-tmuxsnapshot/) (cmdlet). Acquires a replacement `LibTmux.Server` to [`-Depth`](/en/powershell/latest/reference/libtmux-get-tmuxsnapshot/#LibTmux%5CGet-TmuxSnapshot.parameter.Depth) (panes by default). Acquisition is not atomic; retained handles do not refresh. |
| Julia | [`LibTmux.snapshot`](/en/julia/latest/reference/libtmux-snapshot-1gv6/) (function). Acquires a new `Snapshot` over an observation interval. Topology checks do not make it a transaction; earlier snapshots do not refresh. |
| Elixir | [`LibTmux.Server.snapshot/2`](/en/elixir/latest/reference/libtmux-server-snapshot-2/) (function). Captures a new graph over an observation interval. A retained `Snapshot` never refreshes. |
| TypeScript | [`server.Server.snapshot`](/en/ts/latest/reference/server-server-snapshot/) (method) |
| Rust | [`server.Server.hierarchy`](/en/rs/latest/reference/server-server-hierarchy/) (method). Fetches the whole hierarchy with `list-sessions`, `list-windows -a` and `list-panes -a`, and stitches the rows by winlink. The three listings are separate commands, so the capture is not an atomic transaction. |
| Go | [`tmux.Server.Snapshot`](/en/go/latest/reference/tmux-server-snapshot/) (method) |
| Java | [`io.github.libtmux.Server.snapshot`](/en/java/latest/reference/io-github-libtmux-server-server-snapshot/) (method) |
| Kotlin | [`io.github.libtmux.kotlin.Server.snapshot`](/en/kotlin/latest/reference/io-github-libtmux-kotlin-server-snapshot/) (method) |
| Scala | [`io.github.libtmux.scaladsl.Server.snapshot`](/en/scala/latest/reference/io-github-libtmux-scaladsl-server-snapshot/) (method) |
| C# | [`LibTmux.Server.CaptureSnapshotAsync`](/en/csharp/latest/reference/libtmux-server-capturesnapshotasync/) (method) |
| F# | [`LibTmux.FSharp.Server.capture`](/en/fsharp/latest/reference/libtmux-fsharp-server-capture/) (function). Acquires a replacement shared .NET `LibTmux.Server` to the requested depth. Acquisition is not atomic; retained handles do not refresh. |
| C++ | no equivalent on `Server`: `sessions`, `windows`, `panes` and `clients` each take a snapshot of one listing, and `Snapshot::take` needs the internal `detail::Backend`, so no public call reads the whole hierarchy at once |
| Swift | [`Server.snapshot()`](/en/swift/latest/reference/server-snapshot()/) (method) |
