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
- Variables
- func ForegroundCommand(tmuxSaid string, panePID int) string
- func LiteralArg(s string) string
- func OneLineSafe(s string) string
- func ParseNiceness(raw string, set bool) int
- func StripControlChars(s string) string
- type Config
- type Keys
- func (k Keys) ExitCopyMode(name string)
- func (k Keys) SendBracketedPaste(name, text string) error
- func (k Keys) SendBracketedPasteOnly(name, text string) error
- func (k Keys) SendKeySequence(name string, keys ...string) error
- func (k Keys) SendKeys(name, line string) error
- func (k Keys) SendKeysSeparated(name, text string) error
- func (k Keys) SendLiteral(name, text string) error
- func (k Keys) SendLiteralThenEnter(name, text string) error
- func (k Keys) SendRawKeys(name, keys string) error
- type Names
- type PaneDetail
- type PaneInfo
- type SlowError
- type Terminal
- type Tmux
- func (t *Tmux) AllPanes() map[string]PaneInfo
- func (t *Tmux) ApplyConfig(socket string)
- func (t *Tmux) Attached(name string) int
- func (t *Tmux) Capture(name string) (string, bool)
- func (t *Tmux) CaptureAtWidth(term Terminal, name string, cols, rows int) (string, bool)
- func (t *Tmux) CaptureHistory(name string, lines int) (string, bool)
- func (t *Tmux) CaptureStyled(name string) (string, bool)
- func (t *Tmux) CaptureStyledTall(term Terminal, name string, cols, rows int) (string, bool)
- func (t *Tmux) CheckTerminalProcess(name string) (safe bool, process string)
- func (t *Tmux) Command(session string, args ...string) (string, error)
- func (t *Tmux) CreateSession(name string, cols, rows int, cwd string) error
- func (t *Tmux) Display(name, format string) (string, bool)
- func (t *Tmux) ExitCopyMode(name string)
- func (t *Tmux) GrowDetached(name string, cols, rows int) bool
- func (t *Tmux) HasSession(name string) bool
- func (t *Tmux) IsAppSession(name string) bool
- func (t *Tmux) KillServer()
- func (t *Tmux) KillSession(name string)
- func (t *Tmux) ListSessions() []string
- func (t *Tmux) Names() Names
- func (t *Tmux) NewSessionName() string
- func (t *Tmux) OwnShellID(convID, session string) (string, bool)
- func (t *Tmux) OwnShellName(convID, id string) string
- func (t *Tmux) OwnShellPrefix(convID string) string
- func (t *Tmux) PaneCurrentCommand(name string) string
- func (t *Tmux) PaneDetail(name string) PaneDetail
- func (t *Tmux) PaneID(name string) string
- func (t *Tmux) PanePID(name string) int
- func (t *Tmux) PanePath(name string) string
- func (t *Tmux) PaneShellName(tabID string, legacy bool) (string, bool)
- func (t *Tmux) PaneTitle(name string) string
- func (t *Tmux) ParseSessionName(name string) (wsID, paneID, tabID string, ok bool)
- func (t *Tmux) ReadAllPanes() (map[string]PaneInfo, bool)
- func (t *Tmux) ReadAllPanesNow() (map[string]PaneInfo, bool)
- func (t *Tmux) ResolveExistingDir(preferred string) string
- func (t *Tmux) Responsive(name string) error
- func (t *Tmux) SendBracketedPaste(name, text string) error
- func (t *Tmux) SendBracketedPasteOnly(name, text string) error
- func (t *Tmux) SendKeySequence(name string, keys ...string) error
- func (t *Tmux) SendKeys(name, line string) error
- func (t *Tmux) SendKeysSeparated(name, text string) error
- func (t *Tmux) SendLiteral(name, text string) error
- func (t *Tmux) SendLiteralThenEnter(name, text string) error
- func (t *Tmux) SendRawKeys(name, keys string) error
- func (t *Tmux) SessionName(wsID, paneID, tabID string) string
- func (t *Tmux) SessionsOfPane(paneID, socket string) []string
- func (t *Tmux) Shell() string
- func (t *Tmux) ShellLaunchCommand() string
- func (t *Tmux) SocketOf(name string) string
- func (t *Tmux) Sockets() []string
- func (t *Tmux) TabOf(session string) string
- func (t *Tmux) With(ctx context.Context) Keys
- type WatchOptions
- type WatchStats
- type Watcher
Constants ¶
const EscapeMark = "␛"
EscapeMark stands for ESC in text bound for a terminal, so it stays visible but cannot start a sequence.
const ProbeTimeout = 2 * time.Second
ProbeTimeout is how long the server may take to answer before keys are typed into a pane.
Variables ¶
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
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
ExitCopyMode leaves copy mode in the session's pane, so typed text reaches the program and not the scrollback.
func (Keys) SendBracketedPaste ¶
SendBracketedPaste pastes text, presses Enter, and Enter again 600 ms later.
func (Keys) SendBracketedPasteOnly ¶
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 ¶
SendKeySequence sends several keys in one call, so a chord such as `C-x C-s` arrives back to back.
func (Keys) SendKeys ¶
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 ¶
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 ¶
SendLiteral types text literally, without control characters, and presses nothing: for an input a TUI shows in place.
func (Keys) SendLiteralThenEnter ¶
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 ¶
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.
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 ¶
New runs commands on the named servers; sessions it creates start with tmux's defaults and the process environment.
func (*Tmux) ApplyConfig ¶
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
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 ¶
Capture is the visible screen of the session's pane as text; false when tmux failed.
func (*Tmux) CaptureAtWidth ¶
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 ¶
CaptureHistory is the visible screen and up to lines lines of scrollback above it.
func (*Tmux) CaptureStyled ¶
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
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 ¶
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 ¶
Command runs any other tmux command on the server the session lives on and returns what it printed.
func (*Tmux) CreateSession ¶
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 ¶
Display is `display-message -p` of a format for the session's active pane, trimmed; false when tmux failed.
func (*Tmux) ExitCopyMode ¶
func (*Tmux) GrowDetached ¶ added in v0.16.86
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 ¶
HasSession says whether the session exists (exact name).
func (*Tmux) IsAppSession ¶
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 ¶
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 ¶
ListSessions are the runtime's sessions on every server: the current server's first.
func (*Tmux) NewSessionName ¶
NewSessionName is an ad hoc session name: the prefix and three random six-character ids.
func (*Tmux) OwnShellID ¶ added in v0.15.40
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
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
OwnShellPrefix is what the sessions of a v2 conversation's own terminals begin with: `<prefix>v2t-<convID>-`.
func (*Tmux) PaneCurrentCommand ¶
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 ¶
PaneID is the active pane's id (`%12`), the key a program in the pane sees as $TMUX_PANE; "" when unknown.
func (*Tmux) PaneShellName ¶
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) ParseSessionName ¶
ParseSessionName inverts SessionName for either prefix; false for any other name.
func (*Tmux) ReadAllPanes ¶
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 ¶
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 ¶
ResolveExistingDir is preferred, or its nearest existing ancestor folder, or Home when none exists or preferred is "".
func (*Tmux) Responsive ¶
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 (*Tmux) SendBracketedPasteOnly ¶
func (*Tmux) SendKeysSeparated ¶
func (*Tmux) SendLiteral ¶
func (*Tmux) SendLiteralThenEnter ¶
func (*Tmux) SendRawKeys ¶
func (*Tmux) SessionName ¶
SessionName is the session of a workspace tab: `<prefix><wsID>-<paneID>-<tabID>`.
func (*Tmux) SessionsOfPane ¶
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 ¶
Shell is the person's login shell: SHELL of the environment, else the platform's default.
func (*Tmux) ShellLaunchCommand ¶
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 ¶
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 ¶
Sockets are the servers the runtime's sessions may be on: the current one first.
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.