term2go

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Jun 15, 2026 License: MIT Imports: 20 Imported by: 0

README

term2go

Go client library for the iTerm2 WebSocket API.

中文文档

Overview

term2go is a Go client library that mirrors the official iTerm2 Python API, enabling programmatic control of iTerm2 via WebSocket. It provides comprehensive support for the full iTerm2 session hierarchy, RPC operations, notification subscriptions, and authentication.

Proto files: The proto/api.proto file is derived from the official iTerm2 Python API and is kept in sync with iTerm2 releases.

Features

Category APIs
Connection Connect, Run, NewConnection, AppleScript / env auth
Hierarchy GetApp, App.Refresh, Window, Tab, Session, Splitter
Session SendText, GetBuffer, Inject, Activate, Close, RestartSession
Screenshot Window.Screenshot, Tab.Screenshot, Session.Screenshot — capture window as PNG
Pane / Tab SplitPane (vertical/horizontal), CreateTab (also creates new windows)
Variable GetVariable, SetVariable
Property GetProperty, SetProperty, GetProfileProperty, SetProfileProperty
Selection SelectionRequest, SetSelection
Prompt GetPrompt, ListPrompts
Profile ListProfiles
Focus FocusRequest
Alert ShowAlert, ShowTextInputAlert, ShowOpenPanel, ShowSavePanel, PolyModalAlert
Trigger NotificationPostedEventTrigger, MarkStopScrolling, event-based triggers
Binding Binding, ListBindings, keyboard binding management
Color ListColorPresets, GetColorPreset, color preset management
Status Bar StatusBarComponent, CheckboxKnob, StringKnob, FloatKnob, ColorKnob
Advanced PreferencesRequest, TmuxRequest, SavedArrangementRequest, InvokeFunction
Notification SubscribeNewSession, SubscribeKeystroke, SubscribeFocusChange, SubscribeVariableChange, and more
RPC NotificationRequest, ServerOriginatedRPCResultRequest, RPCRegistry, RPCRegistration
Capability ProtocolVersion, SupportsFeature, version feature detection

Installation

go get github.com/phpgao/term2go

Requirements:

  • Go 1.23+
  • iTerm2 with the Python API enabled (Preferences → General → Magic)

Quick Start

Basic Usage
package main

import (
    "context"
    "fmt"

    "github.com/phpgao/term2go"
)

func main() {
    ctx := context.Background()
    term2go.Run(ctx, "my-app", func(caller term2go.Caller) error {
        app, _ := term2go.GetApp(caller)
        for _, w := range app.Windows {
            fmt.Printf("Window %s: %d tabs\n", w.ID, len(w.Tabs))
        }
        return nil
    })
}
Send Text to Session
app, _ := term2go.GetApp(caller)
session := app.Windows[0].Tabs[0].Root.FindSessionByID("session-id")
session.SendText(ctx, "ls -la\n", false)
Split Pane
session.SplitPane(ctx, true, false, "Default") // Vertical split
Screenshot Window
app, _ := term2go.GetApp(caller)
w := app.Windows[0]

// Captures the entire window as a PNG file
err := w.Screenshot(ctx, "/tmp/screenshot.png")

Screenshot is also available on Tab and Session. It activates the window, then uses macOS screencapture -l to capture the window directly by its native window ID.

Subscribe to Events
token, _ := term2go.SubscribeNewSession(caller, conn,
    func(c term2go.Caller, n *iterm2.NewSessionNotification) {
        fmt.Println("new session:", n.GetSessionId())
    })
defer conn.Unsubscribe(token)

Authentication

term2go tries environment variables first, then falls back to AppleScript:

# Option 1: Set env vars (recommended for scripts)
export ITERM2_COOKIE="..."
export ITERM2_KEY="..."

# Option 2: Auto-detect via AppleScript (needs iTerm2 running)

Object Hierarchy

App → Window → Tab → Splitter (recursive) → Session

- App:       top-level container, holds all windows
- Window:    an iTerm2 window, holds tabs
- Tab:       a tab, holds a Splitter root
- Splitter:  a pane-split container (recursive, leaf is Session)
- Session:   a terminal session (pane)

Examples

See example/ for runnable demos:

Example What it demonstrates
session SendText, GetBuffer, command execution
variable GetVariable, SetVariable
pane SplitPane, traverse split structures
inject Inject keystrokes into session
property SetName, SetBadge, SetBuried, SetGridSize
query GetApp, traverse hierarchy
notification Event subscriptions
prompt Interactive prompt / user input
live Continuous output with poll-based delta tracking

Run an example:

go run ./example/session

Documentation

go doc github.com/phpgao/term2go

Or check the inline documentation in the source files.

Development

# Run all tests
make test

# Run with race detector
make test

# Generate coverage report
make cover

# Run linter
make lint

# Regenerate protobuf files
make proto

# Build
make build

License

MIT

Documentation

Overview

Package term2go provides a Go client library for iTerm2's WebSocket API.

It mirrors the official iTerm2 Python API, enabling Go programs to control iTerm2 — list windows/tabs/sessions, send text, split panes, read terminal content, subscribe to notifications, and more.

Quick start:

package main

import (
    "context"
    "fmt"
    "github.com/phpgao/term2go"
)

func main() {
    ctx := context.Background()
    term2go.Run(ctx, "my-app", func(caller term2go.Caller) error {
        app, err := term2go.GetApp(caller)
        if err != nil {
            return err
        }
        for _, w := range app.Windows {
            fmt.Printf("Window: %d tabs\n", len(w.Tabs))
        }
        return nil
    })
}

Connection:

The library connects to iTerm2 via WebSocket. It tries the Unix domain socket first (~/Library/Application Support/iTerm2/private/socket), then falls back to TCP (localhost:1912). Authentication uses the ITERM2_COOKIE / ITERM2_KEY environment variables, or obtains them automatically via AppleScript.

Object hierarchy:

App → Window → Tab → Splitter (recursive) → Session

- App:       top-level container, holds all windows
- Window:    an iTerm2 window, holds tabs
- Tab:       a tab, holds a Splitter root
- Splitter:  a pane-split container (recursive, leaf is Session)
- Session:   a terminal session (pane)

RPC:

All 30+ iTerm2 RPC operations are available as package-level functions, or through methods on the model objects:

session.SendText("ls -la\n", false)
session.SplitPane(true, false, "Default")
name, _ := session.GetVariable("jobName")

Notifications:

Subscribe to iTerm2 events:

token, _ := term2go.SubscribeNewSession(caller, conn,
    func(c Caller, n *iterm2.NewSessionNotification) {
        fmt.Println("new session:", n.GetSessionId())
    })
defer conn.Unsubscribe(token)

Requirements:

The iTerm2 Python API must be enabled in iTerm2's preferences.

Package term2go provides a Go client library for iTerm2's Python API. It connects to the iTerm2 WebSocket interface, implements the RPC protocol, and exposes the full session hierarchy (App → Window → Tab → Splitter → Session).

Index

Constants

View Source
const (
	// ---- iTerm2 ----
	MenuItemAboutITerm2             = "About iTerm2"
	MenuItemShowTipOfTheDay         = "Show Tip of the Day"
	MenuItemCheckForUpdates         = "Check For Updates…"
	MenuItemToggleDebugLogging      = "Toggle Debug Logging"
	MenuItemCopyPerformanceStats    = "Copy Performance Stats"
	MenuItemCaptureGPUFrame         = "Capture Metal Frame"
	MenuItemPreferences             = "Preferences..."
	MenuItemHideITerm2              = "Hide iTerm2"
	MenuItemHideOthers              = "Hide Others"
	MenuItemShowAll                 = "Show All"
	MenuItemSecureKeyboard          = "Secure Keyboard Entry"
	MenuItemMakeITerm2DefaultTerm   = "Make iTerm2 Default Term"
	MenuItemMakeTerminalDefaultTerm = "Make Terminal Default Term"
	MenuItemInstallShellIntegration = "Install Shell Integration"
	MenuItemQuitITerm2              = "Quit iTerm2"

	// ---- Shell ----
	MenuItemNewWindow                           = "New Window"
	MenuItemNewWindowWithCurrentProfile         = "New Window with Current Profile"
	MenuItemNewTab                              = "New Tab"
	MenuItemNewTabWithCurrentProfile            = "New Tab with Current Profile"
	MenuItemDuplicateTab                        = "Duplicate Tab"
	MenuItemSplitHorizontallyWithCurrentProfile = "Split Horizontally with Current Profile"
	MenuItemSplitVerticallyWithCurrentProfile   = "Split Vertically with Current Profile"
	MenuItemSplitHorizontally                   = "Split Horizontally…"
	MenuItemSplitVertically                     = "Split Vertically…"
	MenuItemSaveContents                        = "Log.SaveContents"
	MenuItemSaveSelectedText                    = "Save Selected Text…"
	MenuItemClose                               = "Close"
	MenuItemCloseTerminalWindow                 = "Close Terminal Window"
	MenuItemCloseAllPanesInTab                  = "Close All Panes in Tab"
	MenuItemUndoClose                           = "Undo Close"

	// Shell > BroadcastInput
	MenuItemSendInputToCurrentSessionOnly        = "Broadcast Input.Send Input to Current Session Only"
	MenuItemBroadcastInputToAllPanesInAllTabs    = "Broadcast Input.Broadcast Input to All Panes in All Tabs"
	MenuItemBroadcastInputToAllPanesInCurrentTab = "Broadcast Input.Broadcast Input to All Panes in Current Tab"
	MenuItemToggleBroadcastInputToCurrentSession = "Broadcast Input.Toggle Broadcast Input to Current Session"
	MenuItemShowBackgroundPatternIndicator       = "Broadcast Input.Show Background Pattern Indicator"

	// Shell > tmux
	MenuItemTmuxDetach      = "tmux.Detach"
	MenuItemTmuxForceDetach = "tmux.Force Detach"
	MenuItemTmuxNewWindow   = "tmux.New Tmux Window"
	MenuItemTmuxNewTab      = "tmux.New Tmux Tab"
	MenuItemTmuxPausePane   = "trmux.Pause Pane"
	MenuItemTmuxDashboard   = "tmux.Dashboard"

	// Shell > ssh
	MenuItemSSHDisconnect         = "ssh.Disconnect"
	MenuItemSSHRemoveFileProvider = "ssh.Remove File Provider"
	MenuItemSSHAddFileProvider    = "ssh.Add File Provider"

	// Shell > Print
	MenuItemPageSetup      = "Page Setup..."
	MenuItemPrintScreen    = "Print.Screen"
	MenuItemPrintSelection = "Print.Selection"
	MenuItemPrintBuffer    = "Print.Buffer"

	// ---- Edit ----
	MenuItemUndo                     = "Undo"
	MenuItemRedo                     = "Redo"
	MenuItemCut                      = "Cut"
	MenuItemCopy                     = "Copy"
	MenuItemCopyWithStyles           = "Copy with Styles"
	MenuItemCopyWithControlSequences = "Copy with Control Sequences"
	MenuItemCopyMode                 = "Copy Mode"
	MenuItemPaste                    = "Paste"

	// Edit > PasteSpecial
	MenuItemAdvancedPaste                     = "Paste Special.Advanced Paste…"
	MenuItemPasteSelection                    = "Paste Special.Paste Selection"
	MenuItemPasteFileBase64Encoded            = "Paste Special.Paste File Base64-Encoded"
	MenuItemPasteSlowly                       = "Paste Special.Paste Slowly"
	MenuItemPasteFaster                       = "Paste Special.Paste Faster"
	MenuItemPasteSlowlyFaster                 = "Paste Special.Paste Slowly Faster"
	MenuItemPasteSlower                       = "Paste Special.Paste Slower"
	MenuItemPasteSlowlySlower                 = "Paste Special.Paste Slowly Slower"
	MenuItemWarnBeforeMultilinePaste          = "Paste Special.Warn Before Multi-Line Paste"
	MenuItemPromptConvertTabsToSpacesOnPaste  = "Paste Special.Prompt to Convert Tabs to Spaces when Pasting"
	MenuItemLimitMultilinePasteWarningToShell = "Paste Special.Limit Multi-Line Paste Warning to Shell Prompt"
	MenuItemWarnBeforePastingOneLine          = "Paste Special.Warn Before Pasting One Line Ending in a Newline at Shell Prompt"

	MenuItemRenderSelection                 = "Render Selection Natively"
	MenuItemOpenSelection                   = "Open Selection"
	MenuItemJumpToSelection                 = "Find.Jump to Selection"
	MenuItemSelectAll                       = "Select All"
	MenuItemSelectionRespectsSoftBoundaries = "Selection Respects Soft Boundaries"
	MenuItemSelectOutputOfLastCommand       = "Select Output of Last Command"
	MenuItemSelectCurrentCommand            = "Select Current Command"

	// Edit > Find
	MenuItemFindFind            = "Find.Find..."
	MenuItemFindNext            = "Find.Find Next"
	MenuItemFindPrevious        = "Find.Find Previous"
	MenuItemUseSelectionForFind = "Find.Use Selection for Find"
	MenuItemFindGlobally        = "Find.Find Globally..."
	MenuItemSelectMatches       = "Find.ConvertMatchesToSelections"
	MenuItemFindURLs            = "Find.Find URLs"
	MenuItemFindPickResult      = "Find.Pick Result To Open"
	MenuItemFilter              = "Find.Filter"

	// Edit > MarksAndAnnotations
	MenuItemSetMark               = "Marks and Annotations.Set Mark"
	MenuItemJumpToMark            = "Marks and Annotations.Jump to Mark"
	MenuItemNextMark              = "Marks and Annotations.Next Mark"
	MenuItemPreviousMark          = "Marks and Annotations.Previous Mark"
	MenuItemAddAnnotationAtCursor = "Marks and Annotations.Add Annotation at Cursor"
	MenuItemNextAnnotation        = "Marks and Annotations.Next  Annotation"
	MenuItemPreviousAnnotation    = "Marks and Annotations.Previous  Annotation"

	// Edit > MarksAndAnnotations > Alerts
	MenuItemAlertOnNextMark   = "Marks and Annotations.Alerts.Alert on Next Mark"
	MenuItemShowModalAlertBox = "Marks and Annotations.Alerts.Show Modal Alert Box"
	MenuItemPostNotification  = "Marks and Annotations.Alerts.Post Notification"

	MenuItemClearBuffer             = "Clear Buffer"
	MenuItemClearScrollbackBuffer   = "Clear Scrollback Buffer"
	MenuItemClearToStartOfSelection = "Clear to Start of Selection"
	MenuItemClearToLastMark         = "Clear to Last Mark"

	// ---- View ----
	MenuItemShowTabsInFullscreen               = "Show Tabs in Fullscreen"
	MenuItemToggleFullScreen                   = "Toggle Full Screen"
	MenuItemUseTransparency                    = "Use Transparency"
	MenuItemDisableTransparencyForActiveWindow = "Disable Transparency for Active Window"
	MenuItemZoomInOnSelection                  = "Zoom In on Selection"
	MenuItemZoomOut                            = "Zoom Out"
	MenuItemFindCursor                         = "Find Cursor"
	MenuItemShowCursorGuide                    = "Show Cursor Guide"
	MenuItemShowTimestamps                     = "Show Timestamps"
	MenuItemShowAnnotations                    = "Show Annotations"
	MenuItemShowComposer                       = "Composer"
	MenuItemAutoCommandCompletion              = "Auto Command Completion"
	MenuItemOpenQuickly                        = "Open Quickly"
	MenuItemMaximizeActivePane                 = "Maximize Active Pane"
	MenuItemMakeTextBigger                     = "Make Text Bigger"
	MenuItemMakeTextNormalSize                 = "Make Text Normal Size"
	MenuItemRestoreTextAndSessionSize          = "Restore Text and Session Size"
	MenuItemMakeTextSmaller                    = "Make Text Smaller"
	MenuItemSizeChangesUpdateProfile           = "Size Changes Update Profile"
	MenuItemStartInstantReplay                 = "Start Instant Replay"

	// ---- Session ----
	MenuItemEditSession           = "Edit Session…"
	MenuItemRunCoprocess          = "Run Coprocess…"
	MenuItemStopCoprocess         = "Stop Coprocess"
	MenuItemRestartSession        = "Restart Session"
	MenuItemOpenAutocomplete      = "Open Autocomplete…"
	MenuItemOpenCommandHistory    = "Open Command History…"
	MenuItemOpenRecentDirectories = "Open Recent Directories…"
	MenuItemOpenPasteHistory      = "Open Paste History…"

	// Session > Triggers
	MenuItemAddTrigger                  = "Add Trigger"
	MenuItemEditTriggers                = "Edit Triggers"
	MenuItemEnableTriggersInInteractive = "Enable Triggers in Interactive Apps"
	MenuItemTriggersEnableAll           = "Triggers.Enable All"
	MenuItemTriggersDisableAll          = "Triggers.Disable All"

	MenuItemReset             = "Reset"
	MenuItemResetCharacterSet = "Reset Character Set"

	// Session > Log
	MenuItemLogToggle          = "Log.Toggle"
	MenuItemLogImportRecording = "Log.ImportRecording"
	MenuItemLogExportRecording = "Log.ExportRecording"

	// Session > TerminalState
	MenuItemAlternateScreen          = "Alternate Screen"
	MenuItemFocusReporting           = "Focus Reporting"
	MenuItemMouseReporting           = "Mouse Reporting"
	MenuItemPasteBracketing          = "Paste Bracketing"
	MenuItemApplicationCursor        = "Application Cursor"
	MenuItemApplicationKeypad        = "Application Keypad"
	MenuItemStandardKeyReportingMode = "Terminal State.Standard Key Reporting"
	MenuItemModifyOtherKeysMode1     = "Terminal State.Report Modifiers like xterm 1"
	MenuItemModifyOtherKeysMode2     = "Terminal State.Report Modifiers like xterm 2"
	MenuItemCSIuMode                 = "Terminal State.Report Modifiers with CSI u"
	MenuItemRawKeyReportingMode      = "Terminal State.Raw Key Reporting"
	MenuItemResetTerminalState       = "Reset Terminal State"

	MenuItemBurySession = "Bury Session"

	// ---- Scripts > Manage ----
	MenuItemNewPythonScript       = "New Python Script"
	MenuItemOpenPythonREPL        = "Open Interactive Window"
	MenuItemManageDependencies    = "Manage Dependencies"
	MenuItemInstallPythonRuntime  = "Install Python Runtime"
	MenuItemRevealScriptsInFinder = "Reveal in Finder"
	MenuItemScriptsImport         = "Import Script"
	MenuItemScriptsExport         = "Export Script"
	MenuItemScriptsConsole        = "Script Console"

	// ---- Profiles ----
	MenuItemOpenProfiles            = "Open Profiles…"
	MenuItemPressOptionForNewWindow = "Press Option for New Window"
	MenuItemOpenInNewWindow         = "Open In New Window"

	// ---- Toolbelt ----
	MenuItemShowToolbelt    = "Show Toolbelt"
	MenuItemSetDefaultWidth = "Set Default Width"

	// ---- Window ----
	MenuItemMinimize        = "Minimize"
	MenuItemZoom            = "Zoom"
	MenuItemEditTabTitle    = "Edit Tab Title"
	MenuItemEditWindowTitle = "Edit Window Title"

	// Window > WindowStyle
	MenuItemWindowStyleNormal          = "Window Style.Normal"
	MenuItemWindowStyleFullScreen      = "Window Style.Full Screen"
	MenuItemWindowStyleMaximized       = "Window Style.Maximized"
	MenuItemWindowStyleNoTitleBar      = "Window Style.No Title Bar"
	MenuItemWindowStyleFullWidthBottom = "Window Style.FullWidth Bottom of Screen"
	MenuItemWindowStyleFullWidthTop    = "Window Style.FullWidth Top of Screen"
	MenuItemWindowStyleFullHeightLeft  = "Window Style..FullHeight Left of Screen"
	MenuItemWindowStyleFullHeightRight = "Window Style.FullHeight Right of Screen"
	MenuItemWindowStyleBottom          = "Window Style.Bottom of Screen"
	MenuItemWindowStyleTop             = "Window Style.Top of Screen"
	MenuItemWindowStyleLeft            = "Window Style.Left of Screen"
	MenuItemWindowStyleRight           = "Window Style.Right of Screen"

	MenuItemMergeAllWindows                = "Merge All Windows"
	MenuItemArrangeWindowsHorizontally     = "Arrange Windows Horizontally"
	MenuItemArrangeSplitPanesEvenly        = "Arrange Split Panes Evenly"
	MenuItemMoveSessionToWindow            = "Move Session to Window"
	MenuItemSaveWindowArrangement          = "Save Window Arrangement"
	MenuItemSaveCurrentWindowAsArrangement = "Save Current Window as Arrangement"

	// Window > SelectSplitPane
	MenuItemSelectPaneAbove    = "Select Split Pane.Select Pane Above"
	MenuItemSelectPaneBelow    = "Select Split Pane.Select Pane Below"
	MenuItemSelectPaneLeft     = "Select Split Pane.Select Pane Left"
	MenuItemSelectPaneRight    = "Select Split Pane.Select Pane Right"
	MenuItemSelectNextPane     = "Select Split Pane.Next Pane"
	MenuItemSelectPreviousPane = "Select Split Pane.Previous Pane"

	// Window > ResizeSplitPane
	MenuItemMoveDividerUp    = "Resize Split Pane.Move Divider Up"
	MenuItemMoveDividerDown  = "Resize Split Pane.Move Divider Down"
	MenuItemMoveDividerLeft  = "Resize Split Pane.Move Divider Left"
	MenuItemMoveDividerRight = "Resize Split Pane.Move Divider Right"

	// Window > ResizeWindow
	MenuItemResizeDecreaseHeight = "Resize Window.Decrease Height"
	MenuItemResizeIncreaseHeight = "Resize Window.Increase Height"
	MenuItemResizeDecreaseWidth  = "Resize Window.Decrease Width"
	MenuItemResizeIncreaseWidth  = "Resize Window.Increase Width"

	MenuItemSelectNextTab     = "Select Next Tab"
	MenuItemSelectPreviousTab = "Select Previous Tab"
	MenuItemMoveTabLeft       = "Move Tab Left"
	MenuItemMoveTabRight      = "Move Tab Right"
	MenuItemPasswordManager   = "Password Manager"
	MenuItemPinHotkeyWindow   = "Pin Hotkey Window"
	MenuItemBringAllToFront   = "Bring All To Front"

	// ---- Help ----
	MenuItemITerm2Help              = "iTerm2 Help"
	MenuItemCopyModeShortcuts       = "Copy Mode Shortcuts"
	MenuItemOpenSourceLicenses      = "Open Source Licenses"
	MenuItemGPURendererAvailability = "GPU Renderer Availability"
)
View Source
const (
	BounceUntilActivated = 0
	BounceOnce           = 1
)
View Source
const (
	BufferInputStart = 0
	BufferInputStop  = 1
)
View Source
const (
	ExitCodeAny     = "*"
	ExitCodeSuccess = "0"
	ExitCodeNonZero = "!0"
)
View Source
const (
	ProgressAny         = "*"
	ProgressAppeared    = "appeared"
	ProgressDisappeared = "disappeared"
)

Variables

This section is empty.

Functions

func Activate

func Activate(ctx context.Context, caller Caller, sessionID string, orderWindowFront bool, selectTab bool, opts ...ActivateOption) error

Activate activates a session/tab/window/app.

func CheckboxKnob

func CheckboxKnob(key string, defaultValue bool) (string, string)

CheckboxKnob returns a (key, value) pair for a checkbox knob.

func Close

func Close(ctx context.Context, caller Caller, sessionID string, opts ...CloseOption) error

Close closes a session, tab, or window.

func CloseForce

func CloseForce(ctx context.Context, caller Caller, sessionID string) error

CloseForce closes a session with force=true. This is a convenience function equivalent to Close(ctx, caller, sessionID, WithCloseForce(true)).

func ColorKnob

func ColorKnob(key string, colorJSON string) (string, string)

ColorKnob returns a (key, value) pair for a color knob. The value should be a JSON-encoded color (e.g., from Color.JSON()).

func CreateTab

func CreateTab(ctx context.Context, caller Caller, windowID string, profileName string, opts ...CreateTabOption) (*iterm2.CreateTabResponse, error)

CreateTab creates a new tab.

func EachSessionOnce deprecated

func EachSessionOnce(conn *Connection, fn func(session *Session) error)

EachSessionOnce calls fn exactly once for every session — including those that already exist and those created in the future. It subscribes to new session notifications on the connection so the callback fires automatically when a new session appears.

Already-seen session IDs are tracked internally so fn is never called more than once for the same session.

Errors returned by fn are logged and do not interrupt processing.

Deprecated: Use EachSessionOnceCtx instead for proper cancellation support.

func EachSessionOnceCtx

func EachSessionOnceCtx(ctx context.Context, conn *Connection, fn func(session *Session) error)

EachSessionOnceCtx is like EachSessionOnce but accepts a context for cancellation. Pass ctx.Done() to stop processing new sessions.

func EnumerateRanges

func EnumerateRanges(
	sel *iterm2.Selection,
	fn func(start, end Coord) error,
) error

EnumerateRanges iterates over a selected range, calling fn for each line-contiguous sub-selection.

func ExitCodeFilter

func ExitCodeFilter(code int) string

ExitCodeFilter returns an exit-code filter string from an int.

func FloatKnob

func FloatKnob(key string, defaultValue float64) (string, string)

FloatKnob returns a (key, value) pair for a float knob. The value is JSON-encoded.

func FocusRequest

func FocusRequest(ctx context.Context, caller Caller) (*iterm2.FocusResponse, error)

FocusRequest returns information about the currently focused element.

func GetBuffer

func GetBuffer(ctx context.Context, caller Caller, sessionID string, lineRange *iterm2.LineRange, opts ...GetBufferOption) (*iterm2.GetBufferResponse, error)

GetBuffer returns the contents of a session's buffer.

func GetCookieOrCreate

func GetCookieOrCreate(scriptName string) (cookie, key string, err error)

GetCookieOrCreate returns credentials, trying env var first then AppleScript.

func GetProfileProperty

func GetProfileProperty(ctx context.Context, caller Caller, sessionID string, keys []string) (*iterm2.GetProfilePropertyResponse, error)

GetProfileProperty gets a profile property.

func GetPrompt

func GetPrompt(ctx context.Context, caller Caller, sessionID string, opts ...GetPromptOption) (*iterm2.GetPromptResponse, error)

GetPrompt returns prompt metadata for a session.

func GetProperty

func GetProperty(ctx context.Context, caller Caller, sessionID string, name string) (*iterm2.GetPropertyResponse, error)

GetProperty gets a property from a window or session.

func GetSelection

func GetSelection(ctx context.Context, caller Caller, sessionID string) (*iterm2.SelectionResponse_GetSelectionResponse, error)

GetSelection returns the current text selection in a session.

func GetVariable

func GetVariable(ctx context.Context, caller Caller, sessionID string, names []string) ([]string, error)

GetVariable gets session variables.

func Inject

func Inject(ctx context.Context, caller Caller, sessionIDs []string, data []byte) error

Inject injects bytes directly into the terminal. sessionIDs must not be empty.

func InvokeFunction

InvokeFunction invokes a registered function.

func ListColorPresets

func ListColorPresets(ctx context.Context, caller Caller) ([]string, error)

ListColorPresets returns the names of all available color presets.

func ListProfiles

func ListProfiles(ctx context.Context, caller Caller, properties []string, guids []string) (*iterm2.ListProfilesResponse, error)

ListProfiles lists all available profiles.

func ListPromptIDs

func ListPromptIDs(ctx context.Context, caller Caller, sessionID, first, last string) ([]string, error)

ListPromptIDs returns a list of prompt IDs for a session, optionally bounded by first/last.

func ListPrompts

func ListPrompts(ctx context.Context, caller Caller, sessionID string, opts ...ListPromptsOption) (*iterm2.ListPromptsResponse, error)

ListPrompts lists all prompts for a session.

func ListSessions

func ListSessions(ctx context.Context, caller Caller) (*iterm2.ListSessionsResponse, error)

ListSessions returns a list of all sessions.

func MarkNoStopScrolling

func MarkNoStopScrolling() string

MarkNoStopScrolling returns the param value for a MarkTrigger without stop scrolling.

func MarkStopScrolling

func MarkStopScrolling() string

MarkStopScrolling returns the param value for a MarkTrigger with stop scrolling.

func NotificationRequest

func NotificationRequest(ctx context.Context, caller Caller, subscribe bool, notificationType iterm2.NotificationType,
	sessionID string,
) (*iterm2.NotificationResponse, error)

NotificationRequest sends a notification subscription request.

func OpenStatusBarPopover

func OpenStatusBarPopover(ctx context.Context, caller Caller, identifier, sessionID, html string, width, height int32) error

OpenStatusBarPopover opens a popover with HTML content from a status bar component.

func PreferencesRequest

func PreferencesRequest(ctx context.Context, caller Caller, req *iterm2.PreferencesRequest) (*iterm2.PreferencesResponse, error)

PreferencesRequest gets or sets preferences.

func RegisterStatusBarComponent

func RegisterStatusBarComponent(ctx context.Context, caller Caller, component StatusBarComponent) error

RegisterStatusBarComponent registers a status bar component with iTerm2.

func RestartSession

func RestartSession(ctx context.Context, caller Caller, sessionID string, opts ...RestartSessionOption) error

RestartSession restarts a session.

func RestartSessionIfExited

func RestartSessionIfExited(ctx context.Context, caller Caller, sessionID string) error

RestartSessionIfExited restarts a session only if it has exited. This is a convenience function equivalent to RestartSession(ctx, caller, sessionID, WithRestartOnlyIfExited(true)).

func Run

func Run(ctx context.Context, scriptName string, fn func(caller Caller) error) error

Run connects to iTerm2, executes fn with the connection as a Caller, and closes the connection when fn returns. scriptName identifies this program in iTerm2's scripting console.

func SavedArrangementRequest

func SavedArrangementRequest(ctx context.Context, caller Caller, req *iterm2.SavedArrangementRequest) (*iterm2.SavedArrangementResponse, error)

SavedArrangementRequest manages saved window arrangements.

func SelectMenuItem

func SelectMenuItem(ctx context.Context, caller Caller, identifier string) error

SelectMenuItem selects a menu item by its identifier string.

func SelectionRequest

func SelectionRequest(ctx context.Context, caller Caller, sessionID string) (*iterm2.SelectionResponse, error)

SelectionRequest returns the current selection.

func SendText

func SendText(ctx context.Context, caller Caller, sessionID string, text string, opts ...SendTextOption) error

SendText sends text to a session as if typed.

func SendTextNoBroadcast

func SendTextNoBroadcast(ctx context.Context, caller Caller, sessionID string, text string) error

SendTextNoBroadcast sends text to a session with suppress_broadcast=true. This is a convenience function equivalent to SendText(ctx, caller, sessionID, text, WithSendTextSuppressBroadcast(true)).

func ServerOriginatedRPCResultRequest

func ServerOriginatedRPCResultRequest(ctx context.Context, caller Caller, req *iterm2.ServerOriginatedRPCResultRequest) error

ServerOriginatedRPCResultRequest sends the result of a server-originated RPC.

func SetBuried

func SetBuried(ctx context.Context, caller Caller, sessionID string, buried bool) error

SetBuried sets or unsets the buried (minimized) state of a session.

func SetGridSize

func SetGridSize(ctx context.Context, caller Caller, sessionID string, width, height int32) error

SetGridSize sets the visible grid size of a session.

func SetProfileProperty

func SetProfileProperty(ctx context.Context, caller Caller, sessionID string, key string, jsonValue string) error

SetProfileProperty sets a profile property.

func SetProperty

func SetProperty(ctx context.Context, caller Caller, sessionID string, name string, jsonValue string) error

SetProperty sets a property on a window or session.

func SetSelection

func SetSelection(ctx context.Context, caller Caller, sessionID string, selection *iterm2.Selection) error

SetSelection sets the selection on a session.

func SetTabLayout

func SetTabLayout(ctx context.Context, caller Caller, tabID string, root *iterm2.SplitTreeNode) error

SetTabLayout adjusts the split-pane sizes of a tab. The root tree must match the tab's actual split structure exactly (only grid_sizes may change).

func SetTriggers

func SetTriggers(ctx context.Context, caller Caller, sessionID string, triggers []*Trigger) error

SetTriggers writes triggers to the session's profile.

func SetVariable

func SetVariable(ctx context.Context, caller Caller, sessionID string, name string, value string) error

SetVariable sets a session variable.

func ShowAlert

func ShowAlert(ctx context.Context, caller Caller, title, message string, buttons []string) (int, error)

ShowAlert displays a modal alert with buttons. Returns the button index (0-based).

func ShowOpenPanel

func ShowOpenPanel(ctx context.Context, caller Caller, title, initialPath string) (string, error)

ShowOpenPanel displays an open file panel and returns selected files.

func ShowSavePanel

func ShowSavePanel(ctx context.Context, caller Caller, title, initialPath string) (string, error)

ShowSavePanel displays a save file panel and returns the selected path.

func ShowTextInputAlert

func ShowTextInputAlert(ctx context.Context, caller Caller, title, message, defaultValue string) (string, error)

ShowTextInputAlert displays a modal alert with a text field. Returns the entered text.

func SplitPane

func SplitPane(ctx context.Context, caller Caller, sessionID string, vertical bool, before bool,
	profileName string, opts ...SplitPaneOption,
) (*iterm2.SplitPaneResponse, error)

SplitPane splits a session's pane.

func StringKnob

func StringKnob(key string, defaultValue string) (string, string)

StringKnob returns a (key, value) pair for a string knob. The value is JSON-encoded.

func SupportsAddAnnotation

func SupportsAddAnnotation(conn *Connection) bool

SupportsAddAnnotation checks if annotations can be added (requires proto version >= 1.8).

func SupportsAdvancedKeyNotifications

func SupportsAdvancedKeyNotifications(conn *Connection) bool

SupportsAdvancedKeyNotifications checks if advanced keystroke notifications (key-up, flags-changed) are available (requires proto version >= 1.9).

func SupportsAdvancedKeyUp

func SupportsAdvancedKeyUp(conn *Connection) bool

SupportsAdvancedKeyUp is an alias for SupportsAdvancedKeyNotifications.

func SupportsApplyLayout

func SupportsApplyLayout(conn *Connection) bool

SupportsApplyLayout checks if App.apply_layout() is available (requires proto version >= 1.14).

func SupportsApplyLayoutNewSession

func SupportsApplyLayoutNewSession(conn *Connection) bool

SupportsApplyLayoutNewSession checks if apply_layout can create new sessions inline via new_session leaves (requires proto version >= 1.16).

func SupportsContextMenuProviders

func SupportsContextMenuProviders(conn *Connection) bool

SupportsContextMenuProviders checks if context menu providers can be registered (requires proto version >= 1.7).

func SupportsCoprocesses

func SupportsCoprocesses(conn *Connection) bool

SupportsCoprocesses checks if coprocess manipulation is available (requires proto version >= 1.3).

func SupportsFeature

func SupportsFeature(conn *Connection, min ProtocolVersion) bool

SupportsFeature checks if the connected iTerm2 supports a feature requiring at least the given protocol version.

func SupportsFilePanels

func SupportsFilePanels(conn *Connection) bool

SupportsFilePanels checks if open/save panels can be used (requires proto version >= 1.10).

func SupportsGetDefaultProfile

func SupportsGetDefaultProfile(conn *Connection) bool

SupportsGetDefaultProfile checks if the default profile can be retrieved (requires proto version >= 1.4).

func SupportsListSavedArrangements

func SupportsListSavedArrangements(conn *Connection) bool

SupportsListSavedArrangements checks if saved arrangements can be listed (requires proto version >= 1.6).

func SupportsLoadURL

func SupportsLoadURL(conn *Connection) bool

SupportsLoadURL checks if URLs can be loaded in browser sessions (requires proto version >= 1.12).

func SupportsMoveSession

func SupportsMoveSession(conn *Connection) bool

SupportsMoveSession checks if sessions can be moved to split panes (requires proto version >= 1.11).

func SupportsMoveSessionToTabOrWindow

func SupportsMoveSessionToTabOrWindow(conn *Connection) bool

SupportsMoveSessionToTabOrWindow checks if sessions can be moved to new tabs or windows (requires proto version >= 1.13).

func SupportsMultipleSetProfile

func SupportsMultipleSetProfile(conn *Connection) bool

SupportsMultipleSetProfile checks if multiple profile properties can be set in a single call (requires proto version >= 0.69).

func SupportsPromptExcludedSubranges

func SupportsPromptExcludedSubranges(conn *Connection) bool

SupportsPromptExcludedSubranges checks if prompt responses include excluded subranges (PS2 prefixes, right-prompt cells) (requires proto version >= 1.15).

func SupportsPromptID

func SupportsPromptID(conn *Connection) bool

SupportsPromptID checks if prompts can be listed or fetched by ID (requires proto version >= 1.5).

func SupportsPromptMonitorModes

func SupportsPromptMonitorModes(conn *Connection) bool

SupportsPromptMonitorModes checks if different prompt monitor modes are available (requires proto version >= 1.1).

func SupportsSelectPaneInDirection

func SupportsSelectPaneInDirection(conn *Connection) bool

SupportsSelectPaneInDirection checks if pane direction selection (left/right/up/down) is available (requires proto version >= 1.0).

func SupportsStatusBarUnreadCount

func SupportsStatusBarUnreadCount(conn *Connection) bool

SupportsStatusBarUnreadCount checks if the status bar can show an unread count (requires proto version >= 1.2).

func TmuxRequest

func TmuxRequest(ctx context.Context, caller Caller, req *iterm2.TmuxRequest) (*iterm2.TmuxResponse, error)

TmuxRequest sends a tmux command.

Types

type ActivateOption

type ActivateOption func(*iterm2.ActivateRequest)

ActivateOption is an option for Activate.

func WithActivateApp

func WithActivateApp(raiseAllWindows, ignoringOtherApps bool) ActivateOption

WithActivateApp also activates the app.

func WithSelectSession

func WithSelectSession() ActivateOption

WithSelectSession selects the session in addition to the tab.

type App

type App struct {
	Windows []*Window
	// contains filtered or unexported fields
}

App represents the iTerm2 application. It holds all terminal windows and provides the entry point for navigating the session hierarchy.

func GetApp

func GetApp(ctx context.Context, caller Caller) (*App, error)

GetApp retrieves the full iTerm2 session hierarchy by calling ListSessions and constructing the object tree from the response.

func (*App) Refresh

func (a *App) Refresh(ctx context.Context) error

Refresh reloads the full window/tab/session hierarchy from iTerm2.

type AppleScriptAuthProvider

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

AppleScriptAuthProvider obtains credentials via osascript.

func NewAppleScriptAuthProvider

func NewAppleScriptAuthProvider(scriptName string) *AppleScriptAuthProvider

func (*AppleScriptAuthProvider) GetCookie

func (p *AppleScriptAuthProvider) GetCookie() (string, error)

func (*AppleScriptAuthProvider) GetKey

func (p *AppleScriptAuthProvider) GetKey() (string, error)

type AuthProvider

type AuthProvider interface {
	GetCookie() (string, error)
	GetKey() (string, error)
}

AuthProvider provides authentication credentials.

type BindingAction

type BindingAction int

BindingAction represents an action triggered by a key binding in iTerm2. Values match the Python iterm2.BindingAction enum.

const (
	ActionNextSession                  BindingAction = 0
	ActionNextWindow                   BindingAction = 1
	ActionPreviousSession              BindingAction = 2
	ActionPreviousWindow               BindingAction = 3
	ActionScrollEnd                    BindingAction = 4
	ActionScrollHome                   BindingAction = 5
	ActionScrollLineDown               BindingAction = 6
	ActionScrollLineUp                 BindingAction = 7
	ActionScrollPageDown               BindingAction = 8
	ActionScrollPageUp                 BindingAction = 9
	ActionEscapeSequence               BindingAction = 10
	ActionHexCode                      BindingAction = 11
	ActionText                         BindingAction = 12
	ActionIgnore                       BindingAction = 13
	ActionIRBackward                   BindingAction = 15
	ActionSendCHBackspace              BindingAction = 16
	ActionSendCQMBackspace             BindingAction = 17
	ActionSelectPaneLeft               BindingAction = 18
	ActionSelectPaneRight              BindingAction = 19
	ActionSelectPaneAbove              BindingAction = 20
	ActionSelectPaneBelow              BindingAction = 21
	ActionDoNotRemapModifiers          BindingAction = 22
	ActionToggleFullscreen             BindingAction = 23
	ActionRemapLocally                 BindingAction = 24
	ActionSelectMenuItem               BindingAction = 25
	ActionNewWindowWithProfile         BindingAction = 26
	ActionNewTabWithProfile            BindingAction = 27
	ActionSplitHorizontallyWithProfile BindingAction = 28
	ActionSplitVerticallyWithProfile   BindingAction = 29
	ActionNextPane                     BindingAction = 30
	ActionPreviousPane                 BindingAction = 31
	ActionNextMRUTab                   BindingAction = 32
	ActionMoveTabLeft                  BindingAction = 33
	ActionMoveTabRight                 BindingAction = 34
	ActionRunCoprocess                 BindingAction = 35
	ActionFindRegex                    BindingAction = 36
	ActionSetProfile                   BindingAction = 37
	ActionVimText                      BindingAction = 38
	ActionPreviousMRUTab               BindingAction = 39
	ActionLoadColorPreset              BindingAction = 40
	ActionPasteSpecial                 BindingAction = 41
	ActionPasteSpecialFromSelection    BindingAction = 42
	ActionToggleHotkeyWindowPinning    BindingAction = 43
	ActionUndo                         BindingAction = 44
	ActionMoveEndOfSelectionLeft       BindingAction = 45
	ActionMoveEndOfSelectionRight      BindingAction = 46
	ActionMoveStartOfSelectionLeft     BindingAction = 47
	ActionMoveStartOfSelectionRight    BindingAction = 48
	ActionDecreaseHeight               BindingAction = 49
	ActionIncreaseHeight               BindingAction = 50
	ActionDecreaseWidth                BindingAction = 51
	ActionIncreaseWidth                BindingAction = 52
	ActionSwapPaneLeft                 BindingAction = 53
	ActionSwapPaneRight                BindingAction = 54
	ActionSwapPaneAbove                BindingAction = 55
	ActionSwapPaneBelow                BindingAction = 56
	ActionFindAgainDown                BindingAction = 57
	ActionFindAgainUp                  BindingAction = 58
	ActionToggleMouseReporting         BindingAction = 59
	ActionInvokeScriptFunction         BindingAction = 60
	ActionDuplicateTab                 BindingAction = 61
	ActionMoveToSplitPane              BindingAction = 62
	ActionSendSnippet                  BindingAction = 63
)

type Caller

Caller abstracts the ability to make RPC calls to iTerm2.

type CellStyle

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

CellStyle wraps a proto CellStyle with convenience accessors.

func (*CellStyle) BGAlternate

func (c *CellStyle) BGAlternate() (iterm2.AlternateColor, bool)

BGAlternate returns the alternate background color.

func (*CellStyle) BGPlacementY

func (c *CellStyle) BGPlacementY() (uint32, bool)

BGPlacementY returns the alternate-placement-y background value.

func (*CellStyle) BGRGB

func (c *CellStyle) BGRGB() (*iterm2.RGBColor, bool)

BGRGB returns the RGB background color.

func (*CellStyle) BGStandard

func (c *CellStyle) BGStandard() (uint32, bool)

BGStandard returns the standard background color.

func (c *CellStyle) Blink() bool

func (*CellStyle) BlockID

func (c *CellStyle) BlockID() string

BlockID returns the block ID string.

func (*CellStyle) Bold

func (c *CellStyle) Bold() bool

func (*CellStyle) FGAlternate

func (c *CellStyle) FGAlternate() (iterm2.AlternateColor, bool)

FGAlternate returns the alternate (semantic) foreground color.

func (*CellStyle) FGPlacementX

func (c *CellStyle) FGPlacementX() (uint32, bool)

FGPlacementX returns the alternate-placement-x foreground value.

func (*CellStyle) FGRGB

func (c *CellStyle) FGRGB() (*iterm2.RGBColor, bool)

FGRGB returns the RGB foreground color.

func (*CellStyle) FGStandard

func (c *CellStyle) FGStandard() (uint32, bool)

FGStandard returns the standard (palette-indexed) foreground color.

func (*CellStyle) Faint

func (c *CellStyle) Faint() bool

func (*CellStyle) Guarded

func (c *CellStyle) Guarded() bool

func (*CellStyle) HasBG

func (c *CellStyle) HasBG() bool

HasBG reports whether background color is set.

func (*CellStyle) HasFG

func (c *CellStyle) HasFG() bool

HasFG reports whether foreground color is set.

func (*CellStyle) Image

Image returns the image placeholder type.

func (*CellStyle) Inverse

func (c *CellStyle) Inverse() bool

func (*CellStyle) Invisible

func (c *CellStyle) Invisible() bool

func (*CellStyle) Italic

func (c *CellStyle) Italic() bool

func (*CellStyle) Strikethrough

func (c *CellStyle) Strikethrough() bool

func (*CellStyle) URL

func (c *CellStyle) URL() (url, identifier string, ok bool)

URL returns the URL and identifier if set.

func (*CellStyle) Underline

func (c *CellStyle) Underline() bool

func (*CellStyle) UnderlineRGB

func (c *CellStyle) UnderlineRGB() (*iterm2.RGBColor, bool)

UnderlineRGB returns the underline color if set.

type CloseOption

type CloseOption func(*iterm2.CloseRequest)

CloseOption is an option for Close.

func WithCloseForce

func WithCloseForce(force bool) CloseOption

WithCloseForce forces the close without confirmation.

func WithCloseTabs

func WithCloseTabs(tabIDs []string) CloseOption

WithCloseTabs closes tabs instead of sessions.

func WithCloseWindows

func WithCloseWindows(windowIDs []string) CloseOption

WithCloseWindows closes windows instead of sessions.

type Color

type Color struct {
	Red        float64
	Green      float64
	Blue       float64
	Alpha      float64
	ColorSpace string
}

Color represents a terminal color with optional alpha and color space.

func NewColor

func NewColor(r, g, b float64) *Color

NewColor creates a Color with full opacity (alpha=255) in the sRGB color space.

func NewColorWithAlpha

func NewColorWithAlpha(r, g, b, a float64) *Color

NewColorWithAlpha creates a Color with the specified alpha in the sRGB color space.

func NewColorWithColorSpace

func NewColorWithColorSpace(r, g, b float64, cs string) *Color

NewColorWithColorSpace creates a Color with the specified color space and full opacity.

type ColorPreset

type ColorPreset struct {
	Name   string
	Colors map[string]*Color
}

ColorPreset is a named collection of colors for terminal attributes.

func GetColorPreset

func GetColorPreset(ctx context.Context, caller Caller, name string) (*ColorPreset, error)

GetColorPreset fetches a color preset by name.

type Connection

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

Connection manages the WebSocket connection to iTerm2.

func Connect

func Connect(ctx context.Context, scriptName string) (*Connection, error)

Connect is a convenience function.

func NewConnection

func NewConnection(cookie, key, scriptName string, opts ...Option) *Connection

NewConnection creates a new Connection with optional configuration.

func (*Connection) Call

Call implements Caller.

func (*Connection) Close

func (c *Connection) Close() error

Close closes the WebSocket connection. Safe to call multiple times.

func (*Connection) ConnType

func (c *Connection) ConnType() string

ConnType returns the connection type.

func (*Connection) Connect

func (c *Connection) Connect(ctx context.Context) error

Connect establishes the WebSocket connection and starts the dispatch loop.

func (*Connection) ConnectWithWS

func (c *Connection) ConnectWithWS(ctx context.Context, conn wsConn)

ConnectWithWS sets a pre-established WebSocket for testing.

func (*Connection) Cookie

func (c *Connection) Cookie() string

Cookie returns the cookie.

func (*Connection) Dispatch

func (c *Connection) Dispatch(msg *iterm2.ServerOriginatedMessage)

Dispatch routes an incoming ServerOriginatedMessage that carries a Notification to every matching subscribed handler on this connection.

The caller is responsible for feeding notifications to this function, for example by registering a wrapper handler on a Connection:

conn.RegisterHandler(func(msg *iterm2.ServerOriginatedMessage) bool {
    conn.Dispatch(msg)
    return true
})

func (*Connection) IsConnected

func (c *Connection) IsConnected() bool

IsConnected reports whether the WebSocket connection is still active.

func (*Connection) Key

func (c *Connection) Key() string

Key returns the key.

func (*Connection) OnDisconnect

func (c *Connection) OnDisconnect(fn func())

OnDisconnect registers a callback that fires when the WebSocket connection is lost. Multiple callbacks can be registered; they are invoked in order.

func (*Connection) ProtocolVersion

func (c *Connection) ProtocolVersion() ProtocolVersion

ProtocolVersion returns the iTerm2 protocol version from the handshake. Defaults to (0,0) which means no features are gated behind version checks.

func (*Connection) RegisterHandler

func (c *Connection) RegisterHandler(h NotificationHandler)

RegisterHandler implements Notifier.

func (*Connection) Send

Send implements Caller.

func (*Connection) SetProtocolVersion

func (c *Connection) SetProtocolVersion(v ProtocolVersion)

SetProtocolVersion sets the protocol version (for testing or manual override).

func (*Connection) UnregisterHandler

func (c *Connection) UnregisterHandler(h NotificationHandler)

UnregisterHandler implements Notifier.

func (*Connection) Unsubscribe

func (c *Connection) Unsubscribe(token NotificationToken)

Unsubscribe removes a previously registered notification handler and, if it was the last handler for its key, sends an unsubscribe RPC to iTerm2.

type Coord

type Coord struct {
	X, Y int32
}

Coord represents a terminal coordinate (column, line).

func CoordFromProto

func CoordFromProto(c *iterm2.Coord) Coord

CoordFromProto converts a proto Coord to a native Coord. Note: proto Y is int64 (line numbers can exceed int32 range for long scrollback), but native Coord uses int32 for both fields. Values beyond int32 range are truncated.

type CoordRange

type CoordRange struct {
	Start, End Coord
}

CoordRange represents a range of coordinates.

func CoordRangeFromProto

func CoordRangeFromProto(cr *iterm2.CoordRange) CoordRange

CoordRangeFromProto converts a proto CoordRange to a native CoordRange.

type CreateTabOption

type CreateTabOption func(*iterm2.CreateTabRequest)

CreateTabOption is an option for CreateTab.

func WithCustomProfileProperties

func WithCustomProfileProperties(props []*iterm2.ProfileProperty) CreateTabOption

WithCustomProfileProperties modifies the profile to customize its behavior just for this session.

func WithTabIndex

func WithTabIndex(idx uint32) CreateTabOption

WithTabIndex sets the desired index of the new tab. Only valid if the tab is being created in an existing window (windowID is set).

type CustomControlSequenceMonitor

type CustomControlSequenceMonitor struct {
	C chan []string // regex match groups
	// contains filtered or unexported fields
}

CustomControlSequenceMonitor watches for custom control sequences matching an identity and regex pattern. Corresponds to Python's CustomControlSequenceMonitor.

Usage:

mon := NewCustomControlSequenceMonitor(conn, "shared-secret", `^open$`, "")
mon.Start(ctx, caller)
for match := range mon.C {
    fmt.Println(match[0])
}
defer mon.Stop(ctx, caller)

func NewCustomControlSequenceMonitor

func NewCustomControlSequenceMonitor(conn *Connection, identity, pattern, sessionID string) (*CustomControlSequenceMonitor, error)

NewCustomControlSequenceMonitor creates a monitor. sessionID can be empty to watch all sessions.

func (*CustomControlSequenceMonitor) Start

Start subscribes to custom escape sequence notifications and begins filtering.

func (*CustomControlSequenceMonitor) Stop

func (m *CustomControlSequenceMonitor) Stop(caller Caller) error

Stop unsubscribes from notifications and closes the channel.

type EnvAuthProvider

type EnvAuthProvider struct{}

EnvAuthProvider reads ITERM2_COOKIE / ITERM2_KEY.

func (*EnvAuthProvider) GetCookie

func (p *EnvAuthProvider) GetCookie() (string, error)

func (*EnvAuthProvider) GetKey

func (p *EnvAuthProvider) GetKey() (string, error)

type FocusMonitor

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

FocusMonitor streams focus-change events. Create one with NewFocusMonitor, iterate over Chan(), and call Close() when finished.

func NewFocusMonitor

func NewFocusMonitor(conn *Connection) (*FocusMonitor, error)

NewFocusMonitor subscribes to focus-change notifications.

Usage:

fm, err := NewFocusMonitor(conn)
if err != nil { ... }
defer fm.Close()
for u := range fm.Chan() {
    if u.ApplicationActive != nil {
        fmt.Println("app active:", *u.ApplicationActive)
    }
    if u.WindowChanged != nil {
        fmt.Println("window:", u.WindowChanged.WindowID)
    }
}

func (*FocusMonitor) Chan

func (fm *FocusMonitor) Chan() <-chan *FocusUpdate

Chan returns a receive-only channel of FocusUpdates.

func (*FocusMonitor) Close

func (fm *FocusMonitor) Close()

Close stops the monitor and unsubscribes. Safe to call multiple times.

type FocusUpdate

type FocusUpdate struct {
	// ApplicationActive is set when the app becomes/resigns active.
	// true = application became active; false = resigned active.
	ApplicationActive *bool

	// WindowChanged reports a window focus change.
	WindowChanged *WindowFocusChange

	// SelectedTab is the tab ID that became selected (non-nil when set).
	SelectedTab *string

	// ActiveSession is the session ID that became active (non-nil when set).
	ActiveSession *string
}

FocusUpdate is produced by FocusMonitor on each focus change. Exactly one field will be non-nil/non-zero.

type GetBufferOption

type GetBufferOption func(*iterm2.GetBufferRequest)

GetBufferOption is an option for GetBuffer.

func WithIncludeStyles

func WithIncludeStyles() GetBufferOption

WithIncludeStyles populates the style field of LineContents in the response.

type GetPromptOption

type GetPromptOption func(*iterm2.GetPromptRequest)

GetPromptOption is an option for GetPrompt.

func WithUniquePromptID

func WithUniquePromptID(id string) GetPromptOption

WithUniquePromptID returns the prompt with the given ID instead of the last one.

type KeystrokeAction

type KeystrokeAction int

KeystrokeAction describes the type of keyboard event.

const (
	KeystrokeKeyDown      KeystrokeAction = 0
	KeystrokeKeyUp        KeystrokeAction = 1
	KeystrokeFlagsChanged KeystrokeAction = 2
)

type KeystrokeEvent

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

KeystrokeEvent wraps a KeystrokeNotification with convenience accessors.

func (*KeystrokeEvent) Action

func (k *KeystrokeEvent) Action() KeystrokeAction

Action returns the keystroke action (key down / key up / flags changed).

func (*KeystrokeEvent) Characters

func (k *KeystrokeEvent) Characters() string

Characters returns the characters produced by the keystroke.

func (*KeystrokeEvent) CharactersIgnoringModifiers

func (k *KeystrokeEvent) CharactersIgnoringModifiers() string

CharactersIgnoringModifiers returns the characters ignoring modifier keys.

func (*KeystrokeEvent) KeyCode

func (k *KeystrokeEvent) KeyCode() int32

KeyCode returns the virtual key code.

func (*KeystrokeEvent) Modifiers

func (k *KeystrokeEvent) Modifiers() []iterm2.Modifiers

Modifiers returns the modifier flags.

func (*KeystrokeEvent) Raw

Raw returns the underlying proto notification.

func (*KeystrokeEvent) Session

func (k *KeystrokeEvent) Session() string

Session returns the session ID where the keystroke occurred.

type KeystrokeFilter

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

KeystrokeFilter tells iTerm2 to intercept keystrokes matching the given patterns. Intercepted keystrokes are not delivered to the terminal but are still sent as KeystrokeNotifications — use a KeystrokeMonitor to receive them.

The filter is active from creation until Close() is called.

func NewKeystrokeFilter

func NewKeystrokeFilter(conn *Connection, sessionID string, patterns []*iterm2.KeystrokePattern) (*KeystrokeFilter, error)

NewKeystrokeFilter subscribes the KEYSTROKE_FILTER with the given patterns. sessionID may be "" to filter keystrokes in all sessions.

func (*KeystrokeFilter) Close

func (kf *KeystrokeFilter) Close()

Close removes the filter. Safe to call multiple times.

type KeystrokeMonitor

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

KeystrokeMonitor streams keystroke events from a session. Pass sessionID == "" to monitor all sessions.

By default, only key-down events are received. Pass advanced=true to also receive key-up and flags-changed events.

func NewKeystrokeMonitor

func NewKeystrokeMonitor(conn *Connection, sessionID string, advanced bool) (*KeystrokeMonitor, error)

NewKeystrokeMonitor subscribes to keystroke notifications. If advanced is true, key-up and flags-changed events are included.

Usage:

km, err := NewKeystrokeMonitor(conn, "s1", true)
defer km.Close()
for ev := range km.Chan() {
    fmt.Printf("key: %s mods: %v\n", ev.Characters(), ev.Modifiers())
}

func (*KeystrokeMonitor) Chan

func (km *KeystrokeMonitor) Chan() <-chan *KeystrokeEvent

Chan returns a receive-only channel of KeystrokeEvents.

func (*KeystrokeMonitor) Close

func (km *KeystrokeMonitor) Close()

Close stops the monitor. Safe to call multiple times.

type LineContent

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

LineContent wraps a LineContents proto, pre-computing per-cell offsets so callers can do random-access lookups by column.

func (*LineContent) HardEOL

func (l *LineContent) HardEOL() bool

HardEOL reports whether the line ends with a hard (explicit) newline.

func (*LineContent) Len

func (l *LineContent) Len() int

Len returns the number of cells in this line.

func (*LineContent) RuneAt

func (l *LineContent) RuneAt(col int) (rune, int)

RuneAt returns the first rune at column col and its byte length, or (0,0).

func (*LineContent) StyleAt

func (l *LineContent) StyleAt(col int) *CellStyle

StyleAt returns the cell style at column col, or nil if no style info or col is out of bounds.

func (*LineContent) Text

func (l *LineContent) Text() string

Text returns the raw text content of the line.

type LineInfo

type LineInfo struct {
	MutableAreaHeight      int // Visible grid rows
	ScrollbackBufferHeight int // History lines
	Overflow               int // Lines lost to overflow
	FirstVisibleLineNumber int // First line on screen, changes on scroll
}

LineInfo describes a session's geometry, corresponding to Python's SessionLineInfo.

type ListPromptsOption

type ListPromptsOption func(*iterm2.ListPromptsRequest)

ListPromptsOption is an option for ListPrompts.

func WithFirstUniqueID

func WithFirstUniqueID(id string) ListPromptsOption

WithFirstUniqueID starts listing prompts from the given ID (exclusive).

func WithLastUniqueID

func WithLastUniqueID(id string) ListPromptsOption

WithLastUniqueID ends listing prompts at the given ID (inclusive).

type MenuItemState struct {
	Checked bool
	Enabled bool
}

MenuItemState describes the current state of a menu item.

func GetMenuItemState

func GetMenuItemState(ctx context.Context, caller Caller, identifier string) (*MenuItemState, error)

GetMenuItemState queries the state of a menu item by its identifier string.

type NotificationHandler

type NotificationHandler func(msg *iterm2.ServerOriginatedMessage) bool

NotificationHandler is a callback for incoming server notifications.

type NotificationToken

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

NotificationToken identifies a subscription so it can be unsubscribed.

func SubscribeBroadcastChange

func SubscribeBroadcastChange(ctx context.Context, caller Caller, c *Connection,
	callback func(Caller, *iterm2.BroadcastDomainsChangedNotification),
) (NotificationToken, error)

SubscribeBroadcastChange registers a callback that fires when the broadcast domains change.

func SubscribeCustomEscapeSequence

func SubscribeCustomEscapeSequence(ctx context.Context, caller Caller, c *Connection,
	callback func(Caller, *iterm2.CustomEscapeSequenceNotification), sessionID string,
) (NotificationToken, error)

SubscribeCustomEscapeSequence registers a callback that fires when a custom escape sequence (OSC 1337 ; Custom=...) is received in sessionID.

func SubscribeFocusChange

func SubscribeFocusChange(ctx context.Context, caller Caller, c *Connection,
	callback func(Caller, *iterm2.FocusChangedNotification),
) (NotificationToken, error)

SubscribeFocusChange registers a callback that fires when the focused window or session changes.

func SubscribeKeystroke

func SubscribeKeystroke(ctx context.Context, caller Caller, c *Connection,
	callback func(Caller, *iterm2.KeystrokeNotification), sessionID string,
) (NotificationToken, error)

SubscribeKeystroke registers a callback that fires when a key is pressed in sessionID. Pass sessionID == "" to monitor all sessions.

func SubscribeLayoutChange

func SubscribeLayoutChange(ctx context.Context, caller Caller, c *Connection,
	callback func(Caller, *iterm2.LayoutChangedNotification),
) (NotificationToken, error)

SubscribeLayoutChange registers a callback that fires when the window/tab layout changes.

func SubscribeNewSession

func SubscribeNewSession(ctx context.Context, caller Caller, c *Connection,
	callback func(Caller, *iterm2.NewSessionNotification),
) (NotificationToken, error)

SubscribeNewSession registers a callback that fires when a new iTerm2 session is created.

func SubscribeProfileChange

func SubscribeProfileChange(ctx context.Context, caller Caller, c *Connection,
	callback func(Caller, *iterm2.ProfileChangedNotification),
) (NotificationToken, error)

SubscribeProfileChange registers a callback that fires when a profile changes. Pass guid == "" to match all profiles.

func SubscribePrompt

func SubscribePrompt(ctx context.Context, caller Caller, c *Connection,
	callback func(Caller, *iterm2.PromptNotification), sessionID string,
) (NotificationToken, error)

SubscribePrompt registers a callback that fires when a shell prompt is detected in sessionID.

func SubscribeScreenUpdate

func SubscribeScreenUpdate(ctx context.Context, caller Caller, c *Connection,
	callback func(Caller, *iterm2.ScreenUpdateNotification), sessionID string,
) (NotificationToken, error)

SubscribeScreenUpdate registers a callback that fires when the screen contents change for sessionID. Pass sessionID == "" for all sessions.

func SubscribeServerOriginatedRPC

func SubscribeServerOriginatedRPC(ctx context.Context, caller Caller, c *Connection,
	callback func(Caller, *iterm2.ServerOriginatedRPCNotification),
) (NotificationToken, error)

SubscribeServerOriginatedRPC registers a callback that fires when iTerm2 invokes a server-originated RPC. Use name == "" to match all RPC names.

func SubscribeTerminateSession

func SubscribeTerminateSession(ctx context.Context, caller Caller, c *Connection,
	callback func(Caller, *iterm2.TerminateSessionNotification),
) (NotificationToken, error)

SubscribeTerminateSession registers a callback that fires when an iTerm2 session terminates.

func SubscribeVariableChange

func SubscribeVariableChange(ctx context.Context, caller Caller, c *Connection,
	callback func(Caller, *iterm2.VariableChangedNotification),
	sessionID, variableName string,
) (NotificationToken, error)

SubscribeVariableChange registers a callback that fires when variableName changes in sessionID. The sessionID is used as both the session filter on the notification request and the identifier in the variable monitor.

type Notifier

type Notifier interface {
	RegisterHandler(h NotificationHandler)
	UnregisterHandler(h NotificationHandler)
}

Notifier abstracts notification subscription management.

type OpenPanelOptions

type OpenPanelOptions int

OpenPanelOptions are flags for ShowOpenPanel.

const (
	OpenPanelCanCreateDirectories            OpenPanelOptions = 1 << 0
	OpenPanelTreatsFilePackagesAsDirectories OpenPanelOptions = 1 << 1
	OpenPanelShowsHiddenFiles                OpenPanelOptions = 1 << 2
	OpenPanelResolvesAliases                 OpenPanelOptions = 1 << 32
	OpenPanelCanChooseDirectories            OpenPanelOptions = 1 << 33
	OpenPanelAllowsMultipleSelection         OpenPanelOptions = 1 << 34
	OpenPanelCanChooseFiles                  OpenPanelOptions = 1 << 35
)

type OpenPanelResult

type OpenPanelResult struct {
	Files []string
}

OpenPanelResult holds the files selected in the open panel.

func ShowOpenPanelWithOptions

func ShowOpenPanelWithOptions(ctx context.Context, caller Caller, title, message, initialPath, prompt string, options OpenPanelOptions, extensions []string) (*OpenPanelResult, error)

ShowOpenPanelWithOptions displays an open file panel with full options.

type Option

type Option func(*Connection)

Option configures a Connection.

func WithCallTimeout

func WithCallTimeout(d time.Duration) Option

WithCallTimeout sets the deadline for each Call operation. Zero means no timeout (use with caution — a missing response blocks forever). Default: 30s.

func WithHandshakeTimeout

func WithHandshakeTimeout(d time.Duration) Option

WithHandshakeTimeout sets the WebSocket handshake timeout for dialing. Default: 45s.

func WithReadTimeout

func WithReadTimeout(d time.Duration) Option

WithReadTimeout sets the read deadline for each WebSocket read. This controls how long dispatchLoop waits for the next message before timing out. Default: 60s.

type Point

type Point struct {
	X, Y int32
}

Point represents an origin coordinate in iTerm2 (pixels).

type PolyModalAlert

type PolyModalAlert struct {
	Title            string
	Subtitle         string
	WindowID         string
	Width            int
	Buttons          []string
	CheckboxItems    []string
	CheckboxDefaults []int
	ComboBoxItems    []string
	ComboBoxDefault  string
	TextFieldDefault string
	TextFieldLabel   string
}

PolyModalAlert is a modal alert with checkboxes, combobox, and text field.

func NewPolyModalAlert

func NewPolyModalAlert(title, subtitle string) *PolyModalAlert

NewPolyModalAlert creates a new PolyModalAlert.

func (*PolyModalAlert) AddButton

func (a *PolyModalAlert) AddButton(label string)

AddButton adds a button.

func (*PolyModalAlert) AddCheckbox

func (a *PolyModalAlert) AddCheckbox(label string, checked bool)

AddCheckbox adds a checkbox with default state (1=checked, 0=unchecked).

func (*PolyModalAlert) AddComboBox

func (a *PolyModalAlert) AddComboBox(items []string, defaultItem string)

AddComboBox replaces cometable items and sets the default selection.

func (*PolyModalAlert) AddTextField

func (a *PolyModalAlert) AddTextField(placeholder, defaultValue string)

AddTextField adds a text field with placeholder and default value.

func (*PolyModalAlert) Run

func (a *PolyModalAlert) Run(ctx context.Context, caller Caller) (*PolyModalResult, error)

Run displays the poly modal alert and returns the result.

type PolyModalResult

type PolyModalResult struct {
	Button     string   // label of the clicked button
	TextField  string   // text entered into the field
	ComboBox   string   // selected combobox item
	Checkboxes []string // checked checkbox labels
}

PolyModalResult holds the returned values of a PolyModalAlert.

type Prompt

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

Prompt wraps GetPromptResponse from a shell prompt.

func GetLastPrompt

func GetLastPrompt(ctx context.Context, caller Caller, sessionID string) (*Prompt, error)

GetLastPrompt retrieves the most recent prompt for a session. Returns nil if PROMPT_UNAVAILABLE.

func GetPromptByID

func GetPromptByID(ctx context.Context, caller Caller, sessionID, promptID string) (*Prompt, error)

GetPromptByID retrieves a specific prompt by its unique ID.

func NewPrompt

func NewPrompt(raw *iterm2.GetPromptResponse) *Prompt

NewPrompt creates a Prompt from a proto response.

func (*Prompt) Command

func (p *Prompt) Command() string

Command returns the text of the command.

func (*Prompt) CommandRange

func (p *Prompt) CommandRange() CoordRange

CommandRange returns the coordinates of the command typed by the user.

func (*Prompt) ExcludedSubranges

func (p *Prompt) ExcludedSubranges() []CoordRange

ExcludedSubranges returns ranges inside the command that are not part of user input (e.g. copy-mode paste bracketed regions).

func (*Prompt) ExitStatus

func (p *Prompt) ExitStatus() uint32

ExitStatus returns the command exit code (only valid when state==Finished).

func (*Prompt) OutputRange

func (p *Prompt) OutputRange() CoordRange

OutputRange returns the coordinates of the command output.

func (*Prompt) PromptRange

func (p *Prompt) PromptRange() CoordRange

PromptRange returns the coordinates of the prompt text.

func (*Prompt) Raw

func (p *Prompt) Raw() *iterm2.GetPromptResponse

Raw returns the underlying proto response.

func (*Prompt) State

func (p *Prompt) State() PromptState

State returns the prompt state.

func (*Prompt) UniqueID

func (p *Prompt) UniqueID() string

UniqueID returns the unique prompt identifier, or "" if unavailable.

func (*Prompt) WorkingDirectory

func (p *Prompt) WorkingDirectory() string

WorkingDirectory returns the working directory when the command ran.

type PromptEvent

type PromptEvent struct {
	Mode    iterm2.PromptMonitorMode // PROMPT / COMMAND_START / COMMAND_END
	Prompt  *Prompt                  // non-nil when Mode==PROMPT
	Command string                   // non-empty when Mode==COMMAND_START
	Status  int32                    // valid when Mode==COMMAND_END

	// UniquePromptID is set when the notification includes it.
	UniquePromptID string
}

PromptEvent is produced by PromptMonitor on each prompt-state change.

type PromptMonitor

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

PromptMonitor streams prompt lifecycle events. Create one with NewPromptMonitor, iterate over Chan(), and call Close() when finished.

Unlike ScreenStreamer, PromptMonitor does not need a run goroutine — the prompt data is embedded directly in the notification, so no extra RPC calls are needed.

func NewPromptMonitor

func NewPromptMonitor(conn *Connection, sessionID string, modes []iterm2.PromptMonitorMode) (*PromptMonitor, error)

NewPromptMonitor subscribes to prompt notifications with the given modes. If modes is nil, defaults to [PromptMonitorMode_PROMPT].

Usage:

pm, err := NewPromptMonitor(conn, sessionID, []PromptMonitorMode{PROMPT, COMMAND_END})
if err != nil { ... }
defer pm.Close()
for ev := range pm.Chan() {
    switch ev.Mode {
    case PROMPT:
        fmt.Println("prompt:", ev.Prompt.Command())
    case COMMAND_END:
        fmt.Println("exit:", ev.Status)
    }
}

func (*PromptMonitor) Chan

func (pm *PromptMonitor) Chan() <-chan PromptEvent

Chan returns a receive-only channel of PromptEvents.

func (*PromptMonitor) Close

func (pm *PromptMonitor) Close()

Close stops the monitor and unsubscribes. Safe to call multiple times.

type PromptState

type PromptState int

PromptState describes the lifecycle of a shell prompt.

const (
	PromptEditing  PromptState = 0 // Command is being edited
	PromptRunning  PromptState = 1 // Command is executing
	PromptFinished PromptState = 2 // Command has completed
)

type ProtocolVersion

type ProtocolVersion struct {
	Major int
	Minor int
}

ProtocolVersion represents an iTerm2 protocol version.

type RPCArgs

type RPCArgs map[string]interface{}

RPCArgs holds named arguments from an iTerm2 server-originated RPC invocation. Values are JSON-decoded from the notification's argument list.

type RPCError

type RPCError struct {
	Message string
}

RPCError is returned when iTerm2 responds with an error.

func (*RPCError) Error

func (e *RPCError) Error() string

type RPCHandler

type RPCHandler func(ctx context.Context, args RPCArgs) (interface{}, error)

RPCHandler is a function that processes a server-originated RPC. It receives the context and parsed arguments, and returns a JSON-serializable result or an error. Errors are sent back to iTerm2 as exceptions.

type RPCRPCRole

type RPCRPCRole int32

RPCRPCRole mirrors iterm2.RPCRegistrationRequest_Role.

const (
	RPCRoleGeneric            RPCRPCRole = 1
	RPCRoleSessionTitle       RPCRPCRole = 2
	RPCRoleStatusBarComponent RPCRPCRole = 3
	RPCRoleContextMenu        RPCRPCRole = 4
)

type RPCRegistration

type RPCRegistration struct {
	Name      string            // RPC function name iTerm2 uses to invoke it
	Arguments []string          // argument names in the RPC signature
	Defaults  map[string]string // default key → variable path (like Python's Reference)
	Timeout   float32           // seconds iTerm2 waits; 0 means use default
	// Role-specific fields
	Role        RPCRPCRole // GENERIC / SESSION_TITLE / STATUS_BAR_COMPONENT / CONTEXT_MENU
	DisplayName string     // for SESSION_TITLE / CONTEXT_MENU roles
	UniqueID    string     // unique identifier (reverse DNS), required for non-GENERIC roles
	// StatusBarComponent is embedded in the registration for STATUS_BAR_COMPONENT role.
	StatusBarComponent *StatusBarComponent
}

RPCRegistration configures how an RPC is registered with iTerm2. Corresponds to Python's registration.RPC decorator parameters.

type RPCRegistry

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

RPCRegistry manages registered RPC handlers and dispatches incoming ServerOriginatedRPCNotification messages to the correct handler.

Usage:

reg := NewRPCRegistry(conn)
reg.Register(ctx, conn, RPCRegistration{
    Name:      "my_function",
    Arguments: []string{"arg1"},
}, func(ctx context.Context, args RPCArgs) (interface{}, error) {
    return "ok", nil
})
// Block until connection closes:
select {}

func NewRPCRegistry

func NewRPCRegistry(conn *Connection) *RPCRegistry

NewRPCRegistry creates a new RPC registry for the given connection.

func (*RPCRegistry) Register

func (r *RPCRegistry) Register(ctx context.Context, caller Caller, config RPCRegistration, handler RPCHandler) error

Register registers an RPC handler with iTerm2 using the full registration config. Returns an error if the handler could not be registered.

func (*RPCRegistry) Stop

func (r *RPCRegistry) Stop()

Stop unsubscribes from RPC notifications.

type RestartSessionOption

type RestartSessionOption func(*iterm2.RestartSessionRequest)

RestartSessionOption is an option for RestartSession.

func WithRestartOnlyIfExited

func WithRestartOnlyIfExited(onlyIfExited bool) RestartSessionOption

WithRestartOnlyIfExited only restarts if the session has exited.

type SavePanelOptions

type SavePanelOptions int

SavePanelOptions are flags for ShowSavePanel.

const (
	SavePanelCanCreateDirectories            SavePanelOptions = 1 << 0
	SavePanelTreatsFilePackagesAsDirectories SavePanelOptions = 1 << 1
	SavePanelShowsHiddenFiles                SavePanelOptions = 1 << 2
	SavePanelAllowsOtherFileTypes            SavePanelOptions = 1 << 3
	SavePanelCanSelectHiddenExtension        SavePanelOptions = 1 << 4
	SavePanelExtensionHidden                 SavePanelOptions = 1 << 5
)

type SavePanelResult

type SavePanelResult struct {
	File string
}

SavePanelResult holds the file path selected in the save panel.

func ShowSavePanelWithOptions

func ShowSavePanelWithOptions(ctx context.Context, caller Caller, title, message, initialPath, prompt, defaultFilename, nameFieldLabel string, options SavePanelOptions, extensions []string) (*SavePanelResult, error)

ShowSavePanelWithOptions displays a save file panel with full options.

type ScreenContents

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

ScreenContents wraps a GetBufferResponse with convenience accessors. It represents the visible region of a terminal session at a point in time.

func NewScreenContents

func NewScreenContents(raw *iterm2.GetBufferResponse) *ScreenContents

NewScreenContents creates a ScreenContents from a proto response.

func (*ScreenContents) Cursor

func (s *ScreenContents) Cursor() *Coord

Cursor returns the cursor position, or nil.

func (*ScreenContents) LineCount

func (s *ScreenContents) LineCount() int

LineCount returns the number of lines.

func (*ScreenContents) Lines

func (s *ScreenContents) Lines() []*LineContent

Lines returns all lines as LineContent wrappers.

func (*ScreenContents) Raw

Raw returns the underlying proto response.

type ScreenStreamer

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

ScreenStreamer streams terminal screen contents on each update. Create one with NewScreenStreamer, iterate over Chan(), and call Close() when finished.

func NewScreenStreamer

func NewScreenStreamer(conn *Connection, sessionID string) (*ScreenStreamer, error)

NewScreenStreamer subscribes to screen-update notifications for sessionID and starts fetching screen contents on each update.

Usage:

s, err := NewScreenStreamer(conn, sessionID)
if err != nil { ... }
defer s.Close()
for sc := range s.Chan() {
    for _, line := range sc.Lines() { ... }
}

func (*ScreenStreamer) Chan

func (s *ScreenStreamer) Chan() <-chan *ScreenContents

Chan returns a receive-only channel of screen contents. The channel is closed when the streamer is closed.

func (*ScreenStreamer) Close

func (s *ScreenStreamer) Close()

Close stops the streamer and unsubscribes from notifications. It is safe to call multiple times.

type SendTextOption

type SendTextOption func(*iterm2.SendTextRequest)

SendTextOption is an option for SendText.

func WithSendTextSuppressBroadcast

func WithSendTextSuppressBroadcast(suppress bool) SendTextOption

WithSendTextSuppressBroadcast prevents broadcast when broadcasting is on.

type Session

type Session struct {
	ID string
	// contains filtered or unexported fields
}

Session represents an iTerm2 session (a single terminal pane).

func (*Session) Close

func (s *Session) Close(ctx context.Context, opts ...CloseOption) error

Close closes the session.

func (*Session) GetBuffer

func (s *Session) GetBuffer(ctx context.Context, lineRange *iterm2.LineRange) (*iterm2.GetBufferResponse, error)

GetBuffer retrieves the contents of the session's buffer.

func (*Session) GetID

func (s *Session) GetID() string

GetID returns the session's unique identifier.

func (*Session) GetLineInfo

func (s *Session) GetLineInfo(ctx context.Context) (*LineInfo, error)

GetLineInfo fetches the number of lines visible, in history, and overflowed. Corresponds to Python's async_get_line_info.

func (*Session) GetScreenStreamer

func (s *Session) GetScreenStreamer() (*ScreenStreamer, error)

GetScreenStreamer creates a ScreenStreamer that watches this session's screen updates and streams the contents via a channel.

func (*Session) GetVariable

func (s *Session) GetVariable(ctx context.Context, name string) (string, error)

GetVariable gets the value of a variable from this session. iTerm2 encodes all variable values as JSON; this method decodes them back.

func (*Session) Inject

func (s *Session) Inject(ctx context.Context, data []byte) error

Inject injects raw bytes directly into the session's terminal.

func (*Session) Screenshot

func (s *Session) Screenshot(ctx context.Context, path string) error

Screenshot captures this session's containing window and saves it as a PNG file.

func (*Session) SendText

func (s *Session) SendText(ctx context.Context, text string, opts ...SendTextOption) error

SendText sends text to the session as if typed by the user.

func (*Session) SetBadge

func (s *Session) SetBadge(ctx context.Context, text string) error

SetBadge sets the session badge text via SetProfileProperty.

func (*Session) SetBuried

func (s *Session) SetBuried(ctx context.Context, buried bool) error

SetBuried sets or unsets the buried (minimized) state of a session.

func (*Session) SetGridSize

func (s *Session) SetGridSize(ctx context.Context, width, height int32) error

SetGridSize sets the visible grid size (columns, rows) of a session.

func (*Session) SetName

func (s *Session) SetName(ctx context.Context, name string) error

SetName sets the session name via the iterm2.set_name RPC.

func (*Session) SetVariable

func (s *Session) SetVariable(ctx context.Context, name, value string) error

SetVariable sets a variable on this session.

func (*Session) SplitPane

func (s *Session) SplitPane(ctx context.Context, vertical bool, before bool, profile string) (*Session, error)

SplitPane splits this session's pane, creating a new session.

type Size

type Size struct {
	Width, Height int32
}

Size represents dimensions (width, height).

type SplitChild

type SplitChild struct {
	Session  *Session
	Splitter *Splitter
}

SplitChild holds either a Session or a nested Splitter, but never both. Use IsSession() or IsSplitter() to determine which field is set.

func (*SplitChild) IsSession

func (c *SplitChild) IsSession() bool

IsSession reports whether this child is a Session.

func (*SplitChild) IsSplitter

func (c *SplitChild) IsSplitter() bool

IsSplitter reports whether this child is a Splitter.

func (*SplitChild) SessionOrNil

func (c *SplitChild) SessionOrNil() *Session

SessionOrNil returns the Session if this is a leaf, or nil otherwise. This avoids allocating a Splitter when the child is actually a Session.

func (*SplitChild) SplitterOrNil

func (c *SplitChild) SplitterOrNil() *Splitter

SplitterOrNil returns the Splitter if this is a node, or nil otherwise. This avoids allocating a Session when the child is actually a Splitter.

type SplitPaneOption

type SplitPaneOption func(*iterm2.SplitPaneRequest)

SplitPaneOption is an option for SplitPane.

func WithSplitPaneCustomProfileProperties

func WithSplitPaneCustomProfileProperties(props []*iterm2.ProfileProperty) SplitPaneOption

WithSplitPaneCustomProfileProperties modifies the profile for the split pane session.

type Splitter

type Splitter struct {
	Vertical bool
	Children []SplitChild
}

Splitter represents a split pane tree node. It is either a leaf (containing a Session) or an interior node with a split direction and child splitters or sessions.

func SplitterFromProto

func SplitterFromProto(node *iterm2.SplitTreeNode, conn Caller) *Splitter

SplitterFromProto recursively builds a Splitter tree from a proto SplitTreeNode. Each link in the node is either a leaf (Session) or a nested sub-splitter.

func (*Splitter) Sessions

func (s *Splitter) Sessions() []*Session

Sessions returns all Session leaf nodes in this splitter tree, including those nested in sub-splitters.

func (*Splitter) ToProto

func (s *Splitter) ToProto() *iterm2.SplitTreeNode

ToProto converts the Splitter tree back to a SplitTreeNode for RPC use.

type StatusBarComponent

type StatusBarComponent struct {
	ShortDescription    string
	DetailedDescription string
	Knobs               map[string]string
	Exemplar            string
	UpdateCadence       float64 // seconds, 0 means no timer reload
	Identifier          string
	Icons               []StatusBarIcon
	Format              StatusBarFormat
}

StatusBarComponent describes a script-provided status bar component.

type StatusBarFormat

type StatusBarFormat int

StatusBarFormat describes how a component's output is formatted.

const (
	StatusBarFormatPlainText StatusBarFormat = 0
	StatusBarFormatHTML      StatusBarFormat = 1
)

type StatusBarIcon

type StatusBarIcon struct {
	Scale float64
	Data  []byte // raw PNG bytes
}

StatusBarIcon is a PNG icon for a status bar component. Scale gives the ratio between pixels and points (2 for retina, 1 for regular).

type Tab

type Tab struct {
	ID   string
	Root *Splitter
	// contains filtered or unexported fields
}

Tab represents an iTerm2 tab, which contains a tree of split panes.

func (*Tab) Close

func (t *Tab) Close(ctx context.Context, opts ...CloseOption) error

Close closes the tab.

func (*Tab) Screenshot

func (t *Tab) Screenshot(ctx context.Context, path string) error

Screenshot captures this tab's containing window and saves it as a PNG file.

func (*Tab) Select

func (t *Tab) Select(ctx context.Context) error

Select makes this tab the active tab.

func (*Tab) UpdateLayout

func (t *Tab) UpdateLayout(ctx context.Context) error

UpdateLayout sends the current split-pane layout to iTerm2 to adjust sizes.

type TmuxConnection

type TmuxConnection struct {

	// ConnectionID uniquely identifies this tmux connection within iTerm2.
	ConnectionID string

	// OwningSessionID is the iTerm2 session that owns this tmux connection.
	OwningSessionID string
	// contains filtered or unexported fields
}

TmuxConnection represents an open tmux integration connection.

func GetTmuxConnectionByID

func GetTmuxConnectionByID(ctx context.Context, caller Caller, id string) (*TmuxConnection, error)

GetTmuxConnectionByID finds a single tmux connection by ID. Returns nil if not found (no error).

func GetTmuxConnections

func GetTmuxConnections(ctx context.Context, caller Caller) ([]*TmuxConnection, error)

GetTmuxConnections returns all open tmux connections.

func (*TmuxConnection) CreateWindow

func (t *TmuxConnection) CreateWindow(ctx context.Context, affinity string) (string, error)

CreateWindow creates a new tmux window on this connection. affinity is optional — pass "" for none. Returns the new iTerm2 tab ID.

func (*TmuxConnection) SendCommand

func (t *TmuxConnection) SendCommand(ctx context.Context, command string) (string, error)

SendCommand sends a tmux command on this connection and returns the output.

func (*TmuxConnection) SetWindowVisible

func (t *TmuxConnection) SetWindowVisible(ctx context.Context, windowID string, visible bool) error

SetWindowVisible shows or hides a tmux window.

type Trigger

type Trigger struct {
	// Common fields
	Type      TriggerType
	Regex     string
	Param     string // serialised parameter string (type-dependent format)
	Instant   bool   // fire immediately, don't wait for newline
	Enabled   bool
	MatchType TriggerMatchType

	// Event-trigger parameters (MatchType >= 100)
	EventParams map[string]interface{}

	ExitCode  string  // CommandFinishedEvent: "*", "0", "!0"
	Threshold float64 // IdleEvent/ActivityAfterIdle/LongRunningCommand
	Timeout   float64 // IdleEvent/ActivityAfterIdle
	Sequence  string  // CustomEscapeSequenceEvent
	Progress  string  // ProgressBarChangedEvent: "*", "appeared", "disappeared"
	// contains filtered or unexported fields
}

Trigger provides a unified representation of all iTerm2 trigger types. Use New*Trigger factory functions to create specific types, and the generic DecodeTrigger function to parse JSON-encoded triggers.

func DecodeTrigger

func DecodeTrigger(encoded map[string]interface{}) (*Trigger, error)

DecodeTrigger parses a JSON-encoded trigger dict from iTerm2.

func GetTriggers

func GetTriggers(ctx context.Context, caller Caller, sessionID string) ([]*Trigger, error)

GetTriggers reads triggers from the session's profile.

func NewActivityAfterIdleEventTrigger

func NewActivityAfterIdleEventTrigger(timeout float64) *Trigger

func NewAlertTrigger

func NewAlertTrigger(regex, message string) *Trigger

func NewAnnotateTrigger

func NewAnnotateTrigger(regex, annotation string) *Trigger

func NewBellReceivedEventTrigger

func NewBellReceivedEventTrigger() *Trigger

func NewBellTrigger

func NewBellTrigger(regex string) *Trigger

func NewBounceTrigger

func NewBounceTrigger(regex string, bounceOnce bool) *Trigger

func NewBufferInputTrigger

func NewBufferInputTrigger(regex string, start bool) *Trigger

func NewCaptureTrigger

func NewCaptureTrigger(regex, command string) *Trigger

func NewCommandFinishedEventTrigger

func NewCommandFinishedEventTrigger(exitCodeFilter string) *Trigger

func NewCoprocessTrigger

func NewCoprocessTrigger(regex, command string) *Trigger

func NewCustomEscapeSequenceEventTrigger

func NewCustomEscapeSequenceEventTrigger(sequenceID string) *Trigger

func NewDirectoryChangedEventTrigger

func NewDirectoryChangedEventTrigger(dirRegex string) *Trigger

func NewFoldTrigger

func NewFoldTrigger(regex, markname string) *Trigger

func NewHighlightLineTrigger

func NewHighlightLineTrigger(regex, textColor, bgColor string) *Trigger

func NewHighlightTrigger

func NewHighlightTrigger(regex, textColor, bgColor string) *Trigger

func NewHostChangedEventTrigger

func NewHostChangedEventTrigger(hostRegex string) *Trigger

func NewHyperlinkTrigger

func NewHyperlinkTrigger(regex, url string) *Trigger

func NewIdleEventTrigger

func NewIdleEventTrigger(timeout float64) *Trigger

func NewInjectTrigger

func NewInjectTrigger(regex, injection string) *Trigger

func NewLongRunningCommandEventTrigger

func NewLongRunningCommandEventTrigger(threshold float64, commandRegex string) *Trigger

func NewMarkTrigger

func NewMarkTrigger(regex string, stopScrolling bool) *Trigger

func NewMuteCoprocessTrigger

func NewMuteCoprocessTrigger(regex, command string) *Trigger

func NewNotificationPostedEventTrigger

func NewNotificationPostedEventTrigger(messageRegex string) *Trigger

func NewPasswordTrigger

func NewPasswordTrigger(regex, accountName, userName string) *Trigger

func NewProgressBarChangedEventTrigger

func NewProgressBarChangedEventTrigger(filter string) *Trigger

func NewPromptDetectedEventTrigger

func NewPromptDetectedEventTrigger() *Trigger

func NewRPCTrigger

func NewRPCTrigger(regex, invocation string) *Trigger

func NewRunCommandTrigger

func NewRunCommandTrigger(regex, command string) *Trigger

func NewSGRTrigger

func NewSGRTrigger(regex, sgr string) *Trigger

func NewSendTextTrigger

func NewSendTextTrigger(regex, text string) *Trigger

func NewSessionEndedEventTrigger

func NewSessionEndedEventTrigger() *Trigger

func NewSetDirectoryTrigger

func NewSetDirectoryTrigger(regex, directory string) *Trigger

func NewSetHostnameTrigger

func NewSetHostnameTrigger(regex, hostname string) *Trigger

func NewSetNamedMarkTrigger

func NewSetNamedMarkTrigger(regex, markname string) *Trigger

func NewSetTitleTrigger

func NewSetTitleTrigger(regex, title string) *Trigger

func NewSetUserVariableTrigger

func NewSetUserVariableTrigger(regex, name, jsonValue string) *Trigger

func NewShellPromptTrigger

func NewShellPromptTrigger(regex string) *Trigger

func NewStopTrigger

func NewStopTrigger(regex string) *Trigger

func NewUserChangedEventTrigger

func NewUserChangedEventTrigger(userRegex string) *Trigger

func NewUserNotificationTrigger

func NewUserNotificationTrigger(regex, message string) *Trigger

func (*Trigger) Actions

func (t *Trigger) Actions() []string

Actions returns the decoded parameter as actions (for triggers with multiple values).

func (*Trigger) Encode

func (t *Trigger) Encode() map[string]interface{}

Encode serialises the trigger to a JSON-compatible map.

func (*Trigger) IsEvent

func (t *Trigger) IsEvent() bool

IsEvent returns true if this is an event-based trigger (MatchType >= 100).

func (*Trigger) IsRegex

func (t *Trigger) IsRegex() bool

IsRegex returns true if this is a regex-based trigger (MatchType < 100).

func (*Trigger) String

func (t *Trigger) String() string

String returns a human-readable representation.

type TriggerMatchType

type TriggerMatchType int

TriggerMatchType matches Python's MatchType enum.

const (
	MatchTypeREGEX                     TriggerMatchType = 0
	MatchTypeURLRegex                  TriggerMatchType = 1
	MatchTypePageContentRegex          TriggerMatchType = 2
	MatchTypeEventPromptDetected       TriggerMatchType = 100
	MatchTypeEventCommandFinished      TriggerMatchType = 101
	MatchTypeEventDirectoryChanged     TriggerMatchType = 102
	MatchTypeEventHostChanged          TriggerMatchType = 103
	MatchTypeEventUserChanged          TriggerMatchType = 104
	MatchTypeEventIdle                 TriggerMatchType = 105
	MatchTypeEventActivityAfterIdle    TriggerMatchType = 106
	MatchTypeEventSessionEnded         TriggerMatchType = 107
	MatchTypeEventBellReceived         TriggerMatchType = 108
	MatchTypeEventLongRunningCommand   TriggerMatchType = 109
	MatchTypeEventCustomEscapeSequence TriggerMatchType = 110
	MatchTypeEventNotificationPosted   TriggerMatchType = 111
	MatchTypeEventProgressBarChanged   TriggerMatchType = 112
)

type TriggerType

type TriggerType string

TriggerType identifies the kind of trigger.

const (
	TriggerAlert            TriggerType = "AlertTrigger"
	TriggerAnnotate         TriggerType = "AnnotateTrigger"
	TriggerBell             TriggerType = "BellTrigger"
	TriggerBounce           TriggerType = "BounceTrigger"
	TriggerBufferInput      TriggerType = "iTermBufferInputTrigger"
	TriggerRPC              TriggerType = "iTermRPCTrigger"
	TriggerCapture          TriggerType = "CaptureTrigger"
	TriggerSetNamedMark     TriggerType = "iTermSetNamedMarkTrigger"
	TriggerSGR              TriggerType = "iTermSGRTrigger"
	TriggerFold             TriggerType = "iTermFoldTrigger"
	TriggerInject           TriggerType = "iTermInjectTrigger"
	TriggerHighlightLine    TriggerType = "iTermHighlightLineTrigger"
	TriggerHighlight        TriggerType = "HighlightTrigger"
	TriggerUserNotification TriggerType = "iTermUserNotificationTrigger"
	TriggerSetUserVariable  TriggerType = "iTermSetUserVariableTrigger"
	TriggerShellPrompt      TriggerType = "iTermShellPromptTrigger"
	TriggerSetTitle         TriggerType = "iTermSetTitleTrigger"
	TriggerSendText         TriggerType = "SendTextTrigger"
	TriggerRunCommand       TriggerType = "ScriptTrigger"
	TriggerCoprocess        TriggerType = "CoprocessTrigger"
	TriggerMuteCoprocess    TriggerType = "MuteCoprocessTrigger"
	TriggerMark             TriggerType = "MarkTrigger"
	TriggerPassword         TriggerType = "PasswordTrigger"
	TriggerHyperlink        TriggerType = "iTermHyperlinkTrigger"
	TriggerSetDirectory     TriggerType = "SetDirectoryTrigger"
	TriggerSetHostname      TriggerType = "SetHostnameTrigger"
	TriggerStop             TriggerType = "StopTrigger"
	// Event triggers (MatchType >= 100)
	TriggerPromptDetectedEvent       TriggerType = "PromptDetectedEventTrigger"
	TriggerCommandFinishedEvent      TriggerType = "CommandFinishedEventTrigger"
	TriggerDirectoryChangedEvent     TriggerType = "DirectoryChangedEventTrigger"
	TriggerHostChangedEvent          TriggerType = "HostChangedEventTrigger"
	TriggerUserChangedEvent          TriggerType = "UserChangedEventTrigger"
	TriggerIdleEvent                 TriggerType = "IdleEventTrigger"
	TriggerActivityAfterIdleEvent    TriggerType = "ActivityAfterIdleEventTrigger"
	TriggerSessionEndedEvent         TriggerType = "SessionEndedEventTrigger"
	TriggerBellReceivedEvent         TriggerType = "BellReceivedEventTrigger"
	TriggerLongRunningCommandEvent   TriggerType = "LongRunningCommandEventTrigger"
	TriggerCustomEscapeSequenceEvent TriggerType = "CustomEscapeSequenceEventTrigger"
	TriggerNotificationPostedEvent   TriggerType = "NotificationPostedEventTrigger"
	TriggerProgressBarChangedEvent   TriggerType = "ProgressBarChangedEventTrigger"
)

type Window

type Window struct {
	ID     string
	Tabs   []*Tab
	Frame  *WindowFrame
	Number int32
	// contains filtered or unexported fields
}

Window represents an iTerm2 terminal window.

func (*Window) Close

func (w *Window) Close(ctx context.Context, opts ...CloseOption) error

Close closes the window.

func (*Window) CreateTab

func (w *Window) CreateTab(ctx context.Context, profileName string, opts ...CreateTabOption) (*Tab, error)

CreateTab creates a new tab in this window with the given profile name. After creation, it refreshes the window hierarchy to discover the new tab's real identifier (CreateTabResponse returns only a tab index, not the UUID that Tab.Close needs).

func (*Window) Screenshot

func (w *Window) Screenshot(ctx context.Context, path string) error

Screenshot captures this window and saves it as a PNG file.

type WindowFocusChange

type WindowFocusChange struct {
	WindowID string
	Status   WindowStatus
}

WindowFocusChange reports a window-level focus change.

type WindowFrame

type WindowFrame struct {
	Origin Point
	Size   Size
}

WindowFrame stores both origin and size of a window.

type WindowStatus

type WindowStatus int

WindowStatus describes the window focus change reason.

const (
	WindowBecameKey   WindowStatus = 0
	WindowIsCurrent   WindowStatus = 1
	WindowResignedKey WindowStatus = 2
)

Directories

Path Synopsis
example
inject command
example/inject — keystroke injection
example/inject — keystroke injection
live command
example/live — live output from continuously running commands
example/live — live output from continuously running commands
notification command
example/notification — event subscriptions
example/notification — event subscriptions
pane command
example/pane — split pane operations
example/pane — split pane operations
prompt command
example/prompt — custom prompt
example/prompt — custom prompt
property command
example/property — session property operations
example/property — session property operations
query command
example/query — query operations
example/query — query operations
session command
example/session — basic session operations
example/session — basic session operations
variable command
example/variable — session variable read/write
example/variable — session variable read/write

Jump to

Keyboard shortcuts

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