Core Library0.xAPI Reference

Choose documentation 3

latest

Current version

latest
English

Early release libtmux is released, and its APIs may still change between releases. This site's structure and URLs may change too.

method libtmux-rs latest

Server.hierarchy

Fetch the whole hierarchy in three commands.

Source and package
Qualified name
libtmux::server::Server::hierarchy
Module
server
Declared in
Server
Package
libtmux
Source
crates/libtmux/src/server/discovery.rs
Other languages
Perlmethod Erlangfunction PowerShellcmdlet Juliafunction Elixirfunction Haskell Common Lispfunction Python RubyLuaTypeScriptGoJavaC# C++ SwiftKotlinScalaOCamlfunction F#function Clojurefunction
pub async fn hierarchy(&self) -> Result< Vec<SessionTree>, Error >

Description#

Walking down with Server::sessions(), then each session's windows, then each window's panes costs one command per object. tmux can answer the same question with list-sessions, list-windows -a, and list-panes -a, so this issues three regardless of how much is running and stitches the result by winlink.

Use it when you want everything. Use the scoped accessors when you want one branch: they fetch less.

The three listings are separate tmux commands, so this is not an atomic capture. Only sessions in the session listing become roots, and only windows in the window listing join them. A listed session or window can remain with no observed children; empty children do not prove that the branch was empty at one instant.

Errors

Returns an error when any of the three listings fails.

Examples#

List sessions, windows and panes. Read each collection and its relations, then inspect a hierarchy snapshot. Use Rust 1.85 or newer with Cargo, and tmux 3.3a or newer, on a Unix system. In an empty directory, create a project and add the published crates:

Terminal window
$ cargo init --name libtmux-api-example &&
cargo add libtmux@0.1.2 tempfile@3.20 &&
cargo add tokio@1.40 --features macros,rt,time

Replace src/main.rs with this complete program. It owns a private tmux socket, applies a ten-second task deadline, and reports both task and cleanup errors. Server::kill() stops its daemon; Server::shutdown() closes its client executor. Successful cleanup removes the temporary directory even when the task fails. View source

//! List sessions, windows and panes, then read their hierarchy.
use std::error::Error;
use std::time::Duration;
use libtmux::{NewSessionOptions, NewWindowOptions, Server};
type ExampleError = Box<dyn Error>;
fn check(condition: bool, message: &str) -> Result<(), ExampleError> {
if condition {
Ok(())
} else {
Err(message.into())
}
}
async fn demonstrate(server: &Server) -> Result<(), ExampleError> {
let session = server
.new_session(
NewSessionOptions::new("work")
.window_name("editor")
.command("cat"),
)
.await?;
session
.new_window(NewWindowOptions::new("logs").command("cat"))
.await?;
let sessions = server.sessions().await?;
let windows = server.windows().await?;
let panes = server.panes().await?;
check(sessions.len() == 1, "expected one session")?;
check(windows.len() == 2, "expected two windows")?;
check(panes.len() == 2, "expected two panes")?;
check(
session.windows().await?.len() == 2,
"expected two session windows",
)?;
check(
session.panes().await?.len() == 2,
"expected two session panes",
)?;
for window in &windows {
check(
window.session_id() == session.id(),
"window belongs to another session",
)?;
check(
window.panes().await?.len() == 1,
"expected one pane per window",
)?;
}
let hierarchy = server.hierarchy().await?;
let branch = hierarchy.first().ok_or("hierarchy has no session")?;
check(
branch.session.id() == session.id(),
"hierarchy session differs",
)?;
check(branch.windows.len() == 2, "expected two hierarchy windows")?;
check(
branch.windows.iter().all(|window| window.panes.len() == 1),
"hierarchy panes differ",
)?;
println!("listings: 1 session, 2 windows, 2 panes");
Ok(())
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), ExampleError> {
let root = std::path::Path::new("/tmp/libtmux-rs-dev");
std::fs::create_dir_all(root)?;
let directory = tempfile::Builder::new()
.prefix("api-listings-")
.tempdir_in(root)?;
std::fs::write(
directory.path().join("owner"),
std::process::id().to_string(),
)?;
let server = Server::builder()
.socket_path(directory.path().join("tmux.sock"))
.config_file("/dev/null")
.default_timeout(Duration::from_secs(5))
.build()?;
let outcome = tokio::time::timeout(Duration::from_secs(10), demonstrate(&server)).await;
// Stop the owned daemon before closing the client executor.
let killed = server.kill().await;
let closed = server.shutdown().await;
let cleanup_failed = killed.is_err() || closed.is_err();
let mut failures = Vec::new();
match outcome {
Ok(Ok(())) => {}
Ok(Err(error)) => failures.push(format!("example failed: {error}")),
Err(error) => failures.push(format!("example deadline: {error}")),
}
if let Err(error) = killed {
failures.push(format!("daemon cleanup: {error}"));
}
if let Err(error) = closed {
failures.push(format!("executor cleanup: {error}"));
}
if cleanup_failed {
let retained = directory.keep();
failures.push(format!("inspect retained directory {}", retained.display()));
} else if let Err(error) = directory.close() {
failures.push(format!("directory cleanup: {error}"));
}
if failures.is_empty() {
Ok(())
} else {
Err(failures.join("; ").into())
}
}

Run the consumer. Success exits with status 0; setup, operation, deadline or cleanup failures exit unsuccessfully and print diagnostics to stderr:

Terminal window
$ cargo run --quiet

Expected output:

listings: 1 session, 2 windows, 2 panes

In other ports#

Capture the tmux hierarchy

Equivalents of Capture the tmux hierarchy in other languages
Language Equivalent
Python no equivalent on Server
Ruby LibTmux::Server#snapshot
Lua libtmux.Server:snapshot
PowerShell LibTmux\Get-TmuxSnapshot Acquires a replacement LibTmux.Server to -Depth (panes by default). Acquisition is not atomic; retained handles do not refresh.
Julia LibTmux.snapshot Acquires a new Snapshot over an observation interval. Topology checks do not make it a transaction; earlier snapshots do not refresh.
Erlang tmux_server:snapshot/1 Captures a new graph over an observation interval. Retained snapshots never refresh.
Elixir LibTmux.Server.snapshot/2 Captures a new graph over an observation interval. A retained Snapshot never refreshes.
Haskell No public Haskell equivalent is implemented; the current modules expose scalar values and version parsing.
Common Lisp libtmux:fetch-snapshot fetch-snapshot acquires a new interval observation. Retained snapshots never refresh in place.
TypeScript server.Server.snapshot
Go tmux.Server.Snapshot
Java io.github.libtmux.Server.snapshot
Clojure libtmux.core/snapshot! Acquires a captured graph of persistent values. Retained values do not refresh after mutation or close.
Kotlin io.github.libtmux.kotlin.Server.snapshot
Scala io.github.libtmux.scaladsl.Server.snapshot
C# LibTmux.Server.CaptureSnapshotAsync
F# LibTmux.FSharp.Server.capture 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()
OCaml Libtmux_unix.Client.capture Acquires a complete immutable graph over an interval. Earlier observations remain readable without refreshing.
Perl LibTmux::Server::snapshot Strict acquisition observes an interval, not an atomic transaction; retained handles do not refresh.
Esc

Type to search.

Reference previewOpen reference