tmux-tango 2.13.0

A CLI tool for managing tmux sessions - dance between your sessions!
Documentation
//! Runtime-only tmux key bindings installed for the lifetime of a tango process.
//!
//! Installs session-scoped Alt-Left detach bindings via `tmux bind-key -n` and
//! removes them on drop. The bindings are gated on a per-session user option
//! (`@tango_active`); only sessions tango has marked active will detach on press.
//! All other sessions pass the key through to the active pane unchanged.
//!
//! Two bindings are installed because macOS terminals (Terminal.app, iTerm2, Ghostty
//! with default Option behavior) rewrite the physical Option+Left key to `ESC b`
//! (`M-b`) — the readline backward-word sequence — instead of the CSI modified-arrow
//! sequence tmux's `M-Left` matches. Binding both forms covers either terminal mode.
//!
//! The gating uses a `tmux show-options` shell test rather than the `#{@user_option}`
//! format because the latter only expands inside `if-shell -F` on tmux >= 3.0. Older
//! distros (Ubuntu 18.04, RHEL 7/8) still ship tmux 1.8–2.6, where the format would
//! silently expand to an empty string and the binding would never fire.

use std::process::{Command, Stdio};

const ACTIVE_FLAG: &str = "@tango_active";
const BINDING_COND: &str =
    "[ \"$(tmux show-options -v -t '#{session_name}' @tango_active 2>/dev/null)\" = 1 ]";
const BINDING_THEN: &str = "detach-client";

/// Keys we bind, paired with their `send-keys` passthrough form for the else branch.
/// `M-Left` — terminals that send the CSI modified-arrow sequence for Alt+Left.
/// `M-b`    — macOS terminals that rewrite Alt+Left to the readline backward-word
///            sequence (`ESC b`). In non-tango sessions this is forwarded so shells
///            still get word-back.
const BINDINGS: &[(&str, &str)] = &[
    ("M-Left", "send-keys M-Left"),
    ("M-b",    "send-keys M-b"),
];

fn run_tmux(args: &[&str]) {
    let _ = Command::new("tmux")
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status();
}

/// Like `run_tmux` but captures stdout. Returns None on spawn failure or nonzero exit.
fn run_tmux_capture(args: &[&str]) -> Option<String> {
    let output = Command::new("tmux")
        .args(args)
        .stdin(Stdio::null())
        .stderr(Stdio::null())
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    Some(String::from_utf8_lossy(&output.stdout).to_string())
}

/// Whether any session still carries `@tango_active 1` — i.e. some tango process is
/// mid-attach right now. Uses the same tmux-1.8-safe `show-options -v` query as the
/// binding condition; format-style `#{@tango_active}` expansion needs tmux >= 3.0.
fn any_session_active() -> bool {
    let Some(sessions) = run_tmux_capture(&["list-sessions", "-F", "#{session_name}"]) else {
        return false;
    };
    sessions.lines().filter(|name| !name.is_empty()).any(|session| {
        run_tmux_capture(&["show-options", "-v", "-t", session, ACTIVE_FLAG])
            .map(|value| value.trim() == "1")
            .unwrap_or(false)
    })
}

/// Install the detach bindings on the running tmux server.
/// Idempotent and safe to call before any tmux server exists — the call simply
/// fails silently and can be retried after `attach-session` starts a server.
pub fn install_binding() {
    for (key, passthrough) in BINDINGS {
        run_tmux(&[
            "bind-key", "-n", key,
            "if-shell", BINDING_COND,
            BINDING_THEN, passthrough,
        ]);
    }
}

/// Remove tango's detach bindings. Best-effort: silently ignores errors and absent servers.
pub fn unbind_binding() {
    for (key, _) in BINDINGS {
        run_tmux(&["unbind-key", "-n", key]);
    }
}

/// Mark `session` as a tango-managed attachment so the binding fires there.
pub fn set_active(session: &str) {
    run_tmux(&["set-option", "-t", session, ACTIVE_FLAG, "1"]);
}

/// Clear the tango-active flag on `session`. Called after the attach returns.
pub fn clear_active(session: &str) {
    run_tmux(&["set-option", "-t", session, ACTIVE_FLAG, "0"]);
}

/// RAII guard: installs the binding on construction and unbinds it on drop.
/// Drop is best-effort — a panic or kill mid-attach will still run the unbind.
pub struct BindingGuard;

impl BindingGuard {
    pub fn new() -> Self {
        install_binding();
        BindingGuard
    }
}

impl Drop for BindingGuard {
    fn drop(&mut self) {
        // Another tango instance mid-attach still needs the server-global bindings; its own
        // guard removes them at its exit (a tango's flag is always 0 by the time it drops).
        // A SIGKILLed tango can leave a stale flag and leak the bindings — `tango tmux
        // cleanup` covers that.
        if !any_session_active() {
            unbind_binding();
        }
    }
}