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
- func Activate(ctx context.Context, caller Caller, sessionID string, orderWindowFront bool, ...) error
- func CheckboxKnob(key string, defaultValue bool) (string, string)
- func Close(ctx context.Context, caller Caller, sessionID string, opts ...CloseOption) error
- func CloseForce(ctx context.Context, caller Caller, sessionID string) error
- func ColorKnob(key string, colorJSON string) (string, string)
- func CreateTab(ctx context.Context, caller Caller, windowID string, profileName string, ...) (*iterm2.CreateTabResponse, error)
- func EachSessionOnce(conn *Connection, fn func(session *Session) error)deprecated
- func EachSessionOnceCtx(ctx context.Context, conn *Connection, fn func(session *Session) error)
- func EnumerateRanges(sel *iterm2.Selection, fn func(start, end Coord) error) error
- func ExitCodeFilter(code int) string
- func FloatKnob(key string, defaultValue float64) (string, string)
- func FocusRequest(ctx context.Context, caller Caller) (*iterm2.FocusResponse, error)
- func GetBuffer(ctx context.Context, caller Caller, sessionID string, ...) (*iterm2.GetBufferResponse, error)
- func GetCookieOrCreate(scriptName string) (cookie, key string, err error)
- func GetProfileProperty(ctx context.Context, caller Caller, sessionID string, keys []string) (*iterm2.GetProfilePropertyResponse, error)
- func GetPrompt(ctx context.Context, caller Caller, sessionID string, opts ...GetPromptOption) (*iterm2.GetPromptResponse, error)
- func GetProperty(ctx context.Context, caller Caller, sessionID string, name string) (*iterm2.GetPropertyResponse, error)
- func GetSelection(ctx context.Context, caller Caller, sessionID string) (*iterm2.SelectionResponse_GetSelectionResponse, error)
- func GetVariable(ctx context.Context, caller Caller, sessionID string, names []string) ([]string, error)
- func Inject(ctx context.Context, caller Caller, sessionIDs []string, data []byte) error
- func InvokeFunction(ctx context.Context, caller Caller, req *iterm2.InvokeFunctionRequest) (*iterm2.InvokeFunctionResponse, error)
- func ListColorPresets(ctx context.Context, caller Caller) ([]string, error)
- func ListProfiles(ctx context.Context, caller Caller, properties []string, guids []string) (*iterm2.ListProfilesResponse, error)
- func ListPromptIDs(ctx context.Context, caller Caller, sessionID, first, last string) ([]string, error)
- func ListPrompts(ctx context.Context, caller Caller, sessionID string, ...) (*iterm2.ListPromptsResponse, error)
- func ListSessions(ctx context.Context, caller Caller) (*iterm2.ListSessionsResponse, error)
- func MarkNoStopScrolling() string
- func MarkStopScrolling() string
- func NotificationRequest(ctx context.Context, caller Caller, subscribe bool, ...) (*iterm2.NotificationResponse, error)
- func OpenStatusBarPopover(ctx context.Context, caller Caller, identifier, sessionID, html string, ...) error
- func PreferencesRequest(ctx context.Context, caller Caller, req *iterm2.PreferencesRequest) (*iterm2.PreferencesResponse, error)
- func RegisterStatusBarComponent(ctx context.Context, caller Caller, component StatusBarComponent) error
- func RestartSession(ctx context.Context, caller Caller, sessionID string, ...) error
- func RestartSessionIfExited(ctx context.Context, caller Caller, sessionID string) error
- func Run(ctx context.Context, scriptName string, fn func(caller Caller) error) error
- func SavedArrangementRequest(ctx context.Context, caller Caller, req *iterm2.SavedArrangementRequest) (*iterm2.SavedArrangementResponse, error)
- func SelectMenuItem(ctx context.Context, caller Caller, identifier string) error
- func SelectionRequest(ctx context.Context, caller Caller, sessionID string) (*iterm2.SelectionResponse, error)
- func SendText(ctx context.Context, caller Caller, sessionID string, text string, ...) error
- func SendTextNoBroadcast(ctx context.Context, caller Caller, sessionID string, text string) error
- func ServerOriginatedRPCResultRequest(ctx context.Context, caller Caller, ...) error
- func SetBuried(ctx context.Context, caller Caller, sessionID string, buried bool) error
- func SetGridSize(ctx context.Context, caller Caller, sessionID string, width, height int32) error
- func SetProfileProperty(ctx context.Context, caller Caller, sessionID string, key string, ...) error
- func SetProperty(ctx context.Context, caller Caller, sessionID string, name string, ...) error
- func SetSelection(ctx context.Context, caller Caller, sessionID string, ...) error
- func SetTabLayout(ctx context.Context, caller Caller, tabID string, root *iterm2.SplitTreeNode) error
- func SetTriggers(ctx context.Context, caller Caller, sessionID string, triggers []*Trigger) error
- func SetVariable(ctx context.Context, caller Caller, sessionID string, name string, ...) error
- func ShowAlert(ctx context.Context, caller Caller, title, message string, buttons []string) (int, error)
- func ShowOpenPanel(ctx context.Context, caller Caller, title, initialPath string) (string, error)
- func ShowSavePanel(ctx context.Context, caller Caller, title, initialPath string) (string, error)
- func ShowTextInputAlert(ctx context.Context, caller Caller, title, message, defaultValue string) (string, error)
- func SplitPane(ctx context.Context, caller Caller, sessionID string, vertical bool, ...) (*iterm2.SplitPaneResponse, error)
- func StringKnob(key string, defaultValue string) (string, string)
- func SupportsAddAnnotation(conn *Connection) bool
- func SupportsAdvancedKeyNotifications(conn *Connection) bool
- func SupportsAdvancedKeyUp(conn *Connection) bool
- func SupportsApplyLayout(conn *Connection) bool
- func SupportsApplyLayoutNewSession(conn *Connection) bool
- func SupportsContextMenuProviders(conn *Connection) bool
- func SupportsCoprocesses(conn *Connection) bool
- func SupportsFeature(conn *Connection, min ProtocolVersion) bool
- func SupportsFilePanels(conn *Connection) bool
- func SupportsGetDefaultProfile(conn *Connection) bool
- func SupportsListSavedArrangements(conn *Connection) bool
- func SupportsLoadURL(conn *Connection) bool
- func SupportsMoveSession(conn *Connection) bool
- func SupportsMoveSessionToTabOrWindow(conn *Connection) bool
- func SupportsMultipleSetProfile(conn *Connection) bool
- func SupportsPromptExcludedSubranges(conn *Connection) bool
- func SupportsPromptID(conn *Connection) bool
- func SupportsPromptMonitorModes(conn *Connection) bool
- func SupportsSelectPaneInDirection(conn *Connection) bool
- func SupportsStatusBarUnreadCount(conn *Connection) bool
- func TmuxRequest(ctx context.Context, caller Caller, req *iterm2.TmuxRequest) (*iterm2.TmuxResponse, error)
- type ActivateOption
- type App
- type AppleScriptAuthProvider
- type AuthProvider
- type BindingAction
- type Caller
- type CellStyle
- func (c *CellStyle) BGAlternate() (iterm2.AlternateColor, bool)
- func (c *CellStyle) BGPlacementY() (uint32, bool)
- func (c *CellStyle) BGRGB() (*iterm2.RGBColor, bool)
- func (c *CellStyle) BGStandard() (uint32, bool)
- func (c *CellStyle) Blink() bool
- func (c *CellStyle) BlockID() string
- func (c *CellStyle) Bold() bool
- func (c *CellStyle) FGAlternate() (iterm2.AlternateColor, bool)
- func (c *CellStyle) FGPlacementX() (uint32, bool)
- func (c *CellStyle) FGRGB() (*iterm2.RGBColor, bool)
- func (c *CellStyle) FGStandard() (uint32, bool)
- func (c *CellStyle) Faint() bool
- func (c *CellStyle) Guarded() bool
- func (c *CellStyle) HasBG() bool
- func (c *CellStyle) HasFG() bool
- func (c *CellStyle) Image() iterm2.ImagePlaceholderType
- func (c *CellStyle) Inverse() bool
- func (c *CellStyle) Invisible() bool
- func (c *CellStyle) Italic() bool
- func (c *CellStyle) Strikethrough() bool
- func (c *CellStyle) URL() (url, identifier string, ok bool)
- func (c *CellStyle) Underline() bool
- func (c *CellStyle) UnderlineRGB() (*iterm2.RGBColor, bool)
- type CloseOption
- type Color
- type ColorPreset
- type Connection
- func (c *Connection) Call(ctx context.Context, req *iterm2.ClientOriginatedMessage) (*iterm2.ServerOriginatedMessage, error)
- func (c *Connection) Close() error
- func (c *Connection) ConnType() string
- func (c *Connection) Connect(ctx context.Context) error
- func (c *Connection) ConnectWithWS(ctx context.Context, conn wsConn)
- func (c *Connection) Cookie() string
- func (c *Connection) Dispatch(msg *iterm2.ServerOriginatedMessage)
- func (c *Connection) IsConnected() bool
- func (c *Connection) Key() string
- func (c *Connection) OnDisconnect(fn func())
- func (c *Connection) ProtocolVersion() ProtocolVersion
- func (c *Connection) RegisterHandler(h NotificationHandler)
- func (c *Connection) Send(req *iterm2.ClientOriginatedMessage) error
- func (c *Connection) SetProtocolVersion(v ProtocolVersion)
- func (c *Connection) UnregisterHandler(h NotificationHandler)
- func (c *Connection) Unsubscribe(token NotificationToken)
- type Coord
- type CoordRange
- type CreateTabOption
- type CustomControlSequenceMonitor
- type EnvAuthProvider
- type FocusMonitor
- type FocusUpdate
- type GetBufferOption
- type GetPromptOption
- type KeystrokeAction
- type KeystrokeEvent
- func (k *KeystrokeEvent) Action() KeystrokeAction
- func (k *KeystrokeEvent) Characters() string
- func (k *KeystrokeEvent) CharactersIgnoringModifiers() string
- func (k *KeystrokeEvent) KeyCode() int32
- func (k *KeystrokeEvent) Modifiers() []iterm2.Modifiers
- func (k *KeystrokeEvent) Raw() *iterm2.KeystrokeNotification
- func (k *KeystrokeEvent) Session() string
- type KeystrokeFilter
- type KeystrokeMonitor
- type LineContent
- type LineInfo
- type ListPromptsOption
- type MenuItemState
- type NotificationHandler
- type NotificationToken
- func SubscribeBroadcastChange(ctx context.Context, caller Caller, c *Connection, ...) (NotificationToken, error)
- func SubscribeCustomEscapeSequence(ctx context.Context, caller Caller, c *Connection, ...) (NotificationToken, error)
- func SubscribeFocusChange(ctx context.Context, caller Caller, c *Connection, ...) (NotificationToken, error)
- func SubscribeKeystroke(ctx context.Context, caller Caller, c *Connection, ...) (NotificationToken, error)
- func SubscribeLayoutChange(ctx context.Context, caller Caller, c *Connection, ...) (NotificationToken, error)
- func SubscribeNewSession(ctx context.Context, caller Caller, c *Connection, ...) (NotificationToken, error)
- func SubscribeProfileChange(ctx context.Context, caller Caller, c *Connection, ...) (NotificationToken, error)
- func SubscribePrompt(ctx context.Context, caller Caller, c *Connection, ...) (NotificationToken, error)
- func SubscribeScreenUpdate(ctx context.Context, caller Caller, c *Connection, ...) (NotificationToken, error)
- func SubscribeServerOriginatedRPC(ctx context.Context, caller Caller, c *Connection, ...) (NotificationToken, error)
- func SubscribeTerminateSession(ctx context.Context, caller Caller, c *Connection, ...) (NotificationToken, error)
- func SubscribeVariableChange(ctx context.Context, caller Caller, c *Connection, ...) (NotificationToken, error)
- type Notifier
- type OpenPanelOptions
- type OpenPanelResult
- type Option
- type Point
- type PolyModalAlert
- func (a *PolyModalAlert) AddButton(label string)
- func (a *PolyModalAlert) AddCheckbox(label string, checked bool)
- func (a *PolyModalAlert) AddComboBox(items []string, defaultItem string)
- func (a *PolyModalAlert) AddTextField(placeholder, defaultValue string)
- func (a *PolyModalAlert) Run(ctx context.Context, caller Caller) (*PolyModalResult, error)
- type PolyModalResult
- type Prompt
- func (p *Prompt) Command() string
- func (p *Prompt) CommandRange() CoordRange
- func (p *Prompt) ExcludedSubranges() []CoordRange
- func (p *Prompt) ExitStatus() uint32
- func (p *Prompt) OutputRange() CoordRange
- func (p *Prompt) PromptRange() CoordRange
- func (p *Prompt) Raw() *iterm2.GetPromptResponse
- func (p *Prompt) State() PromptState
- func (p *Prompt) UniqueID() string
- func (p *Prompt) WorkingDirectory() string
- type PromptEvent
- type PromptMonitor
- type PromptState
- type ProtocolVersion
- type RPCArgs
- type RPCError
- type RPCHandler
- type RPCRPCRole
- type RPCRegistration
- type RPCRegistry
- type RestartSessionOption
- type SavePanelOptions
- type SavePanelResult
- type ScreenContents
- type ScreenStreamer
- type SendTextOption
- type Session
- func (s *Session) Close(ctx context.Context, opts ...CloseOption) error
- func (s *Session) GetBuffer(ctx context.Context, lineRange *iterm2.LineRange) (*iterm2.GetBufferResponse, error)
- func (s *Session) GetID() string
- func (s *Session) GetLineInfo(ctx context.Context) (*LineInfo, error)
- func (s *Session) GetScreenStreamer() (*ScreenStreamer, error)
- func (s *Session) GetVariable(ctx context.Context, name string) (string, error)
- func (s *Session) Inject(ctx context.Context, data []byte) error
- func (s *Session) Screenshot(ctx context.Context, path string) error
- func (s *Session) SendText(ctx context.Context, text string, opts ...SendTextOption) error
- func (s *Session) SetBadge(ctx context.Context, text string) error
- func (s *Session) SetBuried(ctx context.Context, buried bool) error
- func (s *Session) SetGridSize(ctx context.Context, width, height int32) error
- func (s *Session) SetName(ctx context.Context, name string) error
- func (s *Session) SetVariable(ctx context.Context, name, value string) error
- func (s *Session) SplitPane(ctx context.Context, vertical bool, before bool, profile string) (*Session, error)
- type Size
- type SplitChild
- type SplitPaneOption
- type Splitter
- type StatusBarComponent
- type StatusBarFormat
- type StatusBarIcon
- type Tab
- type TmuxConnection
- type Trigger
- func DecodeTrigger(encoded map[string]interface{}) (*Trigger, error)
- func GetTriggers(ctx context.Context, caller Caller, sessionID string) ([]*Trigger, error)
- func NewActivityAfterIdleEventTrigger(timeout float64) *Trigger
- func NewAlertTrigger(regex, message string) *Trigger
- func NewAnnotateTrigger(regex, annotation string) *Trigger
- func NewBellReceivedEventTrigger() *Trigger
- func NewBellTrigger(regex string) *Trigger
- func NewBounceTrigger(regex string, bounceOnce bool) *Trigger
- func NewBufferInputTrigger(regex string, start bool) *Trigger
- func NewCaptureTrigger(regex, command string) *Trigger
- func NewCommandFinishedEventTrigger(exitCodeFilter string) *Trigger
- func NewCoprocessTrigger(regex, command string) *Trigger
- func NewCustomEscapeSequenceEventTrigger(sequenceID string) *Trigger
- func NewDirectoryChangedEventTrigger(dirRegex string) *Trigger
- func NewFoldTrigger(regex, markname string) *Trigger
- func NewHighlightLineTrigger(regex, textColor, bgColor string) *Trigger
- func NewHighlightTrigger(regex, textColor, bgColor string) *Trigger
- func NewHostChangedEventTrigger(hostRegex string) *Trigger
- func NewHyperlinkTrigger(regex, url string) *Trigger
- func NewIdleEventTrigger(timeout float64) *Trigger
- func NewInjectTrigger(regex, injection string) *Trigger
- func NewLongRunningCommandEventTrigger(threshold float64, commandRegex string) *Trigger
- func NewMarkTrigger(regex string, stopScrolling bool) *Trigger
- func NewMuteCoprocessTrigger(regex, command string) *Trigger
- func NewNotificationPostedEventTrigger(messageRegex string) *Trigger
- func NewPasswordTrigger(regex, accountName, userName string) *Trigger
- func NewProgressBarChangedEventTrigger(filter string) *Trigger
- func NewPromptDetectedEventTrigger() *Trigger
- func NewRPCTrigger(regex, invocation string) *Trigger
- func NewRunCommandTrigger(regex, command string) *Trigger
- func NewSGRTrigger(regex, sgr string) *Trigger
- func NewSendTextTrigger(regex, text string) *Trigger
- func NewSessionEndedEventTrigger() *Trigger
- func NewSetDirectoryTrigger(regex, directory string) *Trigger
- func NewSetHostnameTrigger(regex, hostname string) *Trigger
- func NewSetNamedMarkTrigger(regex, markname string) *Trigger
- func NewSetTitleTrigger(regex, title string) *Trigger
- func NewSetUserVariableTrigger(regex, name, jsonValue string) *Trigger
- func NewShellPromptTrigger(regex string) *Trigger
- func NewStopTrigger(regex string) *Trigger
- func NewUserChangedEventTrigger(userRegex string) *Trigger
- func NewUserNotificationTrigger(regex, message string) *Trigger
- type TriggerMatchType
- type TriggerType
- type Window
- type WindowFocusChange
- type WindowFrame
- type WindowStatus
Constants ¶
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" )
const ( BounceUntilActivated = 0 BounceOnce = 1 )
const ( BufferInputStart = 0 BufferInputStop = 1 )
const ( ExitCodeAny = "*" ExitCodeSuccess = "0" ExitCodeNonZero = "!0" )
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 ¶
CheckboxKnob returns a (key, value) pair for a checkbox knob.
func CloseForce ¶
CloseForce closes a session with force=true. This is a convenience function equivalent to Close(ctx, caller, sessionID, WithCloseForce(true)).
func ColorKnob ¶
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 ¶
EnumerateRanges iterates over a selected range, calling fn for each line-contiguous sub-selection.
func ExitCodeFilter ¶
ExitCodeFilter returns an exit-code filter string from an int.
func FocusRequest ¶
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 ¶
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 InvokeFunction ¶
func InvokeFunction(ctx context.Context, caller Caller, req *iterm2.InvokeFunctionRequest) (*iterm2.InvokeFunctionResponse, error)
InvokeFunction invokes a registered function.
func ListColorPresets ¶
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 ¶
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 ¶
RestartSessionIfExited restarts a session only if it has exited. This is a convenience function equivalent to RestartSession(ctx, caller, sessionID, WithRestartOnlyIfExited(true)).
func Run ¶
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 ¶
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 ¶
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 SetGridSize ¶
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 ¶
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 ¶
ShowOpenPanel displays an open file panel and returns selected files.
func ShowSavePanel ¶
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 ¶
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.
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 ¶
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 ¶
type Caller interface {
Call(ctx context.Context, req *iterm2.ClientOriginatedMessage) (*iterm2.ServerOriginatedMessage, error)
Send(req *iterm2.ClientOriginatedMessage) error
}
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 ¶
BGPlacementY returns the alternate-placement-y background value.
func (*CellStyle) BGStandard ¶
BGStandard returns the standard background color.
func (*CellStyle) FGAlternate ¶
func (c *CellStyle) FGAlternate() (iterm2.AlternateColor, bool)
FGAlternate returns the alternate (semantic) foreground color.
func (*CellStyle) FGPlacementX ¶
FGPlacementX returns the alternate-placement-x foreground value.
func (*CellStyle) FGStandard ¶
FGStandard returns the standard (palette-indexed) foreground color.
func (*CellStyle) Image ¶
func (c *CellStyle) Image() iterm2.ImagePlaceholderType
Image returns the image placeholder type.
func (*CellStyle) Strikethrough ¶
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 ¶
Color represents a terminal color with optional alpha and color space.
func NewColorWithAlpha ¶
NewColorWithAlpha creates a Color with the specified alpha in the sRGB color space.
func NewColorWithColorSpace ¶
NewColorWithColorSpace creates a Color with the specified color space and full opacity.
type ColorPreset ¶
ColorPreset is a named collection of colors for terminal attributes.
func GetColorPreset ¶
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 ¶
func (c *Connection) Call(ctx context.Context, req *iterm2.ClientOriginatedMessage) (*iterm2.ServerOriginatedMessage, error)
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) 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) 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 ¶
func (c *Connection) Send(req *iterm2.ClientOriginatedMessage) error
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 ¶
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 ¶
func (m *CustomControlSequenceMonitor) Start(ctx context.Context, caller Caller) error
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 ¶
func (k *KeystrokeEvent) Raw() *iterm2.KeystrokeNotification
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 ¶
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 ¶
WithCallTimeout sets the deadline for each Call operation. Zero means no timeout (use with caution — a missing response blocks forever). Default: 30s.
func WithHandshakeTimeout ¶
WithHandshakeTimeout sets the WebSocket handshake timeout for dialing. Default: 45s.
func WithReadTimeout ¶
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 ¶
GetLastPrompt retrieves the most recent prompt for a session. Returns nil if PROMPT_UNAVAILABLE.
func GetPromptByID ¶
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) 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 ¶
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) WorkingDirectory ¶
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 ¶
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.
type RPCHandler ¶
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.
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 ¶
func (s *ScreenContents) Raw() *iterm2.GetBufferResponse
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) GetLineInfo ¶
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 ¶
GetVariable gets the value of a variable from this session. iTerm2 encodes all variable values as JSON; this method decodes them back.
func (*Session) Screenshot ¶
Screenshot captures this session's containing window and saves it as a PNG file.
func (*Session) SetGridSize ¶
SetGridSize sets the visible grid size (columns, rows) of a session.
func (*Session) SetVariable ¶
SetVariable sets a variable on this session.
type SplitChild ¶
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 ¶
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 ¶
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 ¶
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 ¶
Screenshot captures this tab's containing window and saves it as a PNG file.
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 ¶
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 ¶
CreateWindow creates a new tmux window on this connection. affinity is optional — pass "" for none. Returns the new iTerm2 tab ID.
func (*TmuxConnection) SendCommand ¶
SendCommand sends a tmux command on this connection and returns the output.
func (*TmuxConnection) SetWindowVisible ¶
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 ¶
DecodeTrigger parses a JSON-encoded trigger dict from iTerm2.
func GetTriggers ¶
GetTriggers reads triggers from the session's profile.
func NewAlertTrigger ¶
func NewAnnotateTrigger ¶
func NewBellReceivedEventTrigger ¶
func NewBellReceivedEventTrigger() *Trigger
func NewBellTrigger ¶
func NewBounceTrigger ¶
func NewBufferInputTrigger ¶
func NewCaptureTrigger ¶
func NewCoprocessTrigger ¶
func NewFoldTrigger ¶
func NewHighlightLineTrigger ¶
func NewHighlightTrigger ¶
func NewHyperlinkTrigger ¶
func NewIdleEventTrigger ¶
func NewInjectTrigger ¶
func NewMarkTrigger ¶
func NewMuteCoprocessTrigger ¶
func NewPasswordTrigger ¶
func NewPromptDetectedEventTrigger ¶
func NewPromptDetectedEventTrigger() *Trigger
func NewRPCTrigger ¶
func NewRunCommandTrigger ¶
func NewSGRTrigger ¶
func NewSendTextTrigger ¶
func NewSessionEndedEventTrigger ¶
func NewSessionEndedEventTrigger() *Trigger
func NewSetDirectoryTrigger ¶
func NewSetHostnameTrigger ¶
func NewSetNamedMarkTrigger ¶
func NewSetTitleTrigger ¶
func NewShellPromptTrigger ¶
func NewStopTrigger ¶
func (*Trigger) Actions ¶
Actions returns the decoded parameter as actions (for triggers with multiple values).
func (*Trigger) IsEvent ¶
IsEvent returns true if this is an event-based trigger (MatchType >= 100).
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).
type WindowFocusChange ¶
type WindowFocusChange struct {
WindowID string
Status WindowStatus
}
WindowFocusChange reports a window-level focus change.
type WindowFrame ¶
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 )
Source Files
¶
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 |