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
- Variables
- func AbsoluteLine(buf *OutputBuffer, lineIdx int) int
- func AppendStatus(hint string, notes []StatusNote, budget int, style func(string) string) string
- func AutoScrollHoldExpired(ticks int) bool
- func BufferAbsolute(buf *OutputBuffer) bool
- func BufferBase(buf *OutputBuffer) (base, total int)
- func CalculatePollingInterval(lastActivityTime time.Time) time.Duration
- func CapturePaneOutput(target string, scrollback int) (string, error)
- func ClaimGeometryLease(target string)
- func ColAt(g Geometry, buf *OutputBuffer, x, lineIdx int) (int, bool)
- func ContainsMouseSequence(s string) bool
- func ContentWidth(surfaceWidth int) int
- func CursorStyle() lipgloss.Style
- func DetectBracketedPasteMode(output string) bool
- func DirectEditorArgv(editor string, line int, path string) []string
- func EdgeScrollDelta(g Geometry, y, limit int) int
- func EdgeScrollRows(outputRow, rows, limit int) int
- func EditorArgv(editor string, line int, path string) ([]string, bool)
- func EditorAvailable() bool
- func ExtractUnknownCSIBytes(msg interface{}) []byte
- func HoldGeometryLease(target string)
- func IsPasteInput(msg tea.KeyPressMsg) bool
- func IsScrollbackKey(state ScrollbackState, msg tea.KeyPressMsg) bool
- func IsSessionDeadError(err error) bool
- func IsTerminalMessage(msg tea.Msg) bool
- func LeaveLiveWindow(freeze *WindowFreeze, offset, maxOffset int) int
- func LineIndexAt(g Geometry, buf *OutputBuffer, y int) (int, bool)
- func LineTextAt(buf *OutputBuffer, lineIdx int) (string, bool)
- func LooksLikeMouseFragment(s string) bool
- func MapKeyToTmux(msg tea.KeyPressMsg) (key string, useLiteral bool)
- func NewSession(args ...string) error
- func NormalizeEditorName(editor string) string
- func NormalizeToCSIu(raw []byte) string
- func NoteUserInput()
- func OutputRowAt(g Geometry, y int) int
- func PaneCoordsAt(v Viewport, relX, relY, paneWidth, paneHeight int) (col, row int, ok bool)
- func PaneSizeIndicator(paneWidth, paneHeight, shownWidth, shownHeight int) string
- func PasteClipboardToTmuxCmd(scope MessageScope, sessionName string) tea.Cmd
- func PlaceCursor(x, y int) *tea.Cursor
- func PrepareServer() error
- func PressLeavesTerminal(region string, terminalRegions ...string) bool
- func PressesTerminal(action mouse.ActionType) bool
- func QueryPaneSize(target string) (width, height int, ok bool)
- func ReleaseGeometryHold(target string)
- func ReleaseGeometryLeases()
- func RenderCursorLine(line string, cursorCol int, visible bool) string
- func RenderWithCursor(content string, cursorRow, cursorCol int, visible bool) string
- func ResetScreenCompare()
- func ResizeTmuxPane(paneID string, width, height int)
- func ResizeWait(last, now time.Time) time.Duration
- func ResizeWaitFor(last, now time.Time, debounce time.Duration) time.Duration
- func ResolveEditor() string
- func SGRMouseFragmentState(s string) (possible, complete bool)
- func ScreenCompareEnabled() bool
- func ScrollKeepsSelection(buf *OutputBuffer) bool
- func ScrollWindow(freeze *WindowFreeze, offset, delta, maxOffset int) int
- func ScrollWindowRows(freeze *WindowFreeze, offset, rows, maxOffset int) int
- func SelectAllSpan(buf *OutputBuffer, tabWidth int) (ui.SelectionPoint, ui.SelectionPoint, bool)
- func SelectedLines(buf *OutputBuffer, sel *ui.SelectionState, tabWidth int) []string
- func SendKeyToTmux(sessionName, key string) error
- func SendKeys(sessionName string, keys ...KeySpec) error
- func SendKeysCmd(scope MessageScope, sessionName string, keys ...KeySpec) tea.Cmd
- func SendKeysOrdered(target string, keys ...KeySpec) <-chan error
- func SendLiteralToTmux(sessionName, text string) error
- func SendOrdered(target string, run func() error) <-chan error
- func SendPasteInput(sessionName, text string) error
- func SendPasteInputCmd(scope MessageScope, sessionName, text string) tea.Cmd
- func SendPasteToTmux(sessionName, text string) error
- func SendSGRMouse(sessionName string, button, col, row int, release bool) error
- func SendSGRWheel(sessionName string, up bool, col, row, notches int) error
- func SetAppFocused(focused bool)
- func SetSessionEnv(sessionName, key, value string) error
- func SetWindowSizeManual(sessionName string)
- func ShouldOverlayCursor(interactive, cursorVisible, atLiveEdge bool) bool
- func ShouldSnapBack(msg tea.KeyPressMsg, sinceScroll time.Duration) bool
- func ThawOffset(layout Viewport) int
- func ThawOffsetFrom(start, maxOffset int) int
- func TouchGeometryLease(target string)
- func TrimsTrailingRows(interactive bool) bool
- func UnitSpanAt(unit SelectionUnit, line string, lineIdx, col, tabWidth int) (ui.SelectionPoint, ui.SelectionPoint, bool)
- func UseRealControlTransport() (restore func())
- func ViewportCursor(v Viewport, in ViewportInput) (x, y int, ok bool)
- func WaitForPendingSends()
- func WheelNotches(delta int) int
- func WheelStaysWithPointer(live bool) bool
- func WindowAnchor(freeze *WindowFreeze, offset int) int
- func WindowBound(in ViewportInput) int
- func WordSpanAt(line string, col int) (int, int, bool)
- type AutoScrollTarget
- type CaptureInput
- type CaptureRange
- type CaptureResultMsg
- type Cell
- type ClickIntent
- type ClickResolution
- type Config
- func (c Config) CopySelectionCmd(lines []string, wrap func(CopyNotice) tea.Msg) tea.Cmd
- func (c Config) CopySelectionNotice(lines []string) CopyNotice
- func (c Config) IsCopyChord(msg tea.KeyPressMsg) bool
- func (c Config) IsPasteChord(msg tea.KeyPressMsg) bool
- func (c Config) IsSelectAllChord(msg tea.KeyPressMsg) bool
- func (c Config) Notice(r CopyResult) CopyNotice
- func (c Config) ResolveSurfaceChord(msg tea.KeyPressMsg, chords SurfaceChords) (tea.Cmd, bool)
- type ControlManager
- type ControlRequest
- type ControlSnapshot
- type ControlSubscription
- type CopyNotice
- type CopyResult
- type EditorSession
- type EditorSessionOptions
- type EscapeTimerMsg
- type ExitAction
- type Geometry
- type HistoryInfo
- type HistoryOutcome
- type HistoryRange
- type HistoryReach
- func (r *HistoryReach) Accept(generation uint64) (scrollLines int, ok bool)
- func (r *HistoryReach) Cancel()
- func (r *HistoryReach) NoteEnd() bool
- func (r *HistoryReach) Record(historySize int)
- func (r *HistoryReach) Remainder(scrollLines, added int) (int, bool)
- func (r *HistoryReach) Request(base int, absolute bool, scrollLines int) (HistoryRange, HistoryOutcome)
- func (r *HistoryReach) RequestAll(base int, absolute bool) (HistoryRange, bool)
- func (r *HistoryReach) Settle(newBase, historySize int)
- type Hooks
- type KeyGate
- type KeyGateInput
- type KeySpec
- type KeyedScheduler
- func (s *KeyedScheduler) Current(key string) int
- func (s *KeyedScheduler) Invalidate(key string) int
- func (s *KeyedScheduler) IsCurrent(key string, generation int) bool
- func (s *KeyedScheduler) Reset()
- func (s *KeyedScheduler) Schedule(key string, delay time.Duration, message func(generation int) tea.Msg) tea.Cmd
- type LeaseDecision
- type LeaseObservation
- type LeasePolicy
- type MessageScope
- type Model
- func (m *Model) Buffer() *OutputBuffer
- func (m *Model) CancelDeferredResize()
- func (m *Model) Close()
- func (m *Model) Cursor() *tea.Cursor
- func (m *Model) CursorState() (row, col int, visible bool)
- func (m *Model) Enter(sessionName, paneID string) tea.Cmd
- func (m *Model) Exit()
- func (m *Model) GetTarget() string
- func (m *Model) History() HistoryInfo
- func (m *Model) IsActive() bool
- func (m *Model) LastMouseActivity() time.Time
- func (m *Model) LinesAbsoluteRange(start, end int) []string
- func (m *Model) NoteInput()
- func (m *Model) NoteMouseActivity()
- func (m *Model) Open(target Target) tea.Cmd
- func (m *Model) PaneCoords(col, row int) (int, int, bool)
- func (m *Model) PaneMouseReporting() bool
- func (m *Model) PaneSize() (width, height int)
- func (m *Model) PreferredMouseMode() tea.MouseMode
- func (m *Model) PrependHistory(content string, baseLine int) bool
- func (m *Model) ReleaseInput()
- func (m *Model) Resize(width, height int) tea.Cmd
- func (m *Model) ResizeAndPollImmediate(width, height int) tea.Cmd
- func (m *Model) Scope() MessageScope
- func (m *Model) SendClick(col, row int) tea.Cmd
- func (m *Model) SendUnknownSequence(msg tea.Msg) tea.Cmd
- func (m *Model) SendWheelNotches(up bool, col, row, notches int) tea.Cmd
- func (m *Model) SetDimensions(width, height int) tea.Cmd
- func (m *Model) SetFocused(focused bool)
- func (m *Model) SetHooks(h Hooks)
- func (m *Model) SetResizeDebounce(d time.Duration)
- func (m *Model) SetResizeHold(hold bool)
- func (m *Model) SetVisible(visible bool) tea.Cmd
- func (m *Model) SizeIndicator() string
- func (m *Model) Update(msg tea.Msg) tea.Cmd
- func (m *Model) View() string
- type ModelFrame
- type ModelInvalidation
- type MouseFragment
- type OutputBuffer
- func (b *OutputBuffer) AbsoluteRange() (start, end int, ok bool)
- func (b *OutputBuffer) ApplySnapshot(s PaneSnapshot) bool
- func (b *OutputBuffer) Clear()
- func (b *OutputBuffer) LastNonEmptyLine() int
- func (b *OutputBuffer) Len() int
- func (b *OutputBuffer) LineCount() int
- func (b *OutputBuffer) Lines() []string
- func (b *OutputBuffer) LinesAbsoluteRange(start, end int) []string
- func (b *OutputBuffer) LinesRange(start, end int) []string
- func (b *OutputBuffer) PaneWindow() (lineCount, paneTop int, ok bool)
- func (b *OutputBuffer) PrependSnapshot(content string, baseLine int) bool
- func (b *OutputBuffer) Revision() uint64
- func (b *OutputBuffer) String() string
- func (b *OutputBuffer) Update(content string) bool
- func (b *OutputBuffer) UpdateSnapshot(content string, baseLine int) bool
- func (b *OutputBuffer) WouldChange(content string) bool
- func (b *OutputBuffer) WouldChangeSnapshot(content string, baseLine int) bool
- func (b *OutputBuffer) Write(content string)
- type PaneFit
- type PaneFitInput
- type PaneResizedMsg
- type PaneSnapshot
- type PaneState
- type PasteResultMsg
- type Pointer
- func (pt *Pointer) Abandon()
- func (pt *Pointer) AdoptSurface(sel *ui.SelectionState, r mouse.Rect)
- func (pt *Pointer) AdvanceAutoScroll(generation uint64, target AutoScrollTarget) bool
- func (pt *Pointer) AnchorFrom(g Geometry, buf *OutputBuffer, sel *ui.SelectionState, originX, originY int, ...) bool
- func (pt *Pointer) Arm(resolution ClickResolution, x, y int)
- func (pt *Pointer) Begin()
- func (pt *Pointer) BeginAutoScrollTick(generation uint64) bool
- func (pt *Pointer) ConsumeAutoScrollTick() bool
- func (pt *Pointer) DragPoint() (int, int)
- func (pt *Pointer) DragTo(g Geometry, buf *OutputBuffer, sel *ui.SelectionState, x, y int) bool
- func (pt *Pointer) ExtendTo(g Geometry, buf *OutputBuffer, sel *ui.SelectionState, cell Cell)
- func (pt *Pointer) ExtendToUnit(g Geometry, buf *OutputBuffer, sel *ui.SelectionState, cell Cell) bool
- func (pt *Pointer) Generation() uint64
- func (pt *Pointer) NoteDragMotion(x, y int)
- func (pt *Pointer) Press(g Geometry, buf *OutputBuffer, sel *ui.SelectionState, ev PressEvent)
- func (pt *Pointer) PressPoint() (int, int)
- func (pt *Pointer) Rect() mouse.Rect
- func (pt *Pointer) Release(sel *ui.SelectionState) (ClickResolution, bool)
- func (pt *Pointer) ResetUnit()
- func (pt *Pointer) ScheduleAutoScroll(tick func(generation uint64) tea.Msg) tea.Cmd
- func (pt *Pointer) SelectUnitAt(g Geometry, buf *OutputBuffer, sel *ui.SelectionState, x, y int, ...) bool
- func (pt *Pointer) Unit() SelectionUnit
- type PointerIntent
- type PointerIntentInput
- type PollTickMsg
- type PressEvent
- type ResyncReason
- type ScreenCompareSample
- type ScreenCompareSnapshot
- type ScreenCompareStats
- type ScrollbackMove
- type ScrollbackState
- type SelectionUnit
- type SessionDeadMsg
- type State
- type StatusNote
- type SurfaceChords
- type Target
- type Viewport
- type ViewportInput
- type WheelBurst
- type WheelBursts
- type WheelGesture
- type WheelHandler
- type WheelInput
- type WheelRoute
- type WindowFreeze
- func (f *WindowFreeze) Active() bool
- func (f *WindowFreeze) Freeze(start int)
- func (f *WindowFreeze) Rebase(added int)
- func (f *WindowFreeze) Release()
- func (f *WindowFreeze) Scroll(delta, maxOffset int)
- func (f *WindowFreeze) Start() int
- func (f *WindowFreeze) Thaw(layout Viewport) (offset int, ok bool)
- func (f *WindowFreeze) ThawFrom(maxOffset int) (offset int, ok bool)
- type WindowPlacement
- type WindowStatusInput
Constants ¶
const ( AutoScrollInterval = 70 * time.Millisecond AutoScrollStep = 5 // A release lost off-window is only noticed when the pointer comes back, so // an unbounded chain would keep dragging the selection through all of // scrollback (and onto the clipboard under copy-on-select) in the meantime. // Roughly 1.5s of holding still without any fresh motion pauses the chain; // real motion re-arms it, so a user genuinely parked at the edge only has to // twitch to keep going. AutoScrollMaxRun = 20 )
A held pointer past an edge keeps scrolling on a timer, the way every real terminal does; motion events alone stop arriving the moment the hand stops.
const ( // HistoryChunkLines is how much older history one bound-hit reads. It bounds // a single capture, not the reach: repeated hits walk back a chunk at a time // until tmux's history is exhausted. HistoryChunkLines = 600 // HistoryBufferLines is how many lines of a pane a surface's buffer holds. // It is sized to tmux's retained history rather than to the seed capture, // because a buffer sized to the seed would trim every line the reach loaded // and leave the surface dead-ended at its initial window. HistoryBufferLines = HistoryLimit + 512 // HistoryExhaustedNotice is what a surface says when a reach lands on tmux's // oldest line. Every host says it in these words: the reader is being told // about the pane, not about the surface they happen to be reading it in. HistoryExhaustedNotice = "This is the beginning of this pane's history" )
const ( EscapeFragmentWindow = 5 * time.Millisecond MouseFragmentWindow = 10 * time.Millisecond )
A split SGR mouse report can reach a host as ordinary key text. Two windows tell the difference between that and real typing: the escape that opened the report was delivered microseconds before its continuation, and any successfully parsed mouse event comes from the same burst of terminal output as the leak.
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
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.
const ( // EnterInteractiveKey is the primary alternate to enter/double-click. EnterInteractiveKey = "i" // EnterInteractiveKeyAlt is what the hints advertise. EnterInteractiveKeyAlt = "E" )
The ways in to a live pane from the surface around it. Both hosts answer both chords for the same act, and the command palette and the preview hint name them, so they are literals in one place rather than one per surface.
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 )
Terminal mode escape sequences
const ( // WheelDebounceInterval is the base coalescing window (~60fps). WheelDebounceInterval = 16 * time.Millisecond // WheelBurstDebounce replaces it once a flick is under way (~30fps): a burst // is filtered harder, because its events arrive faster than any surface can // usefully draw them. WheelBurstDebounce = 12 * time.Millisecond // WheelBurstThreshold is the number of events in a row that makes a flick. WheelBurstThreshold = 3 // WheelBurstTimeout is how long after the last event a flick is still // running. It has to outlast the trailing garbage a split SGR report leaves // behind, and it bounds how long anything keyed to the flick is deferred. WheelBurstTimeout = 500 * time.Millisecond )
Wheel burst tuning (td-3b15ee). A trackpad delivers a flick as a long run of tiny events, and each one that reaches a surface is a repaint — and, when the application owns the wheel, a separate send. Coalescing them keeps a flick travelling the same distance on every surface instead of as far as each surface happens to be able to keep up with.
const CopyNoticeDuration = 2 * time.Second
CopyNoticeDuration is how long a copy notice stays up: long enough to read a line count, short enough not to sit over the output it describes.
const DefaultResizeDebounce = 300 * time.Millisecond
DefaultResizeDebounce is the shared interval when a host does not pass one. Workspace's plugins.workspace.resizeDebounceMs default matches this.
const DefaultScrollbackLines = 600
DefaultScrollbackLines is the number of scrollback lines captured from a pane when no explicit scrollback is requested. The live capture stays small; older ranges are fetched lazily as the user scrolls past the loaded boundary.
const DefaultTabWidth = 8
DefaultTabWidth is the tab stop every terminal surface expands against.
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
const DragScrollStep = 3
DragScrollStep bounds how far one motion event past an edge walks the window through scrollback. Unbounded, a pointer flicked to the top of the screen would skip hundreds of lines the user never saw.
const HistoryLimit = 10000
HistoryLimit is the minimum scrollback retained for sidecar-managed panes.
const LiveEdgeKey = "⇧End"
LiveEdgeKey is the chord that puts a scrolled-back window back on the live edge while a pane is live. It is named in the status because a window off the live edge is showing history, and a user who cannot see how to get back reads that as a pane that stopped producing output.
const MaxWheelNotchesPerFlush = 10
MaxWheelNotchesPerFlush caps how many wheel reports one debounced burst can send. A fast trackpad flick can coalesce a large delta, and every notch is a separate `tmux send-keys`; past a point the app has scrolled as far as the gesture meant anyway.
const MouseFragmentTimeout = 50 * time.Millisecond
MouseFragmentTimeout bounds how long a partial report is held. The remainder of a real report arrives in the same burst of terminal output; anything later is someone typing.
const SnapBackCooldown = 100 * time.Millisecond
SnapBackCooldown suppresses snap-back for input arriving right after a scroll. A flick that leaks mouse-report bytes as key text would otherwise throw the viewport back to the live edge in the middle of the gesture.
const SuperCopyKey = "super+c"
SuperCopyKey is the platform copy chord — Cmd+C on macOS, Super+C elsewhere. It copies alongside the configured key rather than replacing it, because it is a platform convention rather than a sidecar binding: the terminal owns the selection, so the emulator's own copy has nothing to act on and passes the chord through to us. Terminals that intercept it first (iTerm2) never deliver it, which is why the configurable chord stays.
Variables ¶
var DefaultLeasePolicy = LeasePolicy{ StaleTicks: 5, StaleAfter: 60 * time.Second, RefreshTicks: 2, RefreshAfter: 5 * time.Second, PreemptIdle: 5 * time.Second, }
DefaultLeasePolicy leaves an owner at least three refreshes of slack at the slowest poll interval in the app (20s) before anyone else treats its lease as abandoned, and hands geometry to whichever machine the user is actually typing on within a few seconds.
var ErrInertControlTransport = errors.New(
"tmux control: inert transport under test; call tty.UseRealControlTransport to opt in")
ErrInertControlTransport is what an inert transport reports. A test that meant to exercise control mode and sees this in a fallback has not found a broken transport — it has found that it never opted in. Callers that care can tell the two apart with errors.Is rather than passing vacuously.
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 AbsoluteLine ¶ added in v0.98.0
func AbsoluteLine(buf *OutputBuffer, lineIdx int) int
AbsoluteLine lifts a window-relative line index into the buffer's absolute coordinates when it keeps any.
func AppendStatus ¶ added in v0.98.0
AppendStatus adds notes to a header's right region, in full where they fit, compactly where only that fits, and stops at the first that fits neither.
Dropping is by width and takes the least important note last, because WindowStatus returns them most important first. A budget of zero or less keeps every note in full, for a host whose header clips from the right instead. style is the host's own dimming, applied here so the width measured is the width drawn.
func AutoScrollHoldExpired ¶ added in v0.98.0
AutoScrollHoldExpired reports when a run of ticks with no fresh drag motion behind it has gone on long enough to be treated as a lost release rather than a pointer deliberately parked past the edge.
func BufferAbsolute ¶ added in v0.98.0
func BufferAbsolute(buf *OutputBuffer) bool
BufferAbsolute reports that a buffer numbers its lines in absolute pane coordinates, which stay put as the pane produces more output.
func BufferBase ¶ added in v0.98.0
func BufferBase(buf *OutputBuffer) (base, total int)
BufferBase is the coordinate space a buffer keeps: the absolute line its first loaded row sits at, and how many lines the space runs to.
It is the one answer a host needs to draw what a gesture recorded. CellAt records selection points through AbsoluteLine, so a viewport told nothing about the base draws every highlight short by exactly it — off screen entirely once a pane has any scrollback. A relative buffer's own indices are already its coordinate space, so its base is zero.
func CalculatePollingInterval ¶
CalculatePollingInterval determines the appropriate polling interval based on the time since the last user activity.
func CapturePaneOutput ¶
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 ClaimGeometryLease ¶ added in v0.92.0
func ClaimGeometryLease(target string)
ClaimGeometryLease takes ownership of target's session for this instance, overriding whatever lease it finds. Reserved for unambiguous local actions — attaching to a session, entering interactive mode — where the user has just proved which machine they are sitting at.
func ColAt ¶ added in v0.98.0
func ColAt(g Geometry, buf *OutputBuffer, x, lineIdx int) (int, bool)
ColAt maps a screen X coordinate to a visual column in the given line. The returned column is in visual space (post-tab-expansion, accounting for multi-width chars). It reports false only for positions left of the content; a line that cannot be read still yields column zero, because a pointer there is over the surface.
func ContainsMouseSequence ¶
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 ContentWidth ¶ added in v0.98.0
ContentWidth is the columns a terminal surface can actually render into: the surface minus the column the scrollbar reserves.
The scrollbar's column is stable viewport chrome — reserved even while all output fits and RenderScrollbar draws only a spacer. Making the reservation depend on the current history length creates a one-frame geometry race: a new frame can make the scrollbar visible before the asynchronous tmux resize has taken effect, clipping the application's final column and reflowing it on the next repaint (td-0818ef). A surface with no room to give one up keeps what it has rather than reporting a width no pane could be sized to.
func CursorStyle ¶
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 ¶
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 DirectEditorArgv ¶ added in v1.0.0
DirectEditorArgv is the no-profile launch of the same editor. It is the fallback a caller runs when the shell route failed to start at all.
func EdgeScrollDelta ¶ added in v0.98.0
EdgeScrollDelta reports how far one step should move the window for a pointer held at y, and zero once the pointer is back inside the content.
func EdgeScrollRows ¶ added in v0.98.0
EdgeScrollRows turns a pointer row that has run past the content into the rows to scroll, negative above the top. Speed scales with the overshoot so a pointer parked just past the edge crawls while one thrown to the window edge moves quickly, bounded so no single step skips a screenful.
func EditorArgv ¶ added in v1.0.0
EditorArgv returns the argv that opens path in editor, at a one-based line when line > 0. The second result reports whether the user's shell profile is in the picture; when it is false the argv is a direct exec of the editor, which is also the fallback whenever no usable login shell can be identified.
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 HoldGeometryLease ¶ added in v0.92.0
func HoldGeometryLease(target string)
HoldGeometryLease claims target and keeps its lease refreshed from outside the event loop, for actions that suspend the TUI for their whole duration — attaching to a session. Pair every call with ReleaseGeometryHold on the way back; a crash in between is safe, since the refresher dies with the process and the lease then goes stale like any other.
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 IsScrollbackKey ¶ added in v0.98.0
func IsScrollbackKey(state ScrollbackState, msg tea.KeyPressMsg) bool
IsScrollbackKey reports that a key press asks for a scrollback move in this state. It is the half of MapScrollbackKey that needs no page size, so a host resolves its layout only for the keys this claims rather than on every keystroke it types into a pane.
func IsSessionDeadError ¶
IsSessionDeadError checks if an error indicates the tmux session/pane is gone.
The list this used to carry omitted the one message tmux actually prints when a whole session is gone — "can't find session: NAME" — so a shell the user exited kept its embedded terminal polling a target that would never answer, and the mode never ended (td-6a4100). The vocabulary now lives with the rest of the tmux-evidence rules in internal/shellliveness, and it deliberately still refuses server-wide failures like "no server running": those say nothing about one session.
func IsTerminalMessage ¶ added in v0.98.0
IsTerminalMessage reports whether msg is one of the messages an embedded Model's own commands produce. Every one of them carries a MessageScope, so a host may hand each of them to more than one Model: the activation that owns the scope acts on it and the others ignore it.
It exists because a host that is not a plugin — the global Workspaces browser is routed by message type rather than broadcast — cannot otherwise recognise the control-plane messages, which are deliberately unexported.
func LeaveLiveWindow ¶ added in v0.98.0
func LeaveLiveWindow(freeze *WindowFreeze, offset, maxOffset int) int
LeaveLiveWindow is where a window is left when a pane stops being live, and the answer is: exactly where the reader put it.
The two hosts used to disagree — the project surface snapped to the live edge while the global preview kept the offset — which was drift from their two window models rather than a decision (td-2e3738). Keeping the reader's window is the deliberate choice: the rows on screen when the mode ends are the ones the reader was reading, the buffer behind them is not replaced by leaving, and a bottom-relative offset stays meaningful as new output arrives, so nothing is gained by yanking the view to the bottom of a pane the user just scrolled back through. A pin is thawed rather than kept, because the gesture holding it is over: the window resumes following output from where it stands.
func LineIndexAt ¶ added in v0.98.0
func LineIndexAt(g Geometry, buf *OutputBuffer, y int) (int, bool)
LineIndexAt maps a screen row to the absolute buffer line drawn there, or false when the row is outside the output area.
func LineTextAt ¶ added in v0.98.0
func LineTextAt(buf *OutputBuffer, lineIdx int) (string, bool)
LineTextAt reads one line of a buffer, in whichever coordinate space that buffer keeps.
func LooksLikeMouseFragment ¶
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
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
NormalizeEditorName maps common aliases to their editor family.
func NormalizeToCSIu ¶
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 NoteUserInput ¶ added in v0.92.0
func NoteUserInput()
NoteUserInput records keyboard or mouse input on this instance. Focus reports only what one machine's window server believes, and the machine the user walked away from never hears about it — so recent input, compared as a duration between machines, is what actually decides who owns geometry.
func OutputRowAt ¶ added in v0.98.0
OutputRowAt converts a screen row to a 0-indexed output row of the surface. The result is deliberately unbounded: a click needs to reject rows outside the output area, while a drag clamps them.
func PaneCoordsAt ¶ added in v0.98.0
PaneCoordsAt maps a position inside a drawn viewport, relative to its first content cell, to the 1-indexed pane coordinates tmux's mouse protocol expects.
Horizontal placement comes from the fit — a pane wider than the viewport is drawn scrolled — while vertical placement comes from the buffer window, because the viewport scrolls history as well as the live grid.
func PaneSizeIndicator ¶ added in v0.92.0
PaneSizeIndicator describes a clipped pane as "200x50, showing 120x40". It returns "" when nothing is hidden, so callers can append it unconditionally.
func PasteClipboardToTmuxCmd ¶
func PasteClipboardToTmuxCmd(scope MessageScope, sessionName string) tea.Cmd
PasteClipboardToTmuxCmd returns a tea.Cmd that pastes clipboard content to a tmux session. Whether the paste is bracketed is tmux's call, not the caller's. Returns a PasteResultMsg with the result.
func PlaceCursor ¶ added in v0.98.0
PlaceCursor is the terminal cursor every embedded surface draws: a blinking block at the origin's cell. Shape and blink are the terminal's own, not each host's, so a pane looks the same wherever it is embedded.
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 PressLeavesTerminal ¶ added in v0.98.0
PressLeavesTerminal reports that a press landed away from every region that draws a terminal, which ends both the pointer gesture such a surface armed and the interactive mode it was armed in.
Which regions draw a terminal is the host's to name; the verdict is not. Ending only the gesture leaves a live pane holding the keyboard behind whatever the press started — a divider drag, a row selection — and ending only the mode fires the armed click under a selection the user has moved away from.
func PressesTerminal ¶ added in v0.98.0
func PressesTerminal(action mouse.ActionType) bool
PressesTerminal reports the actions that put a button down, which is where a press away from a terminal is decided.
func QueryPaneSize ¶
QueryPaneSize queries the current size of a tmux pane.
func ReleaseGeometryHold ¶ added in v0.92.0
func ReleaseGeometryHold(target string)
ReleaseGeometryHold ends the background refresh started by HoldGeometryLease. The lease stays with this instance; it just goes back to being refreshed by the geometry loop.
func ReleaseGeometryLeases ¶ added in v0.92.0
func ReleaseGeometryLeases()
ReleaseGeometryLeases gives up every lease this instance holds. Call it on the way out of the process.
func RenderCursorLine ¶ added in v0.88.0
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 ¶
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 ResetScreenCompare ¶ added in v0.94.0
func ResetScreenCompare()
ResetScreenCompare clears the counters. Tests use it; production never does.
func ResizeTmuxPane ¶
ResizeTmuxPane resizes a tmux window/pane to the specified dimensions. resize-window works for detached sessions; resize-pane is a fallback.
The geometry ownership lease is enforced here rather than at the dozen call sites (td-ee222a): callers stay dumb, and an instance that does not own the session simply renders the geometry it finds. See geometry_lease.go.
func ResizeWait ¶ added in v0.98.0
ResizeWait is how long a host must hold off asserting geometry, given when it last did, using DefaultResizeDebounce. Zero means assert now. Every surface that resizes a pane asks here: a second literal budget beside this one is how two surfaces come to answer the same layout change at different rates.
Waiting is not dropping. A caller that gets a positive wait still owes the pane the newest geometry and must schedule exactly one deferred assertion for it — one, however many sizes arrive inside the window, or a burst becomes a chain of resizes spaced a debounce apart, which is what the budget exists to prevent.
func ResizeWaitFor ¶ added in v1.0.0
ResizeWaitFor is ResizeWait with a caller-supplied interval. A debounce of 0 or less means assert now — that is the escape hatch, not "unset".
func ResolveEditor ¶ added in v0.88.0
func ResolveEditor() string
ResolveEditor returns the configured editor, preserving the established EDITOR > VISUAL > vim precedence.
func SGRMouseFragmentState ¶ added in v0.98.0
SGRMouseFragmentState recognizes a complete SGR mouse report or any prefix that can become one. The grammar is ESC? "[" "<" digits ";" digits ";" digits ("M"|"m").
func ScreenCompareEnabled ¶ added in v0.94.0
func ScreenCompareEnabled() bool
ScreenCompareEnabled reports whether shadow comparison is on for this process.
func ScrollKeepsSelection ¶ added in v0.98.0
func ScrollKeepsSelection(buf *OutputBuffer) bool
ScrollKeepsSelection reports whether a selection survives a scroll made outside a pointer gesture — a wheel notch, a shift-scrollback key.
A selection in absolute coordinates names the same rows wherever the window moves, so scrolling away from it and back must leave it where the user made it. A buffer without them renumbers its lines as it grows, so the same anchor would come to cover rows the user never picked.
func ScrollWindow ¶ added in v0.98.0
func ScrollWindow(freeze *WindowFreeze, offset, delta, maxOffset int) int
ScrollWindow moves a window delta rows back through scrollback — negative towards the live edge — and reports the offset it lands on. A window a gesture is holding is moved in the coordinate it is pinned in and keeps its offset, which is what lets an edge-autoscroll during a drag walk the rows without handing the window back to the live bottom mid-gesture.
func ScrollWindowRows ¶ added in v0.98.0
func ScrollWindowRows(freeze *WindowFreeze, offset, rows, maxOffset int) int
ScrollWindowRows is ScrollWindow for a caller counting rendered rows down the screen — a wheel notch, an edge autoscroll, a rendered-row drag — rather than rows back through scrollback. The two directions are opposite, and this is the single place they are reconciled: every host used to write that negation into its own call site.
func SelectAllSpan ¶ added in v0.98.0
func SelectAllSpan(buf *OutputBuffer, tabWidth int) (ui.SelectionPoint, ui.SelectionPoint, bool)
SelectAllSpan returns the span covering every line a buffer holds, in whichever coordinate space it keeps.
func SelectedLines ¶ added in v0.98.0
func SelectedLines(buf *OutputBuffer, sel *ui.SelectionState, tabWidth int) []string
SelectedLines is the text a selection covers, clipped to the lines the buffer still holds.
func SendKeyToTmux ¶
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
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
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 ¶
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
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
SendPasteInput forwards paste text to the pane, letting tmux apply the target application's current bracketed-paste mode.
func SendPasteInputCmd ¶
func SendPasteInputCmd(scope MessageScope, sessionName, text string) tea.Cmd
SendPasteInputCmd sends paste text to tmux asynchronously. Used for multi-character terminal input (not clipboard paste which is already async).
func SendPasteToTmux ¶
SendPasteToTmux pastes text into a pane through a uniquely named tmux buffer.
tmux, not Sidecar, decides whether the paste is bracketed: `paste-buffer -p` emits the bracketed-paste control codes only when the pane's application has actually requested that mode. That state is not exposed as a tmux format and cannot be reconstructed from a capture, so any bracketing Sidecar did itself would be a guess. `-d` drops the buffer once it has been pasted, and `-t` names the pane explicitly.
`-r` is deliberately NOT passed, although the plan for this work specified it. It disables tmux's default LF→CR translation, and a raw-mode program that has not requested bracketed paste reads CR — not LF — as "submit this line". With `-r` a multi-line paste into such a program (measured: the pane received `41 0a 42` instead of `41 0d 42`) stops submitting its lines. Line-ending behavior therefore stays exactly as it has always been; `-p` is the part that actually matters. Pinned in both directions by TestSendPasteToTmuxBracketedAndPlain.
func SendSGRMouse ¶
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
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 SetAppFocused ¶ added in v0.92.0
func SetAppFocused(focused bool)
SetAppFocused tells geometry arbitration whether the user is looking at this sidecar instance. ControlManager.SetAppFocused forwards here, so every resize path — including the filebrowser and notes inline editors, which have no focus plumbing of their own — observes the same bit.
func SetSessionEnv ¶ added in v0.96.0
SetSessionEnv sets one variable in a tmux session's environment. Panes already running keep the value they started with, so this is a cue for anything opened later, never the authority on a session's identity.
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 ShouldOverlayCursor ¶ added in v0.98.0
ShouldOverlayCursor reports whether a surface may draw the pane's cursor. A window scrolled off the live edge is showing history, and a cursor painted over history sits on a row the pane is not writing to.
func ShouldSnapBack ¶ added in v0.98.0
func ShouldSnapBack(msg tea.KeyPressMsg, sinceScroll time.Duration) bool
ShouldSnapBack reports whether a key press is real typing, which a scrolled-back viewport owes a jump to the live edge: keystrokes that land under a window parked in history are invisible as they are typed.
sinceScroll is how long ago the surface last scrolled.
func ThawOffset ¶ added in v0.98.0
ThawOffset places a frozen window back against the live bottom without moving the rows on screen: start is where the window was pinned, and the result is the same rows expressed as a distance back from the live edge, so the window follows new output again from exactly where the gesture left it.
func ThawOffsetFrom ¶ added in v0.98.0
ThawOffsetFrom is ThawOffset for a surface that holds the frozen start itself rather than in the layout it rendered.
func TouchGeometryLease ¶ added in v0.92.0
func TouchGeometryLease(target string)
TouchGeometryLease advances the lease for target without asserting geometry.
The lease is refreshed by the work it guards, and callers skip ResizeTmuxPane once a pane already matches — so an owner that has settled on the right size stops refreshing and eventually looks abandoned to everyone else. Every geometry loop therefore ticks the lease on the passes where it decides not to resize; polling the pane at all is what makes this instance the one driving its geometry, not the resize call that occasionally follows.
func TrimsTrailingRows ¶ added in v0.98.0
TrimsTrailingRows reports whether a surface's window ends at the last line with text on it rather than at the end of the buffer.
A window that is not mirroring a live grid is a scrollback window, and tmux's trailing blank rows are padding rather than content there. A live grid's blank rows are the application's own — full-screen programs draw chrome against them — so they stay addressable, which is why FitViewport exempts any buffer with a known live grid from this answer regardless of where its window currently sits. A host must not add a second condition of its own: the two surfaces would then answer a scrolled-back pane differently.
What this costs a watched pane the user has scrolled back on: nothing that moves the rows. A scrollback window is placed by an explicit Start (or by a distance back from the live bottom), so trimming changes EffectiveCount, MaxOffset and where the window may stop — never which buffer line lands on which screen row at a given offset. The visible effect is that the window cannot be scrolled into blank padding below the last row there is anything to see on, which is the behaviour every surface wants of a history window. A live grid gets that for free from its own bound: no window sits below the live edge, so its trailing rows are exactly as reachable as they are now.
func UnitSpanAt ¶ added in v0.98.0
func UnitSpanAt(unit SelectionUnit, line string, lineIdx, col, tabWidth int) (ui.SelectionPoint, ui.SelectionPoint, bool)
UnitSpanAt returns the inclusive visual span of the unit covering col in line. Character gestures have no span to snap to.
func UseRealControlTransport ¶ added in v1.0.3
func UseRealControlTransport() (restore func())
UseRealControlTransport restores the real tmux control transport for tests that genuinely exercise it — the live-terminal tests that drive a real pane through the seed-and-stream path and assert against tmux's own answers.
Those tests must already have isolated tmux (see internal/testenv), because this is the switch that lets a test spawn real `tmux -C attach-session` children. It is deliberately explicit: opting in is a statement that the test owns a private server and will let its panes be torn down with it.
func ViewportCursor ¶ added in v0.98.0
func ViewportCursor(v Viewport, in ViewportInput) (x, y int, ok bool)
ViewportCursor is where the pane's cursor lands inside a drawn viewport, and false when it is scrolled out of the drawn window. A rendered row maps back through PaneTop, so the drawn cursor and the pane row tmux reports for a click on it can never disagree (td-d29821).
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.
func WheelNotches ¶ added in v0.98.0
WheelNotches converts a scroll delta in lines back into whole wheel notches, never rounding a real scroll down to nothing.
A delta is a line count — one notch expands into mouse.WheelScrollLines — but the pane wants notches, and the app applies its own lines-per-notch on top. Forwarding the line count makes every notch scroll that many times too far.
func WheelStaysWithPointer ¶ added in v0.98.0
WheelStaysWithPointer reports that a wheel notch over a host's chrome must be delivered to the live pane under the pointer rather than placed by whichever region the notch landed in.
Placing a notch by region while a pane is live lets one that drifted off the pane reach the list beside it, where moving the cursor rebinds the preview and ends the mode — so a stray trackpad notch would silently drop the user out of the pane they are typing in.
func WindowAnchor ¶ added in v0.98.0
func WindowAnchor(freeze *WindowFreeze, offset int) int
WindowAnchor is where the window sits in whichever coordinate it is currently placed by. Callers use it to tell whether a scroll moved anything, which is the only question that can be asked across both coordinates.
func WindowBound ¶ added in v0.98.0
func WindowBound(in ViewportInput) int
WindowBound is the furthest back a surface's window can be placed, in rows back from its live edge. It is the one derivation every host asks — the global preview, the project's primary surface and its terminal panel — so that a bound and the window it bounds can never come from two different measurements of the same surface.
It is measured off the drawn layout rather than off a line count, because the drawn window is what a reader can actually reach: a pane letterboxed into a taller viewport, or one whose trailing rows are trimmed, stops somewhere a count does not know about. Taking it off the live edge is deliberate — that is the only state a bound is asked about, and it is where offset 0 sits.
Types ¶
type AutoScrollTarget ¶ added in v0.98.0
type AutoScrollTarget struct {
Geometry func() Geometry
Buffer func() *OutputBuffer
Selection *ui.SelectionState
// Scroll moves the window by delta rendered rows, positive downwards, and
// reports whether it actually moved. A window already against the end of the
// buffer ends the chain instead of ticking forever.
Scroll func(delta int) bool
}
AutoScrollTarget is the surface a held-pointer edge scroll walks. The host supplies the window as callbacks because the scroll moves it: everything after the step has to be read again.
type CaptureInput ¶ added in v0.94.0
type CaptureInput struct {
// Output is the capture text and BaseLine its first row's absolute line
// number, meaningful only when Absolute is set.
Output string
BaseLine int
Absolute bool
// PaneHeight is the pane's grid height at the instant of the capture. Zero
// means no geometry was observed, and no split is published.
PaneHeight int
// RowsJoined says the capture was taken with tmux's -J, which collapses each
// wrapped line into a single row. Such a capture has no row-for-row
// correspondence with the grid, so no split can be stated for it.
RowsJoined bool
}
CaptureInput is one capture-pane rendering plus the geometry observed with it, as handed to CaptureSnapshot.
type CaptureRange ¶ added in v0.88.0
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
// MouseReporting is tmux's #{mouse_any_flag}, read with the capture. It
// travels with the poll because it is the polling path's only source for it:
// the capture's own bytes never carry the DECSET sequences that turn
// tracking on, so who owns a click would otherwise mean one thing under
// control mode and another under the fallback.
MouseReporting bool
}
CaptureResultMsg delivers async tmux capture results. Used to avoid blocking the UI thread on tmux subprocess calls.
type Cell ¶ added in v0.98.0
Cell is a position in a captured terminal buffer: a line index in whichever coordinate space that buffer keeps, and a visual column after tab expansion.
func CellAt ¶ added in v0.98.0
func CellAt(g Geometry, buf *OutputBuffer, x, y int) (Cell, bool)
CellAt maps screen coordinates to a buffer cell, refusing positions outside the output area: a click on the header or on padding is not a click on text.
func ClampedCellAt ¶ added in v0.98.0
func ClampedCellAt(g Geometry, buf *OutputBuffer, x, y int) (Cell, bool)
ClampedCellAt maps a pointer position onto the nearest visible cell instead of refusing positions outside the output area. A held pointer routinely leaves the pane mid-gesture — below the last row, left of the content, out over the sidebar — and a selection that stops tracking there reads as broken.
type ClickIntent ¶ added in v0.98.0
type ClickIntent struct {
// Live reports that the surface is already forwarding keys to its pane.
Live bool
// MouseReporting reports that the application running in the pane has asked
// for mouse events.
MouseReporting bool
// Modified is a shift- or alt-click, which is a selection gesture on every
// terminal surface and never an activation.
Modified bool
// LinkClaimed reports that something with a stronger claim on the click — a
// validated link — has already taken it.
LinkClaimed bool
}
ClickIntent is everything a host knows about a mouse-down over a terminal surface at the moment it has to say what a release without motion will mean. It is deliberately not "where the keyboard is": focus follows the press rather than gating it, or a click from elsewhere into a passive terminal would need a second click to do what one click does anywhere else in the surface.
type ClickResolution ¶ added in v0.98.0
type ClickResolution uint8
ClickResolution is what a mouse-down over a terminal surface will mean if the gesture ends without motion. The two outcomes are mutually exclusive for one gesture — "activate and forward" is not a state — and every abort path (lost release, double-click, a click elsewhere) drops whichever one is pending.
const ( ClickNone ClickResolution = iota // ClickActivate makes a passive terminal live. ClickActivate // ClickForward hands the click to the app running in a live terminal that // has asked for mouse reports. ClickForward )
func ResolveClick ¶ added in v0.98.0
func ResolveClick(in ClickIntent) ClickResolution
ResolveClick decides what a release without motion means: make a passive terminal live, hand the click to the application running in a live one, or nothing at all.
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
// SelectAllKey is the keybinding to select every line of output
// (default: "ctrl+a"). The empty-copy notice names it, so a surface that
// hard-codes the chord can tell the user to press a key it no longer binds.
SelectAllKey string
// CopyOnSelect copies a finished selection without a copy chord, the way
// xterm does.
CopyOnSelect bool
// ScrollbackLines is the number of scrollback lines to capture
// (default: DefaultScrollbackLines).
ScrollbackLines int
}
Config holds configuration options for a tty Model.
func (Config) CopySelectionCmd ¶ added in v0.98.0
CopySelectionCmd copies selected terminal lines and reports the outcome as the host's own notification. wrap is the only part of a copy a surface owns: which toast type carries the notice. A host that phrased the notice itself would be a second wording of the same three outcomes.
func (Config) CopySelectionNotice ¶ added in v0.98.0
func (c Config) CopySelectionNotice(lines []string) CopyNotice
CopySelectionNotice copies selected terminal lines and phrases the outcome, so a host needs only its own notification type to report a copy.
func (Config) IsCopyChord ¶ added in v0.98.0
func (c Config) IsCopyChord(msg tea.KeyPressMsg) bool
IsCopyChord reports whether a key press asks to copy the terminal selection: the configured copy key, or the platform copy chord.
func (Config) IsPasteChord ¶ added in v0.98.0
func (c Config) IsPasteChord(msg tea.KeyPressMsg) bool
IsPasteChord reports whether a key press asks to paste into the terminal.
func (Config) IsSelectAllChord ¶ added in v0.98.0
func (c Config) IsSelectAllChord(msg tea.KeyPressMsg) bool
IsSelectAllChord reports whether a key press asks to select every line of output.
func (Config) Notice ¶ added in v0.98.0
func (c Config) Notice(r CopyResult) CopyNotice
Notice phrases a copy result. It is the Config's because the empty case names the select-all chord, and a notice naming a key the surface does not bind is worse than none.
func (Config) ResolveSurfaceChord ¶ added in v0.98.0
func (c Config) ResolveSurfaceChord(msg tea.KeyPressMsg, chords SurfaceChords) (tea.Cmd, bool)
ResolveSurfaceChord answers a key on behalf of the surface, in one order everywhere: the two chords that act on the selection first, then scrollback. The order is stated rather than incidental — the sets do not overlap today, and a host that reordered them would be deciding that for every host.
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)
// ModelPresentation permits a live byte-fed model to suppress capture for
// ordinary output bursts. It is separate from OnModelFrame because the
// diagnostic comparison oracle deliberately retains independent captures.
ModelPresentation bool
// OnModelFrame receives permanent model-backed presentation frames. Command
// response callbacks, including capture recovery callbacks, run on the
// client's single
// ordered actor, which is what makes the seed cut exact. A consequence: an
// OnSnapshot callback that blocks now backpressures the reader, so a slow
// consumer can make tmux pause the pane or discard bytes for this client,
// which was not possible before. No Sidecar consumer blocks in OnSnapshot,
// but a future one must not.
//
// A frame is published only after a seed transaction and its post-seed
// replay have both completed. Until then — and forever, in this slice —
// capture/polling ownership is unchanged.
OnModelFrame func(ModelFrame)
// OnModelInvalid reports that the pane model needs a fresh seed or has
// stopped. It never implies anything about the capture path.
OnModelInvalid func(ModelInvalidation)
}
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
// HistoryRows and PaneRows split Output into the scrolled-off rows above the
// pane and the pane's own grid. They are counted while the capture is still
// a line slice: once Output is joined, a blank final pane row is
// indistinguishable from a trailing terminator, and a consumer that
// re-derives the split loses that row and places the cursor one row too high
// (td-d29821).
HistoryRows int
PaneRows 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
// PaneTitle and CurrentCommand are captured in the same control-mode
// metadata response as the screen. Semantic agent probes must never reuse
// identity from an older ordinary poll while that polling path is suspended.
PaneTitle string
CurrentCommand string
}
ControlSnapshot is a rendered screen captured in-band over a tmux control connection. It supplies bootstrap/recovery presentation and independent semantic or diagnostic evidence 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 CopyNotice ¶ added in v0.98.0
CopyNotice is what the user is told about a copy. Every terminal surface says the same three things — a copy needs a selection, a failure names its error, a success counts its lines — so the wording lives here and each host only wraps it in whatever its own notification type is.
type CopyResult ¶ added in v0.98.0
type CopyResult struct {
Lines int
Err error
// Empty reports a copy asked for with nothing selected. A copy chord with no
// selection must not replace the clipboard with a screen dump — cmd+c is
// reflex, and the clipboard may hold something the user still needs.
Empty bool
}
CopyResult is the outcome of a copy: how many lines reached the clipboard, and why none did. Hosts phrase their own notification from it.
func CopySelection ¶ added in v0.98.0
func CopySelection(lines []string) CopyResult
CopySelection writes selected terminal lines to the system clipboard, without the styling they were drawn with.
type EditorSession ¶ added in v0.88.0
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 ExitAction ¶ added in v0.98.0
type ExitAction uint8
ExitAction separates ending input ownership from closing the terminal.
const ( // ExitClosesTerminal ends the mode and the terminal together. A host that // only shows the pane while the user is typing into it has nothing left to // draw afterwards. ExitClosesTerminal ExitAction = iota // ExitReleasesInput ends input ownership alone: the buffer, its loaded // scrollback and its feed survive. A host that keeps drawing the pane after // the user leaves it requires this — closing here drops the scrollback the // user just read, and the host's next reconciliation reopens the pane with // an empty buffer on the same update, which reads as the output vanishing. ExitReleasesInput )
type Geometry ¶ added in v0.98.0
Geometry places a terminal surface's drawn content on the screen, which is everything hit testing needs to know about it. Content is the absolute rect of the content area, so the first text cell sits at its origin — a host with chrome (a border, a header) subtracts that before building one. Start and End are the buffer lines drawn in it, and ColOffset is the pane column drawn at Content.X when a pane wider than the viewport is clipped.
func GeometryFor ¶ added in v0.98.0
GeometryFor places a drawn window on screen. The origin is the host's — it alone knows where its chrome ends — and everything else is the layout's, so a surface cannot hit-test against a window different from the one it drew.
type HistoryInfo ¶ added in v0.94.0
type HistoryInfo struct {
HistorySize int
CaptureBase int
LoadedStart int
LoadedEnd int
HasHistory bool
}
HistoryInfo is the transport-neutral absolute history state exposed to an embedding viewport. It contains coordinates only; control frames and the screen-model implementation remain private to Model.
type HistoryOutcome ¶ added in v0.99.0
type HistoryOutcome uint8
HistoryOutcome is what came of asking for older history, in the terms a host answers a reader with: a read was opened, one is already running, tmux has nothing older, or nothing here can say yet.
const ( HistoryRequested HistoryOutcome = iota HistoryInFlight HistoryEnded )
type HistoryRange ¶ added in v0.99.0
HistoryRange is one read, in the relative coordinates capture-pane addresses history by, tagged with the generation that admits its result.
type HistoryReach ¶ added in v0.99.0
type HistoryReach struct {
// HistorySize is tmux's own count of the lines above the pane, the origin
// the relative coordinates of a capture are measured from.
HistorySize int
// Loading says a read is in flight; PendingScroll is the movement waiting on
// it, replayed once the rows land.
Loading bool
PendingScroll int
// Exhausted records that the buffer already starts at tmux's oldest line.
Exhausted bool
// RequestGen retires superseded reads: a result carrying any other
// generation belongs to a request that has since been cancelled or replaced.
RequestGen uint64
// NoticeShown records that the reader has already been told this pane has no
// more history, so a wheel held at the bound says it once.
NoticeShown bool
}
HistoryReach is one surface's standing reach into a pane's older history.
func (*HistoryReach) Accept ¶ added in v0.99.0
func (r *HistoryReach) Accept(generation uint64) (scrollLines int, ok bool)
Accept admits a completed read and reports the scroll waiting on it. A result tagged with any other generation belongs to a request this reach superseded, and admitting it would move a window the reader has since placed elsewhere.
func (*HistoryReach) Cancel ¶ added in v0.99.0
func (r *HistoryReach) Cancel()
Cancel drops a pending read and the scroll waiting on it, and retires the generation so a result already in flight cannot land on a window the reader has moved.
func (*HistoryReach) NoteEnd ¶ added in v0.99.0
func (r *HistoryReach) NoteEnd() bool
NoteEnd reports whether the reader still has to be told that tmux has no more history for this pane. It answers true once, so a wheel held at the bound does not repeat itself, and again after a read proves there was more.
func (*HistoryReach) Record ¶ added in v0.99.0
func (r *HistoryReach) Record(historySize int)
Record adopts a pane's own report of how much history it holds.
func (*HistoryReach) Remainder ¶ added in v0.99.0
func (r *HistoryReach) Remainder(scrollLines, added int) (int, bool)
Remainder is what the reader is still owed after a prepend of added rows: a scroll larger than the chunk that arrived walks back another chunk.
func (*HistoryReach) Request ¶ added in v0.99.0
func (r *HistoryReach) Request(base int, absolute bool, scrollLines int) (HistoryRange, HistoryOutcome)
Request opens a read of the chunk immediately older than base, the buffer's first loaded line. scrollLines is what the reader is owed once those rows land; a scroll arriving while a read is in flight is added to it rather than starting a second read of the same range.
func (*HistoryReach) RequestAll ¶ added in v0.99.0
func (r *HistoryReach) RequestAll(base int, absolute bool) (HistoryRange, bool)
RequestAll opens a read of everything above base, superseding any bounded read in flight. Searching is user-initiated and covers the whole of a pane's history, not only the ranges scrolling happened to visit.
func (*HistoryReach) Settle ¶ added in v0.99.0
func (r *HistoryReach) Settle(newBase, historySize int)
Settle records what a completed read left behind: tmux's history size as of the read, and whether the buffer now starts at its oldest line.
type Hooks ¶ added in v0.98.0
type Hooks struct {
OnKey func(tea.KeyPressMsg) (tea.Cmd, bool)
BeforeSend func(tea.KeyPressMsg)
OnExit func() tea.Cmd
OnAttach func() tea.Cmd
OnSessionEnded func() tea.Cmd
ExitAction ExitAction
}
Hooks are the host's answers to everything the component decides for itself: the chords the surface around the pane owns, the moment a key is about to reach it, and the ways the mode can end. They are set together because a host that wires some of them re-implements the rest outside the component, which is how two surfaces embedding the same terminal come to answer the same key differently.
type KeyGate ¶ added in v0.98.0
type KeyGate uint8
KeyGate is what a terminal surface does with a key press before any of it becomes input for the pane.
const ( // KeyGateSend is an ordinary key: send it, preceded by whatever escape the // double-escape window is still holding. KeyGateSend KeyGate = iota // KeyGateDrop is a fragment of an SGR mouse report that the input reader // split across reads and delivered as text. Any held escape belongs to that // report rather than to the keyboard, so it is dropped with the fragment. KeyGateDrop // KeyGateHoldEscape is an escape that must not be forwarded yet: it may be // the first half of the double-escape that leaves interactive mode. KeyGateHoldEscape // KeyGateExitDoubleEscape is the second escape inside that window. KeyGateExitDoubleEscape )
func GateKey ¶ added in v0.98.0
func GateKey(in KeyGateInput) KeyGate
GateKey classifies a key press over a live terminal surface. It decides only what kind of key this is; what a host does about it — how it leaves the mode, how it sends — stays the host's.
With all-motion mouse reporting on, the terminal emits an SGR sequence for every pointer movement, and the input reader can split one across reads:
Read 1: ESC → an escape key press, or consumed internally Read 2: [ → a bare bracket rune, the leak Read 3: <35;10;20M → runes, or a parsed mouse event
The escape window catches the case where the ESC arrived as a key press. When the reader consumed the ESC itself, nothing marks the window, and only the proximity of a real mouse event distinguishes the leak from someone typing a bracket.
type KeyGateInput ¶ added in v0.98.0
type KeyGateInput struct {
Msg tea.KeyPressMsg
// EscapePressed and EscapeAt are the state of the double-escape window.
EscapePressed bool
EscapeAt time.Time
// LastMouseAt is when a mouse event last reached the host, whether or not it
// was routed to this surface.
LastMouseAt time.Time
Now time.Time
}
KeyGateInput is one key press and the two clocks the decision reads.
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.
type LeaseDecision ¶ added in v0.92.0
type LeaseDecision struct {
// Resize reports whether this instance may assert pane geometry.
Resize bool
// Write reports whether it should stamp a fresh token — a claim when the
// lease was free or stale, a refresh when it already held it.
Write bool
// Reason names the rule that fired, for tests and logs.
Reason string
}
LeaseDecision is the verdict for one tick.
func DecideGeometryLease ¶ added in v0.92.0
func DecideGeometryLease(obs LeaseObservation, policy LeasePolicy) LeaseDecision
DecideGeometryLease is the whole arbitration rule, state-free so a headless caller can adopt it unchanged.
type LeaseObservation ¶ added in v0.92.0
type LeaseObservation struct {
// SelfID identifies this sidecar instance. A token belongs to us when it
// carries this ID.
SelfID string
// Token is the raw @sidecar-owner value, empty when the option is unset.
Token string
// Focused reports whether the user is looking at this instance.
Focused bool
// UnchangedTicks is how many of the reader's ticks Token has been identical
// for. Zero on the tick it changed.
UnchangedTicks int
// UnchangedFor is how long Token has been identical in the reader's own
// elapsed time.
UnchangedFor time.Duration
// TicksSinceWrite is how many ticks since this instance last wrote a token.
TicksSinceWrite int
// SinceWrite is how long since this instance last wrote a token, measured on
// its own clock. Zero when it never has.
SinceWrite time.Duration
// SelfIdle is how long since the user last gave this instance input.
SelfIdle time.Duration
// OwnerIdle is what the current token says its writer's idle time was when
// it was written, valid only when OwnerIdleKnown.
OwnerIdle time.Duration
OwnerIdleKnown bool
// OwnerDefunct reports that Token was written by an instance the reader can
// prove is gone — in practice a previous sidecar on this same machine whose
// PID no longer exists. Only ever provable locally; a token from another
// machine is never defunct as far as this reader is concerned.
OwnerDefunct bool
}
LeaseObservation is everything arbitration needs: what this instance is, what the shared option currently says, and how long the reader has watched it.
type LeasePolicy ¶ added in v0.92.0
type LeasePolicy struct {
// StaleTicks is how many consecutive ticks a foreign token may stay
// unchanged before the lease is considered abandoned and claimable.
StaleTicks int
// StaleAfter is the wall-clock floor on the same judgement, for sessions
// whose ticks are sporadic. Zero disables it. It must stay comfortably above
// RefreshAfter *and* above the slowest poll interval any caller ticks on,
// since an owner can only refresh on a tick of its own.
StaleAfter time.Duration
// RefreshTicks is how many ticks the owner lets pass before writing a new
// token, so readers elsewhere keep seeing it change.
RefreshTicks int
// RefreshAfter bounds the same cadence in elapsed time. A tick is a poll,
// and polls run as slowly as 20s, so a tick count alone lets the owner's
// refresh period stretch to a multiple of an arbitrary poll interval — past
// the point where peers polling just as slowly call it abandoned. Zero
// disables the elapsed-time arm.
RefreshAfter time.Duration
// PreemptIdle is how much longer than us the current owner must have gone
// without user input before we take the lease off it. It doubles as the
// window in which our own last input counts as "the user is here". Zero
// disables idle preemption.
PreemptIdle time.Duration
}
LeasePolicy is the budget arbitration runs on. Ticks are the reader's own local ticks; they carry no cross-machine meaning. Durations are elapsed measurements, never timestamps, so they do carry across machines.
type MessageScope ¶ added in v0.88.0
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
// OnSessionEnded is called instead of OnExit when the terminal ends because
// the pane died rather than because the user left it. A host that says
// nothing about that difference shows a mode ending by itself, which reads
// as a dropped keystroke. Nil falls back to OnExit.
OnSessionEnded func() tea.Cmd
// OnKey is the host's first look at a live key press: the chords that act on
// the surface around the pane rather than on the pane itself — its own
// panel toggles, its scrollback, its selection. Returning true stops the key
// before any of it becomes input, and before the double-escape window sees
// it. A host that answers a key here must not also answer it outside the
// component, or the pane receives it twice.
OnKey func(tea.KeyPressMsg) (tea.Cmd, bool)
// BeforeSend runs for a key that is about to reach the pane, and only for
// those: a held escape, a dropped mouse fragment and anything OnKey claimed
// never arrive here. It is where a host pins its viewport to the live edge
// and records that the user is typing.
BeforeSend func(tea.KeyPressMsg)
// ExitAction is what leaving the mode does to the terminal behind it.
ExitAction ExitAction
// 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 ¶
New creates a new tty Model with the given configuration. If config is nil, DefaultConfig() is used.
func (*Model) Buffer ¶ added in v0.98.0
func (m *Model) Buffer() *OutputBuffer
Buffer is the captured output the terminal is drawing, so a host can render its own window over it — scrolled back, with a selection highlighted — instead of only the live tail View draws.
func (*Model) CancelDeferredResize ¶ added in v1.0.0
func (m *Model) CancelDeferredResize()
CancelDeferredResize drops an armed retry and invalidates any in-flight deferredResizeMsg. A leftover tick after this is a no-op.
func (*Model) Close ¶ added in v0.94.0
func (m *Model) Close()
Close releases the current target and rejects all queued deliveries.
func (*Model) Cursor ¶ added in v0.88.0
Cursor returns the native cursor position relative to View().
func (*Model) CursorState ¶ added in v0.98.0
CursorState is the pane's own cursor, in pane coordinates.
func (*Model) Enter ¶
Enter enters interactive mode for the specified tmux session/pane. Returns a tea.Cmd to start polling for output.
func (*Model) History ¶ added in v0.94.0
func (m *Model) History() HistoryInfo
History returns a read-only snapshot of absolute history metadata and the currently loaded half-open range. HasHistory is false for legacy/provisional captures that do not carry trustworthy absolute coordinates.
func (*Model) LastMouseActivity ¶ added in v0.98.0
LastMouseActivity is when a mouse event last reached this terminal. A host that runs the shared key gate itself reads it from here rather than keeping a clock of its own, or the two would disagree about the same bracket.
func (*Model) LinesAbsoluteRange ¶ added in v0.94.0
LinesAbsoluteRange returns loaded terminal rows in [start, end).
func (*Model) NoteInput ¶ added in v0.99.0
func (m *Model) NoteInput()
NoteInput records user input the host is delivering to the pane. The capture cadence decays from this clock, so a pane a reader is scrolling is repainted at the active tier rather than the idle one. A host whose surface can deliver input by any path of its own says so here rather than keeping a second clock.
func (*Model) NoteMouseActivity ¶ added in v0.98.0
func (m *Model) NoteMouseActivity()
NoteMouseActivity records that a mouse event reached this host, which is what the bare-"[" gate in handleKey reads. Hosts that route pointer events themselves must call it, or a split SGR sequence leaks into the pane as a literal bracket.
func (*Model) Open ¶ added in v0.94.0
Open activates the terminal for target. Enter remains as the compatibility spelling for existing embedders.
func (*Model) PaneCoords ¶ added in v0.92.0
PaneCoords maps 1-indexed coordinates within the rendered content area to the 1-indexed pane coordinates tmux's mouse protocol expects. A clipped pane is drawn scrolled, so a click lands ColOffset columns and RowOffset rows in (td-73fa86).
func (*Model) PaneMouseReporting ¶ added in v0.98.0
PaneMouseReporting reports that the application running in the pane has asked for mouse events. It is the whole of "does this notch or click belong to the app or to the surface showing it".
func (*Model) PaneSize ¶ added in v0.98.0
PaneSize is the pane's observed grid, which can differ from the viewport it is drawn in: another client may be driving the same session.
func (*Model) PreferredMouseMode ¶ added in v0.88.0
PreferredMouseMode reports the mode suitable for an active embedded terminal. Containers still own coordinate translation and mouse forwarding.
func (*Model) PrependHistory ¶ added in v0.94.0
PrependHistory merges an older overlapping capture into the loaded absolute buffer. Transport and scheduling remain owned by Model's embedding journey.
func (*Model) ReleaseInput ¶ added in v0.98.0
func (m *Model) ReleaseInput()
ReleaseInput ends the component's ownership of the keyboard for a host that took the mode away from outside — a click landing off every terminal region, a focus change. Every way out must close the double-escape window and drop a half-read mouse report, or a timer scheduled by the last escape still reaches a model the host believes it has left.
func (*Model) ResizeAndPollImmediate ¶
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) SendClick ¶ added in v0.98.0
SendClick forwards a press and release at 1-indexed pane coordinates to the application running in the pane, and polls straight away so the frame it draws in response is not held back by the idle cadence.
func (*Model) SendUnknownSequence ¶ added in v0.98.0
SendUnknownSequence forwards an unparsed CSI sequence — kitty CSI u or modifyOtherKeys, which Bubble Tea does not turn into a KeyPressMsg — to the pane as the key it actually is, so modified keys like shift+enter reach the application running there.
It is a method rather than a case in Update because a host that already forwards these itself would otherwise send each of them twice; the caller decides which of the two paths owns the sequence.
func (*Model) SendWheelNotches ¶ added in v0.98.0
SendWheelNotches forwards whole wheel notches at 1-indexed pane coordinates.
The wheel is the user's most recent input, so it counts as activity: the poll cadence decays to its slow tier on idle time, and a scroll that did not reset it would be repainted at that tier.
func (*Model) SetDimensions ¶
SetDimensions updates the view dimensions for resize handling.
func (*Model) SetFocused ¶ added in v0.94.0
SetFocused updates focus policy for the current target.
func (*Model) SetHooks ¶ added in v0.98.0
SetHooks adopts a host's whole contract with the component. ExitAction is carried with the callbacks rather than defaulted, so a host states what leaving the mode does to the terminal behind it.
func (*Model) SetResizeDebounce ¶ added in v1.0.0
SetResizeDebounce gives this model the host's interval so assertDimensions is not a second clock beside the workspace poll path. 0 means assert now.
func (*Model) SetResizeHold ¶ added in v1.0.0
SetResizeHold is the host's no-SIGWINCH-until-drop flag. Last geometry stays owed; assertDimensions does not ResizeTmuxPane while hold is set unless the configured debounce is 0.
func (*Model) SetVisible ¶ added in v0.94.0
SetVisible controls transport activity without destroying the target.
func (*Model) SizeIndicator ¶ added in v0.92.0
SizeIndicator describes a pane that is larger than the viewport it is drawn into, e.g. "200x50, showing 120x40". It returns "" when the whole pane is visible, so callers can render it unconditionally.
func (*Model) Update ¶
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.
type ModelFrame ¶ added in v0.94.0
type ModelFrame struct {
Session string
Pane string
Generation uint64
// Seeds counts completed seed transactions for this subscription. A frame
// whose Seeds differs from the previous frame's follows a resynchronization.
Seeds int
Frame screenmodel.Frame
// Discarded is the last client_discarded value observed for this control
// client, and DiscardCheckedAt is when it was observed. tmux offers no
// notification for the counter, so it is only known at a seed and on the
// discardProbeInterval cadence: between the last check and now, tmux may have
// dropped bytes for this client and this frame would be built from an
// incomplete stream with nothing in the frame to say so.
//
// These two fields are what makes that window discriminable rather than
// invisible. Any consumer comparing this frame against another source (the
// slice-2 shadow comparison) must treat a mismatch observed later than
// DiscardCheckedAt as unattributable until the next check confirms the
// counter did not move. See §6 of the slice-1 evidence.
Discarded int64
DiscardCheckedAt time.Time
}
ModelFrame is one rendered byte-fed frame for a model-backed subscription. It is delivered only after a seed and its post-seed replay have completed.
type ModelInvalidation ¶ added in v0.94.0
type ModelInvalidation struct {
Session string
Pane string
Generation uint64
Reason ResyncReason
Terminal bool
Err error
}
ModelInvalidation reports that a pane model lost presentation. Terminal invalidations end the model for that subscription; the consumer stays on the existing capture/polling path, which slice 1 never leaves in the first place.
type MouseFragment ¶ added in v0.98.0
type MouseFragment struct {
// contains filtered or unexported fields
}
MouseFragment reassembles an SGR mouse report that the input reader split across reads and delivered as ordinary key text.
GateKey decides one key at a time and can only recognize a fragment that looks like one on its own. This holds the partial report between reads and matches it against the real grammar, which is what tells a genuine "<35;10;20M" leak apart from a user typing "<".
It keeps no clock of its own: every caller passes the same now it gates the rest of the key press with, so a headless driver can replay a split report without waiting for one.
func (*MouseFragment) Consume ¶ added in v0.98.0
Consume reports whether text is part of a split SGR mouse report, retaining it when more of the report is still to come.
escapePressed and escapeAt are the double-escape window: an ESC delivered as its own key press may be the report's first byte rather than the keyboard's.
func (*MouseFragment) Hold ¶ added in v0.98.0
func (f *MouseFragment) Hold(text string, now time.Time)
Hold retains text as the start of a report whose remainder is still to come. It is how a caller hands over a fragment GateKey claimed on its own.
func (*MouseFragment) Pending ¶ added in v0.98.0
func (f *MouseFragment) Pending() string
Pending reports the partial report currently held.
func (*MouseFragment) Reset ¶ added in v0.98.0
func (f *MouseFragment) Reset()
Reset drops any partial report. A surface that stops taking input cannot carry half a report into the next thing the user does.
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) ApplySnapshot ¶ added in v0.94.0
func (b *OutputBuffer) ApplySnapshot(s PaneSnapshot) bool
ApplySnapshot replaces the buffer's live tail with one observed snapshot, recording its pane split in the same critical section as its content.
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) PaneWindow ¶ added in v0.94.0
func (b *OutputBuffer) PaneWindow() (lineCount, paneTop int, ok bool)
PaneWindow reports the buffer's line count together with the index of the line holding pane row 0, both read under one lock. ok is false until a producer has stated the split, which is what a consumer needs in order to fall back to its own geometry rather than trust a stale or invented value.
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) Revision ¶ added in v0.98.0
func (b *OutputBuffer) Revision() uint64
Revision advances only when accepted content changes. Consumers may use it to cache work derived from a captured terminal without tying invalidation to animation or other render-only state.
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.
The content carries no pane split, so the buffer reports none. Producers that know where the live grid starts should call ApplySnapshot instead.
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 PaneFit ¶ added in v0.92.0
type PaneFit struct {
// Width and Height are the display region, never larger than the viewport
// and never larger than the pane.
Width int
Height int
// ColOffset is the first pane column rendered. Non-zero only when the pane
// is wider than the viewport and the cursor sits past the right edge.
ColOffset int
// RowOffset is the first pane row rendered. Non-zero only when the pane is
// taller than the viewport; it anchors the window on the cursor so the row
// being typed into stays on screen, and falls back to the pane's tail when
// there is no cursor to anchor to.
RowOffset int
// ClippedWidth/ClippedHeight report that the pane is larger than the
// viewport on that axis, so part of it is not shown.
ClippedWidth bool
ClippedHeight bool
// LetterboxedWidth/LetterboxedHeight report that the pane is smaller than
// the viewport on that axis, so the pane is padded rather than stretched.
LetterboxedWidth bool
LetterboxedHeight bool
}
PaneFit is the projection of a pane onto a viewport: the region actually drawn, plus the horizontal scroll needed to keep the cursor in view.
func FitPane ¶ added in v0.92.0
func FitPane(in PaneFitInput) PaneFit
FitPane projects a pane of the observed size onto the viewport. It is a pure function so both the workspace viewport and tty.Model share one rule.
func (PaneFit) Letterboxed ¶ added in v0.92.0
Letterboxed reports whether the pane is smaller than the viewport on either axis.
func (PaneFit) PaneCoords ¶ added in v0.92.0
PaneCoords maps a 0-indexed cell of the rendered region to 1-indexed pane coordinates, which is what tmux's mouse protocol speaks. It reports false for a cell outside the rendered region, so hit testing moves with the pixels instead of assuming the viewport and the pane are aligned (td-73fa86).
type PaneFitInput ¶ added in v0.92.0
type PaneFitInput struct {
ViewWidth int
ViewHeight int
PaneWidth int
PaneHeight int
// CursorCol and CursorRow are the pane-relative cursor coordinates used to
// anchor clipping. Ignored unless HasCursor is set.
CursorCol int
CursorRow int
HasCursor bool
}
PaneFitInput describes a tmux pane's real geometry alongside the local viewport it has to be shown in.
Sidecar never owns a tmux session exclusively: the same session can be driven by another sidecar instance on a differently sized terminal, so the pane's actual size routinely disagrees with the size this instance last requested (td-73fa86). Rendering therefore has to derive from the observed size, not the requested one.
PaneWidth/PaneHeight of 0 mean "unknown" — the viewport is used as-is.
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 PaneSnapshot ¶ added in v0.94.0
type PaneSnapshot struct {
// Output is history rows followed by PaneRows live grid rows.
Output string
// BaseLine is the absolute line number of Output's first row. It is
// meaningful only when Absolute is set.
BaseLine int
// Absolute says the snapshot carries trustworthy absolute coordinates, so
// lazily loaded older history can be merged with it.
Absolute bool
// HistoryRows is how many of Output's leading rows sit above pane row 0, and
// PaneRows how many trailing rows are the live grid. PaneRows of 0 means the
// producer does not know the split; the buffer then reports no pane top and
// consumers fall back to their own geometry.
HistoryRows int
PaneRows int
}
PaneSnapshot is one atomically observed screen: history rows followed by the live pane grid, plus the split between them. The producer states the split rather than leaving it to be inferred from the content, because every way of re-deriving it downstream mixes observations taken at different instants and drifts (td-d29821).
PaneRows is also what disambiguates the serialization. Capture-shaped output is row *separated*, so a final blank row and a trailing terminator look identical once split — and the difference is exactly one grid row, the row a cursor sits on at the bottom of a screen.
func CaptureSnapshot ¶ added in v0.94.0
func CaptureSnapshot(in CaptureInput) PaneSnapshot
CaptureSnapshot describes a capture-pane rendering: PaneHeight grid rows preceded by whatever history the capture carried. It is a plain function over the capture and the geometry observed with it, so every capture-shaped producer — control snapshots, poll fallbacks, the workspace's own pollers — states the split the same way.
The invariant it rests on is that the capture's rows and the pane's rows correspond one for one, which is what makes "the last PaneHeight rows are the grid" true. A -J capture breaks it — wrapped lines arrive collapsed, so the capture has fewer rows than the grid and both halves of the split would be wrong — and RowsJoined is how a producer says so. It publishes no split rather than an authoritative wrong one; consumers then fall back to their own geometry, which is where they were before the split was carried at all.
A degenerate capture that carries fewer rows than the pane is tall has no usable split either; it is reported as all-pane, which puts pane row 0 at the top of the buffer, matching what such a capture actually shows.
type PaneState ¶ added in v0.98.0
type PaneState struct {
CursorRow int
CursorCol int
PaneHeight int
PaneWidth int
CursorVisible bool
// MouseReporting is tmux's #{mouse_any_flag}. It is read here rather than
// scanned out of the capture because `capture-pane -e` emits rendering
// escapes only: the DECSET sequences that turn tracking on never reach it,
// so detection over a capture answers false for every mouse-aware app.
MouseReporting bool
}
PaneState is what one display-message reads about a pane beside its output: where the cursor is, how big the grid is, and whether the application running there has asked for mouse events.
func CapturePaneWithState ¶ added in v0.98.0
CapturePaneWithState is a capture plus the geometry observed with it. Every capture-shaped producer needs both — the rows alone cannot say where the live grid starts — so the pair is read here once rather than each caller inventing its own second tmux call.
func QueryPaneStateSync ¶ added in v0.98.0
QueryPaneStateSync reads a pane's cursor, geometry and mouse-tracking flag in the one display-message the capture path already pays for.
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 Pointer ¶ added in v0.98.0
type Pointer struct {
// Resolution is what a release without motion will do.
Resolution ClickResolution
// contains filtered or unexported fields
}
Pointer is the click/drag state machine over a terminal surface: what a release without motion will mean, the granularity a drag extends by, and the held-pointer edge scroll. It owns no selection — the surface it edits is passed in — and no transport, so a headless caller can drive a whole gesture.
func (*Pointer) Abandon ¶ added in v0.98.0
func (pt *Pointer) Abandon()
Abandon ends a gesture whose release will never arrive — the pointer left the window, focus changed, a modal swallowed the button-up. Neither activation nor a forwarded click survives a release the app never saw.
func (*Pointer) AdoptSurface ¶ added in v0.98.0
func (pt *Pointer) AdoptSurface(sel *ui.SelectionState, r mouse.Rect)
AdoptSurface names the surface a gesture belongs to, for the pointer and for the selection it edits at once. Both must describe the same rect: the pointer's is what a drag whose press landed off the text anchors against, the selection's is what the host hit-tests with, and a caller that wrote only one of them left the two able to disagree.
func (*Pointer) AdvanceAutoScroll ¶ added in v0.98.0
func (pt *Pointer) AdvanceAutoScroll(generation uint64, target AutoScrollTarget) bool
AdvanceAutoScroll runs one step of the held-pointer edge scroll and reports whether another is owed. It stops when the tick belongs to an ended gesture, when there is no selection to extend, when the run is long enough to be a lost release, when the pointer is back inside the content, or when the window has no more rows in that direction.
func (*Pointer) AnchorFrom ¶ added in v0.98.0
func (pt *Pointer) AnchorFrom(g Geometry, buf *OutputBuffer, sel *ui.SelectionState, originX, originY int, rectangular bool) bool
AnchorFrom starts a selection for a drag whose mouse-down landed off the text — on the header, on the padding below the last row, in the border. The gesture is unambiguously a selection by the time it is moving, so anchor it at the nearest cell to where the button actually went down rather than letting the whole drag do nothing.
func (*Pointer) Arm ¶ added in v0.98.0
func (pt *Pointer) Arm(resolution ClickResolution, x, y int)
Arm records what a release without motion will do, and where the button went down — a forwarded click is reported at the press position, never the release.
func (*Pointer) Begin ¶ added in v0.98.0
func (pt *Pointer) Begin()
Begin closes whatever gesture was running: any auto-scroll tick still in flight belongs to the old generation and is dropped.
func (*Pointer) BeginAutoScrollTick ¶ added in v0.98.0
BeginAutoScrollTick clears the in-flight tick and reports whether it still belongs to the live gesture.
func (*Pointer) ConsumeAutoScrollTick ¶ added in v0.98.0
ConsumeAutoScrollTick counts one tick without fresh motion behind it, reporting false once the run is long enough to be a lost release.
func (*Pointer) DragPoint ¶ added in v0.98.0
DragPoint is the last pointer position of the live drag, which the edge auto-scroll tick re-reads.
func (*Pointer) DragTo ¶ added in v0.98.0
func (pt *Pointer) DragTo(g Geometry, buf *OutputBuffer, sel *ui.SelectionState, x, y int) bool
DragTo moves the live selection to the cell nearest the pointer, snapped to the gesture's unit.
func (*Pointer) ExtendTo ¶ added in v0.98.0
func (pt *Pointer) ExtendTo(g Geometry, buf *OutputBuffer, sel *ui.SelectionState, cell Cell)
ExtendTo grows an existing selection to a cell, snapped to the gesture's unit when one is in flight.
func (*Pointer) ExtendToUnit ¶ added in v0.98.0
func (pt *Pointer) ExtendToUnit(g Geometry, buf *OutputBuffer, sel *ui.SelectionState, cell Cell) bool
ExtendToUnit extends a word or line gesture to the unit under the pointer. The anchor unit stays whole in either direction: dragging backwards pins the far edge of the anchor, which is what makes word-drag feel like a terminal rather than a character drag that happens to start on a word.
func (*Pointer) Generation ¶ added in v0.98.0
Generation identifies the live gesture, so a timer scheduled by an older one can be discarded.
func (*Pointer) NoteDragMotion ¶ added in v0.98.0
NoteDragMotion records fresh pointer motion, which restarts the hold budget that bounds an auto-scroll chain running on a lost release.
func (*Pointer) Press ¶ added in v0.98.0
func (pt *Pointer) Press(g Geometry, buf *OutputBuffer, sel *ui.SelectionState, ev PressEvent)
Press arms a gesture at the pointer. Selection only activates on actual drag motion, so a press over text prepares a drag rather than starting a selection.
func (*Pointer) PressPoint ¶ added in v0.98.0
PressPoint is where the button went down.
func (*Pointer) Release ¶ added in v0.98.0
func (pt *Pointer) Release(sel *ui.SelectionState) (ClickResolution, bool)
Release ends the gesture and reports what it meant: the armed resolution when nothing was selected, and whether a selection survives.
A character gesture that never left its anchor cell is a click that jittered, not a selection. Without this, a twitch during a click leaves a one-cell selection, silently copies it under copy-on-select, and swallows the activation the user was asking for. A word gesture on a one-character word legitimately ends here, so it is exempt.
func (*Pointer) ResetUnit ¶ added in v0.98.0
func (pt *Pointer) ResetUnit()
ResetUnit drops the anchor unit. A word span left over from an old double-click would otherwise redefine where the next shift-click extends from.
func (*Pointer) ScheduleAutoScroll ¶ added in v0.98.0
ScheduleAutoScroll queues the next step of the held-pointer scroll, at most one tick in flight at a time. The tick message is the host's, built with the generation that pins it to this gesture.
func (*Pointer) SelectUnitAt ¶ added in v0.98.0
func (pt *Pointer) SelectUnitAt(g Geometry, buf *OutputBuffer, sel *ui.SelectionState, x, y int, unit SelectionUnit) bool
SelectUnitAt installs the word or line under the pointer and records it as the gesture's anchor unit, so a button still held extends by that unit and never eats into the unit the gesture started on. The mouse-down that opened the gesture asked for the terminal, or for the app's click; a double or triple click withdraws that, or the release would fire it under the selection the user just made.
func (*Pointer) Unit ¶ added in v0.98.0
func (pt *Pointer) Unit() SelectionUnit
Unit is the granularity the live gesture extends by.
type PointerIntent ¶ added in v0.98.0
type PointerIntent uint8
PointerIntent is what a pointer action over a terminal means, independent of what any one host does about it.
const ( // PointerIgnore is an action the terminal has no answer for. PointerIgnore PointerIntent = iota // PointerPress arms a gesture at the pressed cell, which the release // resolves into an activation, a forwarded click, or nothing. PointerPress // PointerSelectWord and PointerSelectLine are the double and triple click. PointerSelectWord PointerSelectLine // PointerWheel is a notch over the surface. PointerWheel // PointerDrag extends the selection the press anchored. PointerDrag // PointerFinish is the release that resolves the gesture. PointerFinish // PointerAbandon is the release the surface never saw — the pointer left the // window, or focus changed — which ends the gesture where it stands. PointerAbandon )
func PointerIntentFor ¶ added in v0.98.0
func PointerIntentFor(in PointerIntentInput) PointerIntent
PointerIntentFor maps a pointer action over a terminal onto the gesture it means. The bodies are each host's — one arms a tmux click, another moves a browser's window — but which of them an action asks for is one rule, or the two surfaces answer the same gesture differently.
type PointerIntentInput ¶ added in v0.98.0
type PointerIntentInput struct {
Action mouse.ActionType
// OverTerminal reports that the action landed on a region drawing a
// terminal.
OverTerminal bool
// FromTerminal reports that the gesture in flight began on one. A drag and
// its release are answered by where they started, never by where the pointer
// has since travelled — a selection dragged off the pane is still that
// pane's selection.
FromTerminal bool
// LostRelease reports a button-less motion that ended a drag no release was
// ever seen for.
LostRelease bool
}
PointerIntentInput is what a host knows about one pointer action: what the action was, whether it landed on a terminal, and whether the gesture in flight started on one.
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 PressEvent ¶ added in v0.98.0
type PressEvent struct {
X, Y int
Shift, Alt bool
Rect mouse.Rect
Want ClickResolution
SameSource bool
}
PressEvent is a mouse-down over a terminal surface.
SameSource reports whether the press landed on the surface the current selection was made in; a host that draws only one terminal always sets it. Want is what a release without motion should do, which only the host can decide: it knows whether the terminal is already live and whether something with a stronger claim on the click (a link) has already refused it.
type ResyncReason ¶ added in v0.94.0
type ResyncReason uint8
ResyncReason says why a pane model needs a fresh seed, or why it stopped.
const ( // ResyncFirstSeed is the initial bootstrap: first subscribe, Sidecar // restart, or a pane switch that created a new subscription. ResyncFirstSeed ResyncReason = iota + 1 // ResyncReconnect is a replacement control client for the same session. ResyncReconnect // ResyncPause is %pause, or the %continue that follows it. tmux drops the // pane's buffered output while paused, so continuity is broken either way. ResyncPause // ResyncDiscarded is growth in the control client's client_discarded byte // counter: tmux dropped output because this client fell behind. ResyncDiscarded // ResyncLayout is a layout or window-pane change. ResyncLayout // ResyncResize is a Sidecar-initiated geometry change. tmux is resized // first and the seed reads back the authoritative resulting geometry. ResyncResize // ResyncSeedRace means pane bytes arrived between the seed transaction's // metadata response and its capture response, so the metadata describes an // older moment than the capture. Never observed against tmux 3.6b; it is // detected rather than assumed away. ResyncSeedRace // ResyncPaneIdentity means tmux reported a different pane id than the one // subscribed to. Terminal for the feed. ResyncPaneIdentity // ResyncModelFault is a malformed payload, parser error, impossible // geometry, or model panic. Terminal for the feed. ResyncModelFault )
Resync reasons.
func (ResyncReason) String ¶ added in v0.94.0
func (r ResyncReason) String() string
type ScreenCompareSample ¶ added in v0.94.0
type ScreenCompareSample struct {
Signature string `json:"signature"`
Class string `json:"class"`
Row int `json:"row"`
Col int `json:"col"`
}
ScreenCompareSample locates one mismatch without describing it. Coordinates and class only: a grapheme, a colour value, or a link URL would be terminal content and is never recorded.
type ScreenCompareSnapshot ¶ added in v0.94.0
type ScreenCompareSnapshot struct {
// Model lifecycle.
Seeds int `json:"seeds"`
SeedRaces int `json:"seed_races"`
Resyncs map[string]int `json:"resyncs"`
Faults int `json:"faults"`
Fallbacks int `json:"fallbacks"`
ModelsOpened int `json:"models_opened"`
ModelsClosed int `json:"models_closed"`
// Byte flow.
RawEvents int `json:"raw_events"`
RawBytes int64 `json:"raw_bytes"`
DiscardedBytes int64 `json:"discarded_bytes"`
// Frames and captures.
ModelFrames int `json:"model_frames"`
Captures int `json:"captures"`
MetadataQueries int `json:"metadata_queries"`
// CapturesWhileModelLive is the number of capture transactions that ran at
// a moment a live pane model already held the same screen. Under byte-fed
// authority these are exactly the captures that would not be issued, which
// is what the decision gate's "zero capture-pane per output burst" asks
// about. SeedCaptures is the expected remainder.
CapturesWhileModelLive int `json:"captures_while_model_live"`
SeedCaptures int `json:"seed_captures"`
DiscardProbes int `json:"discard_probes"`
// Comparison outcome.
Comparisons int `json:"comparisons"`
ComparisonsClean int `json:"comparisons_clean"`
ComparisonsAttrib int `json:"comparisons_attributable"`
ComparisonsOpenWin int `json:"comparisons_in_open_discard_window"`
ComparisonsMetaRaced int `json:"comparisons_with_capture_metadata_race"`
// UncomparableCells counts cell differences dropped because capture-pane
// cannot express the answer (trailing trimmed blanks). They are neither
// agreements nor mismatches; recorded so "clean" is never overstated.
UncomparableCells int `json:"uncomparable_cells"`
// ComparedCells is the total visible surface offered to the comparator
// (width × height per comparison). It is the denominator UncomparableCells
// has to be read against; without it an absolute count of declined cells
// says nothing about how much of the screen was actually covered.
ComparedCells int64 `json:"compared_cells"`
// ComparisonsSkipped counts comparisons abandoned because the capture side
// described no surface. They are not clean and not mismatched.
ComparisonsSkipped int `json:"comparisons_skipped"`
// Mismatches, split the way the decision gate is judged.
MismatchesBySignature map[string]int `json:"mismatches_by_signature"`
MismatchesByClass map[string]int `json:"mismatches_by_class"`
// FramesWithMismatch counts comparisons (not cells) that had at least one
// mismatch, so one corrupted row does not read as hundreds of failures.
FramesWithMismatch int `json:"frames_with_mismatch"`
FramesWithUnexplainedMismatch int `json:"frames_with_unexplained_mismatch"`
Samples []ScreenCompareSample `json:"samples"`
// Timing, in microseconds, and memory, in bytes.
OutputToFrameUS latencyStat `json:"output_to_frame_us"`
OutputToCaptureUS latencyStat `json:"output_to_capture_us"`
ModelWriteUS latencyStat `json:"model_write_us"`
ModelRenderUS latencyStat `json:"model_render_us"`
CompareUS latencyStat `json:"compare_us"`
ModelBytesPeak int64 `json:"model_bytes_peak"`
ModelBytesLast int64 `json:"model_bytes_last"`
Started time.Time `json:"started"`
}
ScreenCompareSnapshot is the counter payload, separated from its mutex so a reader can copy and marshal it.
type ScreenCompareStats ¶ added in v0.94.0
type ScreenCompareStats struct {
ScreenCompareSnapshot
// contains filtered or unexported fields
}
ScreenCompareStats is the privacy-safe diagnostic counter set the plan's "Rollback and observability" section requires. A zero value is usable.
func ScreenCompare ¶ added in v0.94.0
func ScreenCompare() *ScreenCompareStats
ScreenCompare returns the process-wide shadow-comparison counters.
func (*ScreenCompareStats) JSON ¶ added in v0.94.0
func (s *ScreenCompareStats) JSON() []byte
JSON renders the counters. The output is safe to attach to a report: by construction it contains no terminal content.
func (*ScreenCompareStats) Report ¶ added in v0.94.0
func (s *ScreenCompareStats) Report() string
Report renders the decision-gate evidence as markdown.
func (*ScreenCompareStats) Snapshot ¶ added in v0.94.0
func (s *ScreenCompareStats) Snapshot() ScreenCompareSnapshot
Snapshot returns a copy safe to read and marshal.
type ScrollbackMove ¶ added in v0.98.0
ScrollbackMove is where a shift-scrollback key puts the window. Rows is a relative move, positive towards older output; the two jumps are absolute.
func MapScrollbackKey ¶ added in v0.98.0
func MapScrollbackKey(state ScrollbackState, msg tea.KeyPressMsg, pageSize int) (ScrollbackMove, bool)
MapScrollbackKey turns a navigation key into a window move over captured output, for a surface in the state named.
One set of moves answers both states; what differs is the form of the key that reaches them. While a pane is live every unshifted key is the pane's, so a navigation key moves the window only with shift. While the pane is merely watched nothing is being typed into it, so the same keys answer bare — and the pager aliases answer too: j/k, g/G and ctrl+d/ctrl+u are text and control chords a live pane must receive, and shift cannot free a letter from it, it only capitalises it.
pageSize is the drawn rows of the surface under the keys, which is what makes a page the same distance wherever it is pressed. A page keeps one row of context the way a pager does; the half-page chords take half the surface.
type ScrollbackState ¶ added in v0.99.0
type ScrollbackState uint8
ScrollbackState is who owns the keyboard over a terminal surface. It is what decides which form of a scrollback key that surface may claim: the shift requirement is a property of the state — an unshifted key belongs to a live pane — rather than of the key.
const ( // ScrollbackLive is a pane taking input. A navigation key is the surface's // only with shift; everything else the keyboard sends is typing. ScrollbackLive ScrollbackState = iota // ScrollbackWatched is a pane nobody is typing into. The same navigation // keys answer bare, and the pager aliases answer alongside them. ScrollbackWatched )
type SelectionUnit ¶ added in v0.98.0
type SelectionUnit uint8
SelectionUnit is the granularity a gesture extends by. Double- and triple-clicks keep dragging in whole words and whole lines, as xterm and iTerm2 do, until the next plain click.
const ( SelectUnitChar SelectionUnit = iota SelectUnitWord SelectUnitLine )
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
// 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.
type StatusNote ¶ added in v0.98.0
StatusNote is one fact about the drawn window, in the two lengths a header can afford it. A narrow right region states the fact in fewer columns rather than dropping it — the fact is what the reader needs; the wording is not.
func WindowStatus ¶ added in v0.98.0
func WindowStatus(in WindowStatusInput) []StatusNote
WindowStatus is the facts a pane's header states about the window over it, most important first.
The order is the priority order: a window off the live edge leads, because it is the only note that explains output the user cannot see. Both terminal surfaces read it, so a fact cannot be stated on one and missing on the other — which is exactly how the global browser came to show a scrollbar and no word about being off the live edge.
type SurfaceChords ¶ added in v0.98.0
type SurfaceChords struct {
// Copy puts the current selection on the clipboard.
Copy func() tea.Cmd
// SelectAll selects every line of output the surface is showing.
SelectAll func() tea.Cmd
// Scrollback walks the window through history. It answers for itself
// because which keys move a window is the shared scrollback rule's, and a
// surface with no window scrolled back declines them.
Scrollback func(tea.KeyPressMsg) (tea.Cmd, bool)
}
SurfaceChords are the acts that belong to the surface drawn around a live pane rather than to the pane inside it. A host registers them as one value so the set and the order are the component's, not each host's: two surfaces that each decided where copy sits relative to scrollback would answer the same key differently.
A host with chords genuinely its own — a search over its own buffer, a panel its layout owns — answers those before calling here. Nothing in this set may be one of them: they act on the pane's output, which every host has.
type Viewport ¶ added in v0.98.0
type Viewport struct {
Start int
End int
EffectiveCount int
DisplayWidth int
DisplayHeight int
MaxOffset int
AbsoluteStart int
ShowScrollbar bool
// PadWidth is the column the content block is padded to before a scrollbar
// is joined to it. It tracks the viewport rather than the pane so the
// scrollbar stays at the viewport's edge.
PadWidth int
// Fit records how the pane's observed geometry was projected onto the
// viewport: letterboxed when the pane is smaller, clipped (with ColOffset
// as the first visible column) when it is larger.
Fit PaneFit
// PaneClipped reports that the pane itself does not fit the viewport, as
// opposed to Fit.ClippedWidth, which also trips when the scrollbar takes a
// column off an otherwise perfectly sized pane.
PaneClipped bool
// PaneTop is the buffer index of pane row 0, so a rendered row maps back to
// the pane row tmux would report for it, and so the native cursor lands on
// the row it belongs to.
//
// It comes from the buffer, which was told the split by whoever published
// the content — a screen-model frame knows its loaded history rows and its
// grid height at the instant it is built, and a capture knows its own row
// count and the pane height read with it. Both alternatives were tried and
// both drift. The absolute-coordinate form (history_size + cursor_row -
// buffer base) mixes two independently observed quantities: display-message
// and capture-pane are separate writes, so N lines can scroll into history
// between them and the cursor is drawn N rows too high until the pane is
// re-seeded. Re-deriving it as "the buffer's last PaneHeight lines" instead
// assumes a serialization detail that does not hold: a grid whose final row
// is blank ends in a newline that reads as a terminator, the buffer is a row
// short, and the cursor is drawn one row too high (td-d29821). Absolute
// coordinates are still what scrollback, search, and selection use, where a
// transient off-by-N is harmless.
PaneTop int
}
Viewport is where a buffer's lines land inside a viewport: which lines are drawn, how wide and tall the drawn area is, and how the pane's own geometry was projected onto it.
func FitViewport ¶ added in v0.98.0
func FitViewport(in ViewportInput) Viewport
FitViewport resolves the drawn window for one terminal surface.
type ViewportInput ¶ added in v0.98.0
type ViewportInput struct {
Buffer *OutputBuffer
Width int
Height int
// Offset is absolute from the top unless OffsetFromBottom is set.
Offset int
OffsetFromBottom bool
Follow bool
TrimTrailing bool
Interactive bool
CursorRow int
CursorCol int
CursorVisible bool
PaneHeight int
PaneWidth int
AbsoluteBase int
// Scrollbar reserves the viewport's final column. It is explicit because it
// moves every column the user can click on, so a host that draws one and a
// host that does not must not be distinguished by an implicit width test.
Scrollbar bool
}
ViewportInput contains every value needed to lay out a captured terminal buffer inside a viewport. It is deliberately value-only: layout must not mutate the buffer or any host state.
type WheelBurst ¶ added in v0.98.0
type WheelBurst struct {
// contains filtered or unexported fields
}
WheelBurst coalesces a trackpad flick into whole steps. It is the one place the "how much of this burst has the surface earned" rule lives, so a fast flick travels the same distance whichever surface it lands on.
It holds only the burst's own bookkeeping: no viewport, no transport, no clock of its own — the caller passes the time, so a test can drive a whole flick without sleeping.
func (*WheelBurst) Add ¶ added in v0.98.0
Add takes one wheel event and reports the delta to apply, if any. A held-back event is not lost: its delta joins the next one that gets through.
func (*WheelBurst) LastAt ¶ added in v0.98.0
func (b *WheelBurst) LastAt() time.Time
LastAt is when the burst last let an event through, which is what a snap-back cooldown measures against.
func (*WheelBurst) Pending ¶ added in v0.98.0
func (b *WheelBurst) Pending() int
Pending is the delta held back from the flick so far. It is carried by the next event that gets through, never dropped.
func (*WheelBurst) Remaining ¶ added in v0.98.0
Remaining is how much of the burst window is left, and false once the flick is over. A surface that repaints from a poll defers it for this long: a capture taken mid-flick is stale before it arrives.
func (*WheelBurst) Reset ¶ added in v0.98.0
func (b *WheelBurst) Reset()
Reset drops a burst in progress, for a surface that is no longer the one being scrolled.
type WheelBursts ¶ added in v0.99.0
type WheelBursts struct {
// contains filtered or unexported fields
}
WheelBursts holds one flick per terminal surface a host draws. Two surfaces scroll independently, so the delta one of them is holding back belongs to it alone: a gesture that crosses between them is two gestures, and the flick over the surface being left is dropped rather than spent on the one the pointer arrived at.
A host with a single terminal surface needs one WheelBurst and not this.
func (*WheelBursts) For ¶ added in v0.99.0
func (b *WheelBursts) For(surface string) *WheelBurst
For is the burst of the surface under the pointer, and asking for it is what records the crossing — so a notch cannot reach a surface without the flick over its neighbour ending.
func (*WheelBursts) LastAt ¶ added in v0.99.0
func (b *WheelBursts) LastAt() time.Time
LastAt is when a notch last moved any of these surfaces, which is what a snap-back cooldown measures against: the reader scrolled just now, whichever surface they scrolled.
func (*WheelBursts) Remaining ¶ added in v0.99.0
Remaining is how much of the flick in progress is left, for a caller with no surface of its own to name — a poll deferral, a cooldown. Only the surface the pointer is over can have a flick running; the rest were dropped as it crossed.
func (*WheelBursts) Reset ¶ added in v0.99.0
func (b *WheelBursts) Reset()
Reset drops every flick in progress, for a host whose surfaces have all stopped being the one being scrolled.
type WheelGesture ¶ added in v0.98.0
WheelGesture is one wheel event over a terminal surface, in the host's own screen coordinates.
type WheelHandler ¶ added in v0.98.0
type WheelHandler struct {
// Burst coalesces the flick so the distance travelled does not depend on how
// fast a surface happens to repaint.
Burst *WheelBurst
// WritesEnabled says the host may write to the pane at all. Left false, a
// notch never leaves the host, whatever the pane is running.
WritesEnabled bool
// MouseReporting reports that the application in the pane has asked for
// mouse events, which is the only condition under which it owns the wheel.
// It answers about the pane under the pointer in every state: a host may not
// answer it from whether that pane also holds the keyboard.
MouseReporting func() bool
// PaneCoords maps a screen position onto a cell of the pane's grid. A notch
// over chrome is never the application's. Like MouseReporting it is about the
// pane, not the mode, and must answer for a watched one too.
PaneCoords func(x, y int) (col, row int, ok bool)
// PinToLive returns the host's window to the live edge. While the
// application owns the wheel it owns what the pane shows, and a window left
// scrolled back would sit over stale rows as the application repainted.
PinToLive func()
// NoteActivity records the notch as user input for the host's own poll
// cadence, which would otherwise repaint a scrolled pane at its idle tier.
// Every notch counts, forwarded or local: a pane being scrolled is a pane
// being read.
NoteActivity func()
// SendNotches delivers the notch to the application as wheel reports.
SendNotches func(up bool, col, row, notches int) tea.Cmd
// ScrollLocal moves the host's own window by the coalesced delta. It is what
// makes the wheel work over a plain shell, and it answers every notch the
// application has not claimed.
ScrollLocal func(delta int) tea.Cmd
// OnHold tells the host that this event changed only Burst bookkeeping. A
// host with an expensive View can reuse the frame it just drew once, because
// no terminal, viewport, selection, or routing state changed for this event.
OnHold func()
}
WheelHandler is a host's answers about a wheel notch over a terminal surface, live or merely watched. The order of the acts — coalesce the flick, decide who owns the notch, pin the window before forwarding, note the activity, send — is the shared rule; a host supplies only what it alone can know: where the pane's grid is, how its own window scrolls, and how it sends.
func (WheelHandler) Handle ¶ added in v0.98.0
func (h WheelHandler) Handle(g WheelGesture) tea.Cmd
Handle routes one wheel event. It returns nil while the burst is still coalescing, which is not a dropped notch: the held-back delta rides along with the next event that gets through.
type WheelInput ¶ added in v0.98.0
type WheelInput struct {
Delta int
Shift, Alt bool
MouseReporting bool
InPane bool
// WritesEnabled says the host may write to the pane at all. A forwarded
// notch is input, gated exactly as typing is, so a host that cannot write
// keeps every notch for its own window.
WritesEnabled bool
}
WheelInput is one wheel event over a terminal surface. Delta is a line count, negative upwards. InPane reports that the pointer position maps onto a cell of the pane's grid; a notch over chrome is never the application's.
MouseReporting and InPane are facts about the pane under the pointer, asked in every state: whether the keyboard happens to be in that pane says nothing about who drew what is on screen there.
type WheelRoute ¶ added in v0.98.0
type WheelRoute uint8
WheelRoute is who owns a wheel notch over a terminal surface.
const ( // WheelLocal scrolls the captured output the surface is showing. This is // the fallback for every notch the application has not claimed, and it is // what makes the wheel work over a plain shell. WheelLocal WheelRoute = iota // WheelPane encodes the notch as an SGR wheel report for the application // running in the pane. Full-screen apps draw their own scrollback inside the // pane and keep tmux's history empty, so consuming the notch locally would // slide the viewport across the app's live frame and leave the layout // looking torn. WheelPane )
func RouteWheel ¶ added in v0.98.0
func RouteWheel(in WheelInput) (WheelRoute, int)
RouteWheel decides who owns a notch, and how many whole notches it is worth.
The application only owns the wheel while it has asked for mouse reports. Alt is the "give me the terminal, not the app" modifier; Shift is checked too for symmetry with click handling, though a shift+wheel is normally mapped to horizontal scroll before it arrives.
type WindowFreeze ¶ added in v0.98.0
type WindowFreeze struct {
// contains filtered or unexported fields
}
WindowFreeze is the freeze state for a surface whose window is placed from the live bottom. It holds the absolute start the gesture pinned, and nothing else: the buffer, the layout and the scroll position stay the host's.
func (*WindowFreeze) Active ¶ added in v0.98.0
func (f *WindowFreeze) Active() bool
Active reports that a gesture is holding the window still.
func (*WindowFreeze) Freeze ¶ added in v0.98.0
func (f *WindowFreeze) Freeze(start int)
Freeze pins the window to start. A second freeze inside one gesture keeps the first: the gesture is reading the rows it was armed on.
func (*WindowFreeze) Rebase ¶ added in v0.98.0
func (f *WindowFreeze) Rebase(added int)
Rebase shifts a frozen start by rows prepended to the buffer, so a window pinned to an absolute row keeps the same output after a history load renumbers the buffer underneath it.
func (*WindowFreeze) Release ¶ added in v0.98.0
func (f *WindowFreeze) Release()
Release drops the freeze without placing the window, for a jump that chooses its own offset — a jump is not a gesture reading the rows it lands on.
func (*WindowFreeze) Scroll ¶ added in v0.98.0
func (f *WindowFreeze) Scroll(delta, maxOffset int)
Scroll moves a frozen window by delta rows towards the live edge, positive downwards, clamped to the buffer. A frozen window is placed from the top, so older output is a smaller start rather than a larger distance from the bottom.
func (*WindowFreeze) Start ¶ added in v0.98.0
func (f *WindowFreeze) Start() int
Start is the absolute top row the window is pinned to. It is meaningful only while Active.
func (*WindowFreeze) Thaw ¶ added in v0.98.0
func (f *WindowFreeze) Thaw(layout Viewport) (offset int, ok bool)
Thaw ends the freeze and reports the offset the window resumes following from, leaving the rows on screen where they are. ok is false when nothing was frozen, so a caller does not overwrite a scroll position it never pinned.
type WindowPlacement ¶ added in v0.98.0
WindowPlacement is where a window sits, in the terms the viewport takes it. A window a gesture is holding is placed from an absolute top row and follows nothing; every other window is a distance back from the live bottom, and it follows output exactly when that distance is zero.
func PlaceWindow ¶ added in v0.98.0
func PlaceWindow(freeze *WindowFreeze, offset int) WindowPlacement
PlaceWindow reports where a surface's window sits given its scroll offset and whatever freeze is holding it. It is the one derivation the render path, the native cursor and hit testing share, on every host.
type WindowStatusInput ¶ added in v0.98.0
type WindowStatusInput struct {
Layout Viewport
AbsoluteBase int
// LoadingOlder reports a fetch of older history already in flight, which
// replaces the offer of it.
LoadingOlder bool
// MouseReporting reports that the application in the pane has the mouse.
// WindowStatus no longer states this; callers may still compute it.
MouseReporting bool
// PaneLive reports that this surface is typing into the pane.
PaneLive bool
PaneWidth int
PaneHeight int
// LiveEdgeKey is the chord this surface answers to return to the live edge in
// the state it is in — every unshifted key belongs to a live pane, so it is
// [LiveEdgeKey] there and the host's plain key while the pane is only being
// watched. An empty value states the distance without naming a key, which is
// what a surface that cannot be scrolled back to live owes the reader.
LiveEdgeKey string
}
WindowStatusInput is what a header needs to know about the window drawn over a pane. Every field comes from the layout the surface actually rendered, so the status describes the rows on screen rather than a second derivation of them.
Source Files
¶
- capture_range.go
- click.go
- clipboard.go
- control_manager.go
- control_model.go
- control_protocol.go
- control_transport.go
- csiu.go
- cursor.go
- doc.go
- editor_launch.go
- editor_session.go
- geometry_lease.go
- gesture.go
- history.go
- keymap.go
- keys.go
- messages.go
- mousefragment.go
- output_buffer.go
- pane_fit.go
- paste.go
- pointer.go
- polling.go
- scheduler.go
- screencompare.go
- send_queue.go
- session.go
- surface_chords.go
- terminal_mode.go
- terminal_surface.go
- tty.go
- viewport.go
- wheel.go
- wheel_route.go
- window.go
- window_freeze.go
- window_status.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package screenmodel owns Sidecar's byte-fed pane screen model.
|
Package screenmodel owns Sidecar's byte-fed pane screen model. |