tmux

package
v0.16.521 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2026 License: AGPL-3.0 Imports: 23 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package tmux runs the tmux commands the runtime needs. Sessions live on the runtime's own tmux servers (`-L`), so a person's terminal tmux is never touched.

Two servers may be in use at once: the current one, where every new session is started, and a legacy one that older releases started sessions on. A session named with the current prefix always lives on the current server; a session named with the legacy prefix lives wherever it is found (on the legacy server while it lives from before, on the current one once it was started again), and the server it was last seen on is remembered.

Every command runs `tmux` directly (no shell). A read (the polls) gets 5 s; a command a person waits on — a new session, keys typed into a pane — gets 30 s, so a loaded machine starts the conversation late instead of not at all.

Index

Constants

View Source
const EscapeMark = "␛"

EscapeMark stands for ESC in text bound for a terminal, so it stays visible but cannot start a sequence.

View Source
const ProbeTimeout = 2 * time.Second

ProbeTimeout is how long the server may take to answer before keys are typed into a pane.

Variables

View Source
var SafeShells = map[string]bool{"bash": true, "zsh": true, "fish": true, "sh": true, "dash": true}

SafeShells are the foreground programs that mean "nothing runs in the pane but its shell".

Functions

func ForegroundCommand added in v0.16.154

func ForegroundCommand(tmuxSaid string, panePID int) string

ForegroundCommand is the foreground program of the pane whose shell is panePID: what /proc says, else what tmux said (#{pane_current_command}). Every reader of #{pane_current_command} goes through it.

func LiteralArg

func LiteralArg(s string) string

LiteralArg protects a trailing `;`: tmux ends a command at an argument ending in `;` and drops it, even in `send-keys -l`; `\;` stands for a literal one.

func OneLineSafe

func OneLineSafe(s string) string

OneLineSafe is StripControlChars for a value that must stay on one line: runs of white space become one space, and the ends are trimmed.

func ParseNiceness

func ParseNiceness(raw string, set bool) int

ParseNiceness reads a niceness setting the way the previous runtime did: unset is 10, a whole number is clamped to 0..19 (0 turns nice off), anything else is 10. A blank value counts as 0.

func StripControlChars

func StripControlChars(s string) string

StripControlChars makes text safe to type into a terminal prompt: ESC becomes EscapeMark (one `ESC [ 2 0 1 ~` would end a bracketed paste early and the rest would be typed as keys), every other C0 control except tab and newline, DEL and the C1 controls are dropped. Bytes that are not UTF-8 become U+FFFD.

Types

type Config

type Config struct {
	Names
	// ConfigFile is the tmux.conf a new server reads (`-f`) and ApplyConfig re-reads; "" leaves tmux's defaults.
	ConfigFile string
	// PaneBinDir comes first on a pane shell's PATH (wrappers such as a guarded tmux); "" adds nothing.
	PaneBinDir string
	// Nice is the niceness `nice -n` gives every pane shell (and so every agent and build started in it); 0 runs the
	// shell directly. The tmux server itself stays at the runtime's niceness: a niced server on a loaded machine answers
	// the runtime's commands slower than their timeout, and a new conversation dies with "signal: killed". See
	// ParseNiceness.
	Nice int
	// Env is the environment a pane shell takes its allow-listed variables from; nil means this process's.
	Env []string
	// Home is the folder a session starts in when none is given; "" means HOME of Env, else "/".
	Home string
	// PaneEnv adds KEY=VALUE variables to the pane shell of a new session, given the tab the session belongs to ("" for
	// an ad hoc session); nil adds nothing. Integrations hand agents their addresses and tokens this way.
	PaneEnv func(tabID string) []string
}

Config is everything a session is started with on top of the names.

type Keys

type Keys struct {
	// contains filtered or unexported fields
}

Keys types into panes for one writer: every call is bound to the writer's context — the hold of the pane's lock — so a call made after the hold ended types nothing, and one under way is cut short with it.

func (Keys) ExitCopyMode

func (k Keys) ExitCopyMode(name string)

ExitCopyMode leaves copy mode in the session's pane, so typed text reaches the program and not the scrollback.

func (Keys) SendBracketedPaste

func (k Keys) SendBracketedPaste(name, text string) error

SendBracketedPaste pastes text, presses Enter, and Enter again 600 ms later.

func (Keys) SendBracketedPasteOnly

func (k Keys) SendBracketedPasteOnly(name, text string) error

SendBracketedPasteOnly pastes text into a TUI's input as one bracketed paste and presses nothing. A long text goes in several send-keys calls inside the one pair of paste brackets: the program reads it as a single paste all the same.

func (Keys) SendKeySequence

func (k Keys) SendKeySequence(name string, keys ...string) error

SendKeySequence sends several keys in one call, so a chord such as `C-x C-s` arrives back to back.

func (Keys) SendKeys

func (k Keys) SendKeys(name, line string) error

SendKeys sends a line and Enter in one send-keys call; tmux reads the line as key names where it can (a launch or resume line into a shell).

func (Keys) SendKeysSeparated

func (k Keys) SendKeysSeparated(name, text string) error

SendKeysSeparated sends text (as key names where tmux can), then Enter 50 ms later as its own call, so a TUI that reads one burst as a paste sees a typed line and a submit.

func (Keys) SendLiteral

func (k Keys) SendLiteral(name, text string) error

SendLiteral types text literally, without control characters, and presses nothing: for an input a TUI shows in place.

func (Keys) SendLiteralThenEnter

func (k Keys) SendLiteralThenEnter(name, text string) error

SendLiteralThenEnter types text literally (a line that looks like a key name, such as `Enter`, is typed as words), without control characters, then presses Enter 50 ms later.

func (Keys) SendRawKeys

func (k Keys) SendRawKeys(name, keys string) error

SendRawKeys sends keys as tmux reads them: a key name (`Escape`, `Enter`, `C-g`) or a string. Nothing is stripped.

type Names

type Names struct {
	Socket       string // e.g. the runtime's current server
	LegacySocket string // the server older releases started sessions on
	Prefix       string // sessions of this runtime on Socket; new sessions get it
	LegacyPrefix string // sessions that may be on either server
}

Names are the servers and session name prefixes. Sessions named with LegacyPrefix may live on either server; the others live on Socket.

type PaneDetail

type PaneDetail struct {
	Cwd            string
	Command        string
	PID            int
	Width, Height  int
	SessionCreated int64 // epoch seconds
}

PaneDetail is what one display-message tells about a session's pane; zero values mean unknown.

type PaneInfo

type PaneInfo struct {
	Command        string // pane_current_command
	Path           string // pane_current_path
	PID            int    // pane_pid, 0 when unreadable
	WindowActivity int64  // window_activity (epoch seconds), 0 when unreadable
}

PaneInfo is one pane of the snapshot every poll judges processes by.

type SlowError added in v0.16.5

type SlowError struct {
	Command string        // the tmux command, e.g. new-session
	After   time.Duration // how long it was given before it was killed
}

SlowError is a command tmux did not answer in its time: the machine is overloaded, nothing is broken.

func (*SlowError) Error added in v0.16.5

func (e *SlowError) Error() string

type Terminal

type Terminal interface {
	// Size is the size the page gave the terminal; false when no page has it open.
	Size(session string) (cols, rows int, ok bool)
	// Pause stops output to the page and answers the size to restore; false when there is no terminal or it is paused.
	Pause(session string) (cols, rows int, ok bool)
	// Resize sets the terminal's size, whatever the page asked.
	Resize(session string, cols, rows int)
	Resume(session string)
}

Terminal is the page's terminal attached to a session (internal/terminal's Server is one).

type Tmux

type Tmux struct {
	// contains filtered or unexported fields
}

Tmux runs commands against the runtime's servers.

func New

func New(n Names) *Tmux

New runs commands on the named servers; sessions it creates start with tmux's defaults and the process environment.

func NewConfig

func NewConfig(cfg Config) *Tmux

NewConfig runs commands on the named servers and starts sessions as cfg says.

func (*Tmux) AllPanes

func (t *Tmux) AllPanes() map[string]PaneInfo

AllPanes is ReadAllPanes with a silent tmux read as no panes.

func (*Tmux) ApplyConfig

func (t *Tmux) ApplyConfig(socket string)

ApplyConfig re-reads the config file on one server, or on every server when socket is "", and sets the scroll overlay over it. A server that is not running yet gets them when its first session starts.

func (*Tmux) Attached added in v0.15.40

func (t *Tmux) Attached(name string) int

Attached is how many tmux clients have the session open now (a person's `tmux attach`, a page's terminal); 0 when tmux does not say.

func (*Tmux) Capture

func (t *Tmux) Capture(name string) (string, bool)

Capture is the visible screen of the session's pane as text; false when tmux failed.

func (*Tmux) CaptureAtWidth

func (t *Tmux) CaptureAtWidth(term Terminal, name string, cols, rows int) (string, bool)

CaptureAtWidth is the pane's screen as a program drawing at least cols×rows would show it, for parsing a TUI's options. When the page's terminal is wider than 50 columns and at least rows tall, the screen with 50 lines of scrollback is enough. Otherwise the terminal is paused, resized to at least cols×rows, captured after 300 ms, restored and resumed 300 ms later: the person's terminal visibly changes size for about 0.6 s. With no terminal open (or one already paused) it is the plain screen at the pane's own size. term may be nil.

func (*Tmux) CaptureHistory

func (t *Tmux) CaptureHistory(name string, lines int) (string, bool)

CaptureHistory is the visible screen and up to lines lines of scrollback above it.

func (*Tmux) CaptureStyled

func (t *Tmux) CaptureStyled(name string) (string, bool)

CaptureStyled is the visible screen with its SGR attributes (`-e`), which tell a TUI's dim placeholder from typed text.

func (*Tmux) CaptureStyledTall added in v0.16.86

func (t *Tmux) CaptureStyledTall(term Terminal, name string, cols, rows int) (string, bool)

CaptureStyledTall is the styled screen at no less than cols×rows with the page's terminal attached: it is paused, made that large, captured and given its size back, about 0.6 s the person can see. false with no such terminal, or one that large already.

func (*Tmux) CheckTerminalProcess

func (t *Tmux) CheckTerminalProcess(name string) (safe bool, process string)

CheckTerminalProcess says whether only a shell runs in the session's pane, and the foreground program ("unknown" when tmux did not say).

func (*Tmux) Command

func (t *Tmux) Command(session string, args ...string) (string, error)

Command runs any other tmux command on the server the session lives on and returns what it printed.

func (*Tmux) CreateSession

func (t *Tmux) CreateSession(name string, cols, rows int, cwd string) error

CreateSession starts a detached session of cols×rows running the pane shell in cwd (else Home), always on the current server; then the config is re-read on that server. The server this may start is not niced (the pane shell is): it answers every command of the runtime, each with a few seconds to do it.

func (*Tmux) Display

func (t *Tmux) Display(name, format string) (string, bool)

Display is `display-message -p` of a format for the session's active pane, trimmed; false when tmux failed.

func (*Tmux) ExitCopyMode

func (t *Tmux) ExitCopyMode(name string)

func (*Tmux) GrowDetached added in v0.16.86

func (t *Tmux) GrowDetached(name string, cols, rows int) bool

GrowDetached makes the window of a session no client is attached to at least cols×rows and gives the program time to redraw; true when it grew. An attached terminal keeps the size it set. resize-window turns the window's window-size to manual, so that option is unset again: a terminal attached later sets the size as before.

func (*Tmux) HasSession

func (t *Tmux) HasSession(name string) bool

HasSession says whether the session exists (exact name).

func (*Tmux) IsAppSession

func (t *Tmux) IsAppSession(name string) bool

IsAppSession says whether the name is one of the runtime's sessions (either prefix).

func (*Tmux) KillServer

func (t *Tmux) KillServer()

KillServer ends every server of the runtime and every session on them: the reset of all tabs.

func (*Tmux) KillSession

func (t *Tmux) KillSession(name string)

KillSession ends the session: SIGTERM to its pane's process group and kill-session, checking 5 times 200 ms apart; then SIGKILL and kill-session again, checking 3 times. A session that still lives is left.

func (*Tmux) ListSessions

func (t *Tmux) ListSessions() []string

ListSessions are the runtime's sessions on every server: the current server's first.

func (*Tmux) Names

func (t *Tmux) Names() Names

Names are the servers and prefixes this Tmux works with.

func (*Tmux) NewSessionName

func (t *Tmux) NewSessionName() string

NewSessionName is an ad hoc session name: the prefix and three random six-character ids.

func (*Tmux) OwnShellID added in v0.15.40

func (t *Tmux) OwnShellID(convID, session string) (string, bool)

OwnShellID is the id of an own terminal from its session name, false for any other session of the conversation.

func (*Tmux) OwnShellName added in v0.15.40

func (t *Tmux) OwnShellName(convID, id string) string

OwnShellName is the session of one of a v2 conversation's own terminals. Like the pane shell it does not have the workspace form, so the layout never adopts it as a tab.

func (*Tmux) OwnShellPrefix added in v0.15.40

func (t *Tmux) OwnShellPrefix(convID string) string

OwnShellPrefix is what the sessions of a v2 conversation's own terminals begin with: `<prefix>v2t-<convID>-`.

func (*Tmux) PaneCurrentCommand

func (t *Tmux) PaneCurrentCommand(name string) string

PaneCurrentCommand is the program in the foreground of the session's pane, or "". It is checked against /proc (see foregroundOf): tmux alone answers `nice` for a pane whose foreground it cannot read.

func (*Tmux) PaneDetail

func (t *Tmux) PaneDetail(name string) PaneDetail

PaneDetail reads the pane's folder, foreground program, pid, size and the session's start in one call.

func (*Tmux) PaneID

func (t *Tmux) PaneID(name string) string

PaneID is the active pane's id (`%12`), the key a program in the pane sees as $TMUX_PANE; "" when unknown.

func (*Tmux) PanePID

func (t *Tmux) PanePID(name string) int

PanePID is the pid of the session's active pane (its shell), or 0.

func (*Tmux) PanePath

func (t *Tmux) PanePath(name string) string

PanePath is tmux's idea of the active pane's folder, or "".

func (*Tmux) PaneShellName

func (t *Tmux) PaneShellName(tabID string, legacy bool) (string, bool)

PaneShellName is the session of a conversation's right-panel shell, `<prefix>shell-<tabID>`, under the legacy prefix when legacy is set; false for a tab id that cannot be part of a name. It does not have the workspace form, so the layout never adopts it as a tab.

func (*Tmux) PaneTitle

func (t *Tmux) PaneTitle(name string) string

PaneTitle is the active pane's title, or "".

func (*Tmux) ParseSessionName

func (t *Tmux) ParseSessionName(name string) (wsID, paneID, tabID string, ok bool)

ParseSessionName inverts SessionName for either prefix; false for any other name.

func (*Tmux) ReadAllPanes

func (t *Tmux) ReadAllPanes() (map[string]PaneInfo, bool)

ReadAllPanes is every pane of the runtime's sessions on every server, by session name (for a session with several panes, the last one listed). ok is false when any server did not answer — timed out or failed for another reason — which a caller must not read as "no panes": a loaded machine can keep list-panes past its timeout, and every working agent would look gone at once. A server that is not running is no panes.

While the servers are watched (see Watch) the answer is what their events last said, and no tmux is started.

func (*Tmux) ReadAllPanesNow

func (t *Tmux) ReadAllPanesNow() (map[string]PaneInfo, bool)

ReadAllPanesNow is ReadAllPanes after a listing asked for now, for a caller about to act on what it saw a moment ago. ok is false when the servers are not watched or did not answer: the caller knows nothing newer than ReadAllPanes told it.

func (*Tmux) ResolveExistingDir

func (t *Tmux) ResolveExistingDir(preferred string) string

ResolveExistingDir is preferred, or its nearest existing ancestor folder, or Home when none exists or preferred is "".

func (*Tmux) Responsive

func (t *Tmux) Responsive(name string) error

Responsive asks the session's server a question that costs it nothing and says whether the answer came in ProbeTimeout: a *SlowError when it did not. Keys typed into a server this slow arrive apart, later than the waits between them, so a writer asks first and types later. A session that is gone is not slow: the write says so itself.

func (*Tmux) SendBracketedPaste

func (t *Tmux) SendBracketedPaste(name, text string) error

func (*Tmux) SendBracketedPasteOnly

func (t *Tmux) SendBracketedPasteOnly(name, text string) error

func (*Tmux) SendKeySequence

func (t *Tmux) SendKeySequence(name string, keys ...string) error

func (*Tmux) SendKeys

func (t *Tmux) SendKeys(name, line string) error

func (*Tmux) SendKeysSeparated

func (t *Tmux) SendKeysSeparated(name, text string) error

func (*Tmux) SendLiteral

func (t *Tmux) SendLiteral(name, text string) error

func (*Tmux) SendLiteralThenEnter

func (t *Tmux) SendLiteralThenEnter(name, text string) error

func (*Tmux) SendRawKeys

func (t *Tmux) SendRawKeys(name, keys string) error

func (*Tmux) SessionName

func (t *Tmux) SessionName(wsID, paneID, tabID string) string

SessionName is the session of a workspace tab: `<prefix><wsID>-<paneID>-<tabID>`.

func (*Tmux) SessionsOfPane

func (t *Tmux) SessionsOfPane(paneID, socket string) []string

SessionsOfPane are the runtime's sessions a pane id names. Each server numbers its own panes, so one id can name a pane on each; socket (the last part of the pane's $TMUX path) settles it when the caller knows it, and a socket that is not one of the runtime's finds nothing.

func (*Tmux) Shell

func (t *Tmux) Shell() string

Shell is the person's login shell: SHELL of the environment, else the platform's default.

func (*Tmux) ShellLaunchCommand

func (t *Tmux) ShellLaunchCommand() string

ShellLaunchCommand is the command a new session runs: the login shell under `env -i` with the allow-listed environment, so neither the tmux server's cached environment nor the runtime's own variables reach the pane. TMUX and TMUX_PANE, set by tmux for the pane, are expanded by the shell tmux runs the command with and so survive `env -i`. With a niceness configured the shell runs under `nice`, so the panes yield the CPU and the server does not. Every way of starting a pane shell must go through it.

func (*Tmux) SocketOf

func (t *Tmux) SocketOf(name string) string

SocketOf is the server the session is on, or for one that does not exist, the server it would be started on (the current one).

func (*Tmux) Sockets

func (t *Tmux) Sockets() []string

Sockets are the servers the runtime's sessions may be on: the current one first.

func (*Tmux) TabOf

func (t *Tmux) TabOf(session string) string

TabOf is the tab a session belongs to: a workspace tab's session or a conversation's right-panel shell; "" for any other session.

func (*Tmux) With

func (t *Tmux) With(ctx context.Context) Keys

With is the key sender of a writer whose hold of a pane lives as long as ctx.

type WatchOptions

type WatchOptions struct {
	// Reconcile is the middle of the time between two listings at rest; each wait is within a third of it. 0 is 45 s.
	Reconcile time.Duration
	// Log, when set, hears what an operator would want in the journal: a connection made or lost, events that were missed.
	Log func(level, msg string, kv ...any)
	// contains filtered or unexported fields
}

WatchOptions tune a Watcher; the zero value is what the runtime uses.

type WatchStats

type WatchStats struct {
	Connects   int64 // control clients that connected
	Listings   int64 // listings over the control connection, at events and at rest
	Reconciles int64 // of them, the ones at rest
	Missed     int64 // listings at rest that found a change no event told of
	Served     int64 // ReadAllPanes answered without a tmux command
	Captures   int64 // screens read over the control connection, with no tmux process of their own
}

WatchStats count what a Watcher did since it started.

type Watcher

type Watcher struct {
	// contains filtered or unexported fields
}

Watcher keeps the control clients of a Tmux's servers.

func Watch

func Watch(ctx context.Context, t *Tmux, opt WatchOptions) *Watcher

Watch starts listening to t's servers until ctx ends or Stop. While a server cannot be listened to (no client yet, a client that stopped answering) ReadAllPanes asks it with a tmux command of its own, as without a Watcher. It returns nil when the session names leave no room for the client's own session.

func (*Watcher) Stats

func (w *Watcher) Stats() WatchStats

Stats are the counts so far.

func (*Watcher) Stop

func (w *Watcher) Stop()

Stop ends the control clients and waits for them; ReadAllPanes asks tmux itself again.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL