tty

package
v0.91.0 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2026 License: MIT Imports: 24 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 tty provides an embeddable interactive tmux component for sending keystrokes, mouse events, and clipboard paste to a tmux pane while capturing and rendering its output.

Package tty provides an embeddable tmux terminal model for TUI plugins. It handles tmux session management, key mapping, cursor rendering, and adaptive polling.

Index

Constants

View Source
const (
	// PollingDecayFast is the polling interval during active typing.
	PollingDecayFast = 50 * time.Millisecond

	// PollingDecayMedium is the polling interval after brief inactivity.
	PollingDecayMedium = 200 * time.Millisecond

	// PollingDecaySlow is the polling interval after extended inactivity.
	PollingDecaySlow = 250 * time.Millisecond

	// KeystrokeDebounce delays polling after keystrokes to batch rapid typing.
	// Allows typing bursts to coalesce into fewer polls, reducing CPU usage.
	KeystrokeDebounce = 20 * time.Millisecond

	// InactivityMediumThreshold triggers medium polling.
	InactivityMediumThreshold = 2 * time.Second

	// InactivitySlowThreshold triggers slow polling.
	InactivitySlowThreshold = 10 * time.Second
)

Polling interval constants for adaptive polling

View Source
const (
	SGRWheelUp   = 64
	SGRWheelDown = 65
)

SGR wheel button codes. Wheel notches are reported as button presses in the 64+ range and have no matching release event.

View Source
const (
	BracketedPasteEnable  = "\x1b[?2004h" // ESC[?2004h - app enables bracketed paste
	BracketedPasteDisable = "\x1b[?2004l" // ESC[?2004l - app disables bracketed paste
	BracketedPasteStart   = "\x1b[200~"   // ESC[200~ - start of pasted content
	BracketedPasteEnd     = "\x1b[201~"   // ESC[201~ - end of pasted content

	MouseModeEnable1000  = "\x1b[?1000h"
	MouseModeEnable1002  = "\x1b[?1002h"
	MouseModeEnable1003  = "\x1b[?1003h"
	MouseModeEnable1006  = "\x1b[?1006h"
	MouseModeEnable1015  = "\x1b[?1015h"
	MouseModeDisable1000 = "\x1b[?1000l"
	MouseModeDisable1002 = "\x1b[?1002l"
	MouseModeDisable1003 = "\x1b[?1003l"
	MouseModeDisable1006 = "\x1b[?1006l"
	MouseModeDisable1015 = "\x1b[?1015l"
)

Terminal mode escape sequences

View Source
const (
	// DoubleEscapeDelay is the max time between Escape presses for double-escape exit.
	// Single Escape is delayed by this amount to detect double-press.
	DoubleEscapeDelay = 150 * time.Millisecond
)

Interactive mode timing constants

View Source
const HistoryLimit = 10000

HistoryLimit is the minimum scrollback retained for sidecar-managed panes.

Variables

View Source
var (

	// partialMouseSeqRegex matches SGR mouse sequences that lost their ESC prefix
	// due to split-read timing in terminal input.
	PartialMouseSeqRegex = regexp.MustCompile(`^(\[<\d+;\d+;\d+[Mm])+$`)
)

Regexes for cleaning terminal output

Functions

func CalculatePollingInterval

func CalculatePollingInterval(lastActivityTime time.Time) time.Duration

CalculatePollingInterval determines the appropriate polling interval based on the time since the last user activity.

func CapturePaneOutput

func CapturePaneOutput(target string, scrollback int) (string, error)

CapturePaneOutput captures the current output of a tmux pane. Uses capture-pane with -p flag to print to stdout and -e to preserve ANSI escape sequences (colors, styles). The scrollback parameter controls how many lines of history to capture.

func ContainsMouseSequence

func ContainsMouseSequence(s string) bool

ContainsMouseSequence checks if input looks like it contains SGR mouse data (td-e2ce50). More lenient than PartialMouseSeqRegex - catches truncated/split sequences. Used to filter spurious key events during fast scrolling.

func CursorStyle

func CursorStyle() lipgloss.Style

CursorStyle returns the cursor style using current theme colors. Uses bold reverse video with a bright background for maximum visibility. The bright cyan/white combination stands out against most terminal backgrounds including Claude Code's diff highlighting and colored output.

func DetectBracketedPasteMode

func DetectBracketedPasteMode(output string) bool

DetectBracketedPasteMode checks captured output to determine if the app has enabled bracketed paste mode. Looks for the most recent occurrence of either the enable (ESC[?2004h) or disable (ESC[?2004l) sequence.

func DetectMouseReportingMode

func DetectMouseReportingMode(output string) bool

DetectMouseReportingMode checks captured output to determine if the app has enabled mouse reporting. Looks for the most recent occurrence of enable vs disable sequences across all mouse mode types.

func EditorAvailable added in v0.88.0

func EditorAvailable() bool

EditorAvailable reports whether tmux can host an embedded editor.

func ExtractUnknownCSIBytes

func ExtractUnknownCSIBytes(msg interface{}) []byte

ExtractUnknownCSIBytes extracts an unparsed CSI sequence from Bubble Tea's current ultraviolet event types. The reflection fallback preserves compatibility with Bubble Tea v1's unexported []byte message.

func IsPasteInput

func IsPasteInput(msg tea.KeyPressMsg) bool

IsPasteInput detects if a key message is actually a paste operation.

In bubbletea v2, true bracketed pastes arrive as a separate tea.PasteMsg (handled in Update), so this heuristic only catches terminals that deliver multi-rune text as a single KeyPressMsg without bracketed paste. It returns true if the typed text contains newlines or is suspiciously long for typing.

func IsSessionDeadError

func IsSessionDeadError(err error) bool

IsSessionDeadError checks if an error indicates the tmux session/pane is gone.

func LooksLikeMouseFragment

func LooksLikeMouseFragment(s string) bool

LooksLikeMouseFragment checks if input could be a fragment of an SGR mouse sequence (td-e2ce50). This is even more lenient than ContainsMouseSequence - catches very short fragments like "[<" or "M[<" that occur when terminal splits mouse events across reads. Used to suppress snap-back and key forwarding during fast scrolling.

func MapKeyToTmux

func MapKeyToTmux(msg tea.KeyPressMsg) (key string, useLiteral bool)

MapKeyToTmux translates a Bubble Tea key message to a tmux send-keys argument. Returns the tmux key name and whether to use literal mode (-l). For modified keys and special keys, returns the tmux key name. For literal characters, returns the character with useLiteral=true.

func NewSession added in v0.88.0

func NewSession(args ...string) error

NewSession creates a tmux session only after the server-wide history default is known to be configured. The mutex keeps every sidecar new-session path ordered behind preparation and makes a failed preparation retryable.

func NormalizeEditorName added in v0.88.0

func NormalizeEditorName(editor string) string

NormalizeEditorName maps common aliases to their editor family.

func NormalizeToCSIu

func NormalizeToCSIu(raw []byte) string

NormalizeToCSIu converts an unknown CSI sequence to CSI u format for forwarding to tmux. It handles:

CSI u:             ESC [ keycode ; modifier u  → passed through
modifyOtherKeys:   ESC [ 27 ; modifier ; keycode ~  → converted to CSI u

Returns the CSI u formatted string, or empty string if unrecognized.

func PasteClipboardToTmuxCmd

func PasteClipboardToTmuxCmd(scope MessageScope, sessionName string, bracketed bool) tea.Cmd

PasteClipboardToTmuxCmd returns a tea.Cmd that pastes clipboard content to a tmux session. The bracketed parameter determines whether to use bracketed paste mode. Returns a PasteResultMsg with the result.

func PrepareServer added in v0.88.0

func PrepareServer() error

PrepareServer configures tmux before any sidecar session is created. Raising the global default before new-session is the only behavior that works on older tmux releases where history-limit changes do not affect existing panes. Existing user settings above the sidecar minimum are preserved.

func QueryCursorPositionSync

func QueryCursorPositionSync(target string) (row, col, paneHeight, paneWidth int, visible, ok bool)

QueryCursorPositionSync synchronously queries cursor position for the given target. Used to capture cursor position atomically with output in poll goroutines. Returns row, col (0-indexed), paneHeight, paneWidth, visible, and ok (false if query failed). paneHeight is needed to calculate cursor offset when display height differs from pane height.

func QueryPaneSize

func QueryPaneSize(target string) (width, height int, ok bool)

QueryPaneSize queries the current size of a tmux pane.

func RenderCursorLine added in v0.88.0

func RenderCursorLine(line string, cursorCol int, visible bool) string

RenderCursorLine overlays the cursor on one terminal line. Keeping the line-level primitive separate lets viewport renderers avoid splitting and joining the complete rendered buffer a second time.

func RenderWithCursor

func RenderWithCursor(content string, cursorRow, cursorCol int, visible bool) string

RenderWithCursor overlays the cursor on content at the specified position. cursorRow is relative to the visible content (0 = first visible line). cursorCol is the column within the line (0-indexed). Preserves ANSI escape codes in surrounding content while rendering cursor.

func ResizeTmuxPane

func ResizeTmuxPane(paneID string, width, height int)

ResizeTmuxPane resizes a tmux window/pane to the specified dimensions. resize-window works for detached sessions; resize-pane is a fallback.

func ResolveEditor added in v0.88.0

func ResolveEditor() string

ResolveEditor returns the configured editor, preserving the established EDITOR > VISUAL > vim precedence.

func SendBracketedPasteToTmux

func SendBracketedPasteToTmux(sessionName, text string) error

SendBracketedPasteToTmux sends text wrapped in bracketed paste sequences. Used when the target app has enabled bracketed paste mode.

func SendKeyToTmux

func SendKeyToTmux(sessionName, key string) error

SendKeyToTmux sends a key to a tmux pane using send-keys. Uses the tmux key name syntax (e.g., "Enter", "C-c", "Up").

func SendKeys added in v0.88.0

func SendKeys(sessionName string, keys ...KeySpec) error

SendKeys sends keys to tmux synchronously and preserves their order.

func SendKeysCmd

func SendKeysCmd(scope MessageScope, sessionName string, keys ...KeySpec) tea.Cmd

SendKeysCmd sends keys to tmux asynchronously.

The batch is queued at call time (see send_queue.go) so keystrokes reach tmux in the order Update handled them, not the order Bubble Tea happens to schedule their goroutines in. Call this from Update, not from inside another tea.Cmd. Returns SessionDeadMsg if the session has ended.

func SendKeysOrdered added in v0.88.0

func SendKeysOrdered(target string, keys ...KeySpec) <-chan error

SendKeysOrdered queues a keystroke batch for a tmux target. The batch is delivered atomically with respect to other queued work for the same target.

func SendLiteralToTmux

func SendLiteralToTmux(sessionName, text string) error

SendLiteralToTmux sends literal text to a tmux pane using send-keys -l. This prevents tmux from interpreting special key names.

func SendOrdered added in v0.88.0

func SendOrdered(target string, run func() error) <-chan error

SendOrdered queues work for a tmux target and returns a channel that receives its result. Jobs for the same target run one at a time, in call order.

Call this from the Update loop, not from inside a tea.Cmd — the ordering guarantee is only as good as the ordering of the calls.

func SendPasteInput added in v0.88.0

func SendPasteInput(sessionName, text string, bracketed bool) error

SendPasteInput forwards paste text using the target applications current bracketed-paste mode.

func SendPasteInputCmd

func SendPasteInputCmd(scope MessageScope, sessionName, text string, bracketed bool) tea.Cmd

SendPasteInputCmd sends paste text to tmux asynchronously. Used for multi-character terminal input (not clipboard paste which is already async).

func SendPasteToTmux

func SendPasteToTmux(sessionName, text string) error

SendPasteToTmux pastes multi-line text via tmux buffer. Uses load-buffer + paste-buffer which works regardless of app paste mode state.

func SendSGRMouse

func SendSGRMouse(sessionName string, button, col, row int, release bool) error

SendSGRMouse sends an SGR mouse event to a tmux pane. button is the mouse button (0=left, 1=middle, 2=right). col and row are 1-indexed coordinates. release indicates if this is a button release event.

func SendSGRWheel added in v0.88.2

func SendSGRWheel(sessionName string, up bool, col, row, notches int) error

SendSGRWheel sends `notches` wheel reports to a tmux pane. col and row are 1-indexed. A wheel notch has no release event, so only the press form is emitted — sending a release would look like a stray button-4/5 release to the application.

The reports go out as one send-keys: the pane sees the same byte stream either way, and a flick would otherwise spawn one tmux process per notch.

func SetWindowSizeManual

func SetWindowSizeManual(sessionName string)

SetWindowSizeManual sets the tmux window-size option to "manual" for a session. This prevents tmux from auto-constraining window size based on attached clients, allowing resize-window commands to stick reliably.

func WaitForPendingSends added in v0.88.0

func WaitForPendingSends()

WaitForPendingSends blocks until every queued send has run.

Enqueueing happens where the key is handled, so the tmux call escapes the caller's goroutine and can land arbitrarily later — after a test has restored PATH, for instance, or while a different test owns the fake tmux. Tests that assert on what was spawned use this to draw a hard line around themselves.

Types

type CaptureRange added in v0.88.0

type CaptureRange struct {
	Output      string
	HistorySize int
	StartLine   int
	EndLine     int
}

CaptureRange is a bounded tmux history capture with absolute pane coordinates. StartLine and EndLine describe Output as a half-open range.

func CapturePaneRange added in v0.88.0

func CapturePaneRange(target string, start, end int) (CaptureRange, error)

CapturePaneRange captures the inclusive tmux range [start, end]. Negative coordinates address history above the visible pane, as in capture-pane.

type CaptureResultMsg

type CaptureResultMsg struct {
	Scope          MessageScope
	PollGeneration int
	Target         string // Pane or session this capture is for
	Output         string // Captured output (empty on error)
	Err            error  // Non-nil if capture failed

	// Cursor state captured atomically with output
	CursorRow     int
	CursorCol     int
	CursorVisible bool
	PaneHeight    int
	PaneWidth     int
}

CaptureResultMsg delivers async tmux capture results. Used to avoid blocking the UI thread on tmux subprocess calls.

type Config

type Config struct {
	// ExitKey is the keybinding to exit interactive mode (default: "ctrl+\\").
	ExitKey string

	// AttachKey is the keybinding to attach to the full tmux session (default: "ctrl+]").
	AttachKey string

	// CopyKey is the keybinding to copy selection (default: "alt+c").
	CopyKey string

	// PasteKey is the keybinding to paste clipboard (default: "alt+v").
	PasteKey string

	// ScrollbackLines is the number of scrollback lines to capture (default: 600).
	ScrollbackLines int
}

Config holds configuration options for a tty Model.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default configuration.

type ControlManager added in v0.88.0

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

ControlManager owns a small pool of control clients keyed by tmux session. tmux control clients are attached to exactly one session, so pooling by pane alone would silently miss notifications from Sidecar's other sessions.

func NewControlManager added in v0.88.0

func NewControlManager() *ControlManager

func (*ControlManager) SetAppFocused added in v0.88.0

func (m *ControlManager) SetAppFocused(focused bool)

func (*ControlManager) Stop added in v0.88.0

func (m *ControlManager) Stop()

func (*ControlManager) Subscribe added in v0.88.0

func (m *ControlManager) Subscribe(request ControlRequest) (*ControlSubscription, error)

type ControlRequest added in v0.88.0

type ControlRequest struct {
	Session    string
	Pane       string
	Width      int
	Height     int
	Scrollback int
	Visible    bool
	Focused    bool
	OnSnapshot func(ControlSnapshot)
	OnFallback func(error)
}

ControlRequest describes one active/visible terminal consumer. Consumers retain their existing polling path and resume it from OnFallback whenever control mode cannot start or its client dies.

type ControlSnapshot added in v0.88.0

type ControlSnapshot struct {
	Session       string
	Pane          string
	Output        string
	HistorySize   int
	CaptureBase   int
	HasHistory    bool
	CursorRow     int
	CursorCol     int
	CursorVisible bool
	PaneHeight    int
	PaneWidth     int
	Generation    uint64

	// MouseReporting mirrors tmux's #{mouse_any_flag}: the app running in the
	// pane has enabled at least one mouse tracking mode. It is asked of tmux
	// rather than scanned out of the capture because `capture-pane -e` emits
	// rendering escapes only — DECSET mode sequences never survive it.
	MouseReporting bool
}

ControlSnapshot is an authoritative rendered screen captured in-band over a tmux control connection after an output or layout notification.

type ControlSubscription added in v0.88.0

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

ControlSubscription is a handle to one manager subscription.

func (*ControlSubscription) Close added in v0.88.0

func (s *ControlSubscription) Close()

func (*ControlSubscription) Resize added in v0.88.0

func (s *ControlSubscription) Resize(width, height int)

func (*ControlSubscription) SetFocused added in v0.88.0

func (s *ControlSubscription) SetFocused(focused bool)

func (*ControlSubscription) SetVisible added in v0.88.0

func (s *ControlSubscription) SetVisible(visible bool)

func (*ControlSubscription) UsingControl added in v0.88.0

func (s *ControlSubscription) UsingControl() bool

type EditorSession added in v0.88.0

type EditorSession struct {
	Name   string
	Editor string
}

EditorSession owns the tmux-specific lifecycle and editor conventions shared by inline editor consumers. Domain state (files, tabs, notes, persistence) remains with the calling plugin.

func StartEditorSession added in v0.88.0

func StartEditorSession(opts EditorSessionOptions) (EditorSession, error)

StartEditorSession creates a detached tmux editor with consistent TERM, dimensions, and history setup.

func (EditorSession) CursorToEnd added in v0.88.0

func (s EditorSession) CursorToEnd() bool

CursorToEnd positions supported editors at the end of their buffer.

func (EditorSession) IsAlive added in v0.88.0

func (s EditorSession) IsAlive() bool

IsAlive reports whether the session still exists.

func (EditorSession) Kill added in v0.88.0

func (s EditorSession) Kill()

Kill terminates the session. A missing/already-dead session is harmless.

func (EditorSession) KillCmd added in v0.88.0

func (s EditorSession) KillCmd() tea.Cmd

KillCmd defers session cleanup to Bubble Tea's command runner.

func (EditorSession) MouseCmd added in v0.88.0

func (s EditorSession) MouseCmd(scope MessageScope, button, col, row int, release bool) tea.Cmd

MouseCmd forwards one SGR mouse event and reports a dead session through the owning tty model's scope.

func (EditorSession) SaveAndQuit added in v0.88.0

func (s EditorSession) SaveAndQuit() bool

SaveAndQuit sends the editor-specific save-and-exit sequence. It reports whether the editor is known, independently of command delivery success.

type EditorSessionOptions added in v0.88.0

type EditorSessionOptions struct {
	NamePrefix  string
	Editor      string
	Path        string
	Line        int // zero-indexed; values <= 0 omit the editor line argument
	Width       int
	Height      int
	CursorAtEnd bool
}

EditorSessionOptions describes a detached editor session.

type EscapeTimerMsg

type EscapeTimerMsg struct {
	Scope MessageScope
}

EscapeTimerMsg is sent when the escape delay timer fires. If pendingEscape is still true, we forward the single Escape to tmux.

type KeySpec

type KeySpec struct {
	Value   string
	Literal bool
}

KeySpec describes a key to send to tmux with ordering preserved.

type KeyedScheduler added in v0.88.0

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

KeyedScheduler provides one generation/invalidation mechanism for any number of independently polled panes. It is intended for Bubble Tea's single update goroutine; callers namespace keys by pane source.

func (*KeyedScheduler) Current added in v0.88.0

func (s *KeyedScheduler) Current(key string) int

Current returns the current generation token for key.

func (*KeyedScheduler) Invalidate added in v0.88.0

func (s *KeyedScheduler) Invalidate(key string) int

Invalidate advances key's generation and returns the new token.

func (*KeyedScheduler) IsCurrent added in v0.88.0

func (s *KeyedScheduler) IsCurrent(key string, generation int) bool

IsCurrent reports whether generation still owns key's poll chain.

func (*KeyedScheduler) Reset added in v0.88.0

func (s *KeyedScheduler) Reset()

Reset invalidates all outstanding keys without retaining old pane names.

func (*KeyedScheduler) Schedule added in v0.88.0

func (s *KeyedScheduler) Schedule(key string, delay time.Duration, message func(generation int) tea.Msg) tea.Cmd

Schedule supersedes any outstanding work for key and returns a delayed command stamped with the new generation.

type MessageScope added in v0.88.0

type MessageScope struct {
	Owner      uint64
	Target     string
	Generation uint64
}

MessageScope identifies one activation of one Model. Bubble Tea broadcasts messages to every plugin, so terminal messages must be scoped to prevent a capture or session failure from one consumer affecting another.

type Model

type Model struct {
	Config Config
	State  *State

	// Width and Height are set by the containing plugin
	Width  int
	Height int

	// Callbacks for plugin integration
	OnExit   func() tea.Cmd // Called when user exits interactive mode
	OnAttach func() tea.Cmd // Called when user requests full tmux attach
	// contains filtered or unexported fields
}

Model is an embeddable component that provides interactive tmux functionality. Plugins embed this Model and delegate Update/View when interactive mode is active.

func New

func New(config *Config) *Model

New creates a new tty Model with the given configuration. If config is nil, DefaultConfig() is used.

func (*Model) Cursor added in v0.88.0

func (m *Model) Cursor() *tea.Cursor

Cursor returns the native cursor position relative to View().

func (*Model) Enter

func (m *Model) Enter(sessionName, paneID string) tea.Cmd

Enter enters interactive mode for the specified tmux session/pane. Returns a tea.Cmd to start polling for output.

func (*Model) Exit

func (m *Model) Exit()

Exit exits interactive mode.

func (*Model) GetTarget

func (m *Model) GetTarget() string

GetTarget returns the current tmux target (pane ID or session name).

func (*Model) IsActive

func (m *Model) IsActive() bool

IsActive returns whether interactive mode is currently active.

func (*Model) PreferredMouseMode added in v0.88.0

func (m *Model) PreferredMouseMode() tea.MouseMode

PreferredMouseMode reports the mode suitable for an active embedded terminal. Containers still own coordinate translation and mouse forwarding.

func (*Model) ResizeAndPollImmediate

func (m *Model) ResizeAndPollImmediate(width, height int) tea.Cmd

ResizeAndPollImmediate updates dimensions and triggers an immediate resize and poll. Unlike SetDimensions, this bypasses debouncing for use with WindowSizeMsg. The resize and poll are batched so the view updates immediately after resize.

func (*Model) Scope added in v0.88.0

func (m *Model) Scope() MessageScope

Scope returns the identity of the current Model activation. Commands created for this model should include this scope in their result messages.

func (*Model) SetDimensions

func (m *Model) SetDimensions(width, height int) tea.Cmd

SetDimensions updates the view dimensions for resize handling.

func (*Model) Update

func (m *Model) Update(msg tea.Msg) tea.Cmd

Update handles messages in interactive mode. Returns the updated model and any commands to execute. Plugins should call this when they receive messages and interactive mode is active.

func (*Model) View

func (m *Model) View() string

View renders the interactive terminal content. Cursor ownership is exposed separately through Cursor so the containing plugin can place Bubble Tea's native cursor after applying its pane offset. Plugins should call this to render the terminal when interactive mode is active.

type OutputBuffer

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

OutputBuffer is a thread-safe bounded buffer for terminal output. Uses maphash for efficient content change detection to avoid duplicate processing.

func NewOutputBuffer

func NewOutputBuffer(capacity int) *OutputBuffer

NewOutputBuffer creates a new output buffer with the given capacity.

func (*OutputBuffer) AbsoluteRange added in v0.88.0

func (b *OutputBuffer) AbsoluteRange() (start, end int, ok bool)

AbsoluteRange reports the half-open absolute line range represented by the buffer. ok is false until the buffer has received an absolute snapshot.

func (*OutputBuffer) Clear

func (b *OutputBuffer) Clear()

Clear removes all lines from the buffer.

func (*OutputBuffer) LastNonEmptyLine added in v0.88.0

func (b *OutputBuffer) LastNonEmptyLine() int

LastNonEmptyLine returns the index of the last line containing printable content, or -1 when every line is empty. It scans under the buffer lock and avoids copying the full scrollback into the render path.

func (*OutputBuffer) Len

func (b *OutputBuffer) Len() int

Len returns the number of lines in the buffer.

func (*OutputBuffer) LineCount

func (b *OutputBuffer) LineCount() int

LineCount returns the number of lines without copying.

func (*OutputBuffer) Lines

func (b *OutputBuffer) Lines() []string

Lines returns a copy of all lines in the buffer.

func (*OutputBuffer) LinesAbsoluteRange added in v0.88.0

func (b *OutputBuffer) LinesAbsoluteRange(start, end int) []string

LinesAbsoluteRange returns a copy of absolute lines in [start, end).

func (*OutputBuffer) LinesRange

func (b *OutputBuffer) LinesRange(start, end int) []string

LinesRange returns a copy of lines in the specified range [start, end). This is more efficient than Lines() when only a portion is needed.

func (*OutputBuffer) PrependSnapshot added in v0.88.0

func (b *OutputBuffer) PrependSnapshot(content string, baseLine int) bool

PrependSnapshot merges an older bounded capture into an absolute buffer. The ranges must overlap or touch; a gap is rejected because inventing blank terminal rows would make selection and search coordinates incorrect.

func (*OutputBuffer) String

func (b *OutputBuffer) String() string

String returns the buffer contents as a single string.

func (*OutputBuffer) Update

func (b *OutputBuffer) Update(content string) bool

Update replaces buffer content if it has changed (detected via hash). Returns true if content was updated, false if content was unchanged.

func (*OutputBuffer) UpdateSnapshot added in v0.88.0

func (b *OutputBuffer) UpdateSnapshot(content string, baseLine int) bool

UpdateSnapshot merges a live capture whose first line has the supplied absolute pane coordinate. Older lines loaded with PrependSnapshot are retained while the overlapping live tail is replaced.

func (*OutputBuffer) WouldChange added in v0.88.0

func (b *OutputBuffer) WouldChange(content string) bool

WouldChange reports whether content differs from the last raw update without mutating the buffer. Async capture commands use this to do status work off the UI goroutine while deferring the actual update until ownership is checked.

func (*OutputBuffer) WouldChangeSnapshot added in v0.88.0

func (b *OutputBuffer) WouldChangeSnapshot(content string, baseLine int) bool

WouldChangeSnapshot reports whether an absolute live capture differs from the last one without mutating the buffer.

func (*OutputBuffer) Write

func (b *OutputBuffer) Write(content string)

Write replaces content in the buffer (for backward compatibility). Prefer Update() for change detection.

type PaneResizedMsg

type PaneResizedMsg struct {
	Scope MessageScope
}

PaneResizedMsg is sent when a pane resize operation completes. Triggers a fresh poll so captured content reflects the new width/wrapping.

type PasteResultMsg

type PasteResultMsg struct {
	Scope       MessageScope
	Err         error // Non-nil if paste failed
	Empty       bool  // True if clipboard was empty
	SessionDead bool  // True if session died during paste
}

PasteResultMsg is sent after a paste operation completes.

type PollTickMsg

type PollTickMsg struct {
	Scope      MessageScope
	Target     string // Which pane/session to poll
	Generation int    // For invalidating stale polls
}

PollTickMsg is sent to trigger a poll for output updates.

type SessionDeadMsg

type SessionDeadMsg struct {
	Scope MessageScope
}

SessionDeadMsg indicates the tmux session has ended. Sent when send-keys or capture fails with a session/pane not found error.

type State

type State struct {
	// Active indicates whether interactive mode is currently active.
	Active bool

	// TargetPane is the tmux pane ID (e.g., "%12") receiving input.
	TargetPane string

	// TargetSession is the tmux session name for the active pane.
	TargetSession string

	// LastKeyTime tracks when the last key was sent for polling decay.
	LastKeyTime time.Time

	// Escape handling state
	EscapePressed      bool
	EscapeTime         time.Time
	EscapeTimerPending bool

	// LastMouseEventTime tracks when the last tea.MouseMsg was received,
	// used to suppress split-CSI "[" that leaks from mouse sequences.
	LastMouseEventTime time.Time

	// Cursor state (updated asynchronously via CaptureResultMsg)
	CursorRow     int
	CursorCol     int
	CursorVisible bool
	PaneHeight    int
	PaneWidth     int

	// Terminal mode state (updated from captured output)
	BracketedPasteEnabled bool
	MouseReportingEnabled bool

	// Visible buffer range for selection mapping
	VisibleStart     int
	VisibleEnd       int
	ContentRowOffset int

	// Resize debouncing
	LastResizeAt time.Time

	// Output buffer
	OutputBuf *OutputBuffer

	// Poll generation for invalidating stale polls
	PollGeneration int
}

State tracks the interactive mode state for a tmux session.

Jump to

Keyboard shortcuts

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