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.new_session

Create a detached session and return it.

Source and package
Qualified name
libtmux::server::Server::new_session
Module
server
Declared in
Server
Package
libtmux
Source
crates/libtmux/src/server.rs
Other languages
Perlmethod Erlang PowerShell Julia Elixir Haskell Common Lisp PythonRubyLuaTypeScriptGoJavaC#C++SwiftKotlinScalaOCaml F# Clojure
pub async fn new_session( &self, options: impl Into<NewSessionOptions>, ) -> Result<Session, Error>

Description#

The session is always detached: attaching would take over the calling process's terminal, which a library must not do on its own initiative.

tmux prints the new session through the same format machinery as a listing, so this costs one round trip rather than a create followed by a lookup.

A name given as text reaches tmux as that text, # included. Only a name built with TmuxArg::format(), through NewSessionOptions::new(), is expanded as a format, so #(command) in one runs a shell command. See [the crate documentation][crate#a-name-reaches-tmux-as-text].

Errors

Returns an error when tmux refuses the command, which includes a name that already exists, and when its output cannot be decoded.

Examples#

Create windows and split panes. Create a session and a second window, then split from a window and from a pane. 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

//! Create a session and window, then split a window and a pane.
use std::error::Error;
use std::time::Duration;
use libtmux::{NewSessionOptions, NewWindowOptions, Server, SplitDirection, SplitOptions};
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?;
let window = session
.new_window(NewWindowOptions::new("logs").command("cat"))
.await?;
let pane = window
.split(SplitOptions::new(SplitDirection::Below).command("cat"))
.await?;
pane.split(SplitOptions::new(SplitDirection::Right).command("cat"))
.await?;
check(
session.windows().await?.len() == 2,
"expected two session windows",
)?;
check(
window.panes().await?.len() == 3,
"expected three panes in split window",
)?;
check(
server.panes().await?.len() == 4,
"expected four panes on server",
)?;
println!("creation: 2 windows, 4 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-creation-")
.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:

creation: 2 windows, 4 panes
Parameters

tmux command#

The tmux commands behind new_session.

tmux C API#

The C declarations in tmux that implement these commands.

Each path starts at a function a command runs, which is degree 1. The degree counts steps from there along the path, and each step is a call or a reference: degree 2 is reached from that function, degree 3 from the next, and so on.

Create a session and its first pane

  1. 1 cmd_new_session_exec
  2. calls → 2 spawn_window
  3. calls → 3 spawn_pane
  4. calls → 4 window_add_pane
  5. calls → 5 window_pane_create

In other ports#

Create a session

Equivalents of Create a session in other languages
Language Equivalent
Python libtmux.Server.new_session
Ruby LibTmux::Server#new_session
Lua libtmux.Server:new_session
Erlang tmux_session:create/2
Haskell No public Haskell equivalent is implemented; the current modules expose scalar values and version parsing.
TypeScript server.Server.newSession
Go tmux.Server.NewSession
Java io.github.libtmux.Server.newSession
Clojure libtmux.core/new-session!
Kotlin io.github.libtmux.kotlin.Server.newSession
Scala io.github.libtmux.scaladsl.Server.newSession
C# LibTmux.Server.CreateSessionAsync
C++ libtmux::Server::new_session
Swift Server.newSession(named:startDirectory:windowName:width:height:environment:shell:)
OCaml Libtmux_unix.Client.create_session
Perl LibTmux::Server::new_session Explicit Server operation. Captured entities remain local observations; use a new snapshot to observe changes.

No equivalent is recorded in PowerShell, Julia, Elixir, Common Lisp or F#.

Esc

Type to search.

Reference previewOpen reference