Attach and send keys
Needs libtmux for Go 0.x Install
Create a session, run a command in one of its panes, and read what the pane prints. These examples use libtmux from your program; to attach your terminal interactively, see Attaching to tmux.
The steps below build the program one call at a time. Each block is a range of lines from the complete program, which includes setup, error handling, and cleanup. Each step names the tmux command behind the call; the native version of this example builds the same sequence in shell. Source names the file.
Steps
1. Get a server
Every call that reaches tmux takes a context.Context. The program gives the
whole run 30 seconds, so a wait that never matches ends with
context.DeadlineExceeded instead of blocking forever. tmux.NewServer
validates a tmux.ServerOptions and does not start tmux.
ServerOptions.SocketName selects a named socket, like -L, and
ServerOptions.ConfigFile set to os.DevNull keeps your tmux configuration
file out, like -f /dev/null. Choose a socket name that no other tmux uses,
because cleanup ends the server on that socket. With an unused
name, the program neither touches nor is changed by the tmux you already use.
The native step is
Choose a private socket.
The server goes to run, so a test can pass in an isolated one.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)defer cancel()
// Choose an unused socket name: cleanup kills the server selected here.// The empty config keeps personal settings out of a new server.server, err := tmux.NewServer(tmux.ServerOptions{ SocketName: "libtmux-pane-io", ConfigFile: os.DevNull,})if err != nil { return fmt.Errorf("configure tmux server: %w", err)}return run(ctx, server)
2. Create the session
Server.NewSession creates a detached session, like new-session -d, which
starts the server when the socket has none. NewSessionRequest.Name
names the session and NewSessionRequest.Command is the program its pane
runs. sh keeps the pane from depending on what your login shell does at
startup. The call fails with ErrSessionExists when the socket already holds a
session of that name, as after an earlier run that was killed before it cleaned
up, unless NewSessionRequest.KillExisting is set. A program that runs
repeatedly should look for its session first;
Finding an existing session instead
links that pattern.
session, err := server.NewSession(ctx, tmux.NewSessionRequest{ Name: "libtmux-pane-io", Command: "sh",})if err != nil { return fmt.Errorf("create session: %w", err)}
3. Pick the pane
Session.ResolveActivePane lists the session’s panes, like list-panes -s,
and returns the active pane of the active window as a tmux.Pane. The program
keeps the pane it found, which carries its pane ID, and never has to address a
pane by position. The native
pane ID step
explains why code addresses a pane by identity.
pane, err := session.ResolveActivePane(ctx)if err != nil { return fmt.Errorf("resolve pane: %w", err)}
4. Watch the pane’s output
Pane.OpenObservation opens a dedicated control-mode client on the pane, which
tmux sees as attach-session with -C, and captures the pane’s visible text
with capture-pane. It returns a tmux.PaneObservation that begins at that
text, with no gap before the output that follows. The caller must close it,
which the deferred call does. Open it before typing, so no output is missed.
output, err := pane.OpenObservation(ctx)if err != nil { return fmt.Errorf("observe pane: %w", err)}defer func() { err = errors.Join(err, output.Close()) }()
5. Send a command
Pane.Writer returns the pane’s keyboard as an io.Writer. The bytes are typed
literally and each newline is the Enter key, so fmt.Fprintln submits the line.
It costs two commands: send-keys -l types the text and a second send-keys
presses the Enter key, the pair that the native steps
Type text without pressing keys
and Press Enter run in
shell.
command := `echo "6 x 7 = $((6 * 7))"`if _, err := fmt.Fprintln(pane.Writer(ctx), command); err != nil { return fmt.Errorf("type command: %w", err)}6. Wait for the answer
PaneObservation.WaitFor reads what the pane writes after the observation
opened and calls the function with all of it each time new output arrives,
until the function returns true, the context ends, or the observation is lost. tmux
pushes each write to the control client as an %output notification, so there
is no sleep and no repeated capture-pane; the native step
Poll until the line appears
repeats the capture instead. The terminal echoes the typed line, and the echo
is pane output like any other. The match is for 6 x 7 = 42, which only the
computed answer contains: the typed line says $((6 * 7)).
if _, err := output.WaitFor(ctx, func(text string) bool { return strings.Contains(text, "6 x 7 = 42")}); err != nil { return fmt.Errorf("wait for answer: %w", err)}fmt.Println("the pane answered 6 x 7 = 42")7. Read until the line appears
PaneObservation.Reader is an io.Reader over the same %output stream, so a
bufio scanner reads the pane line by line, as it would a file. Reads block
until the pane writes, the context ends, or the observation closes. The bytes
are the terminal’s: the echo of the typed command arrives first, and a prompt
can share the reply’s line. The loop matches how the line ends, and the typed
command, which ends in a quote, cannot match.
next := `echo "streamed $((1 + 1)) lines"`if _, err := fmt.Fprintln(pane.Writer(ctx), next); err != nil { return fmt.Errorf("type command: %w", err)}scanner := bufio.NewScanner(output.Reader(ctx))for scanner.Scan() { // These are the terminal's bytes: the echo comes first, and a prompt // can share the reply's line. Match how the reply ends. if strings.HasSuffix(scanner.Text(), "streamed 2 lines") { fmt.Println("read the line: streamed 2 lines") return nil }}return fmt.Errorf("read pane: %w", scanner.Err())8. Clean up
Session.Kill destroys the session and its windows, like kill-session. The
deferred calls run in reverse order on every return: the observation closes,
then the session is killed. The kill uses a context of its own that the run’s
cancellation cannot end, with one second to finish, so a deadline that has
passed does not skip the cleanup, and errors.Join reports a cleanup failure
beside the original error. With the default exit-empty setting, the private
server exits when its last session is gone.
defer func() { cleanupCtx, cleanupCancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second) defer cleanupCancel() err = errors.Join(err, session.Kill(cleanupCtx))}()
The complete program
The steps follow the order a reader meets the calls. In the file, the deferred
session cleanup comes right after the call it undoes. The whole file below is
read from the repository’s tested example. From a clone of libtmux-go,
go -C examples run ./pane-io runs it, and it prints
the pane answered 6 x 7 = 42 and then read the line: streamed 2 lines.
// Command pane-io treats a pane as a pair of streams: type into it with an// io.Writer and read what it prints back through an io.Reader.package main
import ( "bufio" "context" "errors" "fmt" "log" "os" "strings" "time"
"github.com/libtmux/libtmux-go/tmux")
func main() { if err := start(); err != nil { log.Fatal(err) }}
// start owns cleanup because log.Fatal skips deferred calls in main.func start() error { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel()
// Choose an unused socket name: cleanup kills the server selected here. // The empty config keeps personal settings out of a new server. server, err := tmux.NewServer(tmux.ServerOptions{ SocketName: "libtmux-pane-io", ConfigFile: os.DevNull, }) if err != nil { return fmt.Errorf("configure tmux server: %w", err) } return run(ctx, server)}
// run accepts injected server state so tests can isolate the example.func run(ctx context.Context, server tmux.Server) (err error) { // A plain POSIX shell, so the pane does not depend on what your login // shell does at startup. session, err := server.NewSession(ctx, tmux.NewSessionRequest{ Name: "libtmux-pane-io", Command: "sh", }) if err != nil { return fmt.Errorf("create session: %w", err) } defer func() { cleanupCtx, cleanupCancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second) defer cleanupCancel() err = errors.Join(err, session.Kill(cleanupCtx)) }() pane, err := session.ResolveActivePane(ctx) if err != nil { return fmt.Errorf("resolve pane: %w", err) }
// Open the observation before typing, so no output is missed. output, err := pane.OpenObservation(ctx) if err != nil { return fmt.Errorf("observe pane: %w", err) } defer func() { err = errors.Join(err, output.Close()) }()
// A pane is an io.Writer, and a newline is the Enter key. command := `echo "6 x 7 = $((6 * 7))"` if _, err := fmt.Fprintln(pane.Writer(ctx), command); err != nil { return fmt.Errorf("type command: %w", err) } // The terminal echoes what is typed, so wait for the answer: the typed // line says "$((6 * 7))" and never "42". if _, err := output.WaitFor(ctx, func(text string) bool { return strings.Contains(text, "6 x 7 = 42") }); err != nil { return fmt.Errorf("wait for answer: %w", err) } fmt.Println("the pane answered 6 x 7 = 42")
// The observation is also an io.Reader over what the pane prints next, so // whatever reads a stream reads a pane. next := `echo "streamed $((1 + 1)) lines"` if _, err := fmt.Fprintln(pane.Writer(ctx), next); err != nil { return fmt.Errorf("type command: %w", err) } scanner := bufio.NewScanner(output.Reader(ctx)) for scanner.Scan() { // These are the terminal's bytes: the echo comes first, and a prompt // can share the reply's line. Match how the reply ends. if strings.HasSuffix(scanner.Text(), "streamed 2 lines") { fmt.Println("read the line: streamed 2 lines") return nil } } return fmt.Errorf("read pane: %w", scanner.Err())}Finding an existing session instead
For a script that runs repeatedly, look up a session before creating it. Attaching to tmux shows that pattern, and Filtering and querying, in practice covers absent and ambiguous matches.
Where this comes from
The program is examples/pane-io/main.go in the libtmux-go repository. The
page shows it whole and quotes a range of its lines in each step.