Documentation
¶
Overview ¶
tui/alt_screen_flash.go (pi: packages/tui/src/components/alt-screen-flash.ts)
Transient messages composited by the alternate-screen renderer. Porting note: the per-entry setTimeout expiry runs on a goroutine under the TUI lock via the injected requestRender callback's owner; pig keeps entries mutex-guarded because Flash/Dispose/Render may race with the expiry goroutine.
tui/alt_screen_search.go (pi: packages/tui/src/alt-screen-search.ts) — transcript search corpus/matching plus the bordered search overlay component with hoverable navigation buttons (v0.85.1).
Porting notes (declared deviations):
- The search corpus and match indexes operate on the rune domain; pi operates on UTF-16 code units. For BMP text (the entire test surface) the two are equivalent; astral graphemes are one match unit here vs. two code units in pi. Consistent with the repo-wide UTF-16 → rune convention (truncate batch precedent).
tui/box.go (pi: packages/tui/src/components/box.ts)
Box component - a container that applies padding and background to all children.
tui/cancellable_loader.go (pi: packages/tui/src/components/cancellable-loader.ts)
Loader that can be cancelled with Escape. Extends Loader with a cancellation handle for cancelling async operations (pi: AbortController / AbortSignal → context, per repo rules).
tui/cjk_segmenter_sst.go — SST (sorted string table) backend for the CJK word re-grouping (cjk_segmenter.go); pig-only, no pi counterpart.
Zero third-party dependencies: the same vendored zh_s/zh_t dictionaries (tui/assets/dict — see SOURCE.md) are parsed into one sorted word table — a single []byte blob plus uint32 offsets and float64 frequencies — and segmented with the classic DAG + Viterbi maximum-probability path. The algorithm mirrors gse's dag.go shape point for point: prefix-driven DAG extension (walk while some dictionary word extends the fragment), exact words as edges, single-char fallback rows, log(freq)-log(total) scoring with the longer word winning ties — so token groupings match the gse backend wherever gse's HMM is not involved.
Measured on the 587k-entry zh table (2026-09-14, dictbench probe):
- steady-state heap ~12MB (gse backend: ~206MB),
- transient allocation during the async build ~50MB peak (gse: ~300MB),
- ~29µs per cut of a 100-character run, zero allocations per cut (scratch buffers below are reused; cut is serialized by the facade mutex) — word-navigation call rates make this unmeasurable.
Declared deviations vs the gse backend:
- No HMM: out-of-vocabulary runs keep per-character tokens (gse hands single-character buffers to its HMM model). Pure-Han runs are the only input here, so gse's ASCII-run buffering cannot trigger.
- Frequencies are summed in sorted word order; gse sums in file order. Sub-ULP float rounding only — token-level behavior is pinned equal by the tests wherever it matters.
tui/colors.go (pi: packages/tui/src/colors.ts) — the Color type (palette index, sRGB, OKLCH), parseColor, color math (mix, OKLCH/OKHSL/RGB/hex conversions) and ANSI encoding (truecolor and 256-color) with styleText.
Package tui corresponds to pi's packages/tui/src.
pi: packages/tui/src/fuzzy.ts — fuzzy matching utilities. Matches if all query characters appear in order (not necessarily consecutive). Lower score = better match.
The first consumers (CLI list-models, later the session selector) need only this file of pi-tui; the rest of the package arrives with the TUI batch (Phase 6).
tui/h_stack.go (pi: packages/tui/src/components/h-stack.ts)
tui/keys.go (pi: packages/tui/src/keys.ts) — keyboard input handling for terminal applications: legacy sequences + Kitty keyboard protocol + xterm modifyOtherKeys.
Porting notes:
- TS `KeyId` is a template-literal union for autocomplete; Go uses a plain string alias (open union, README §3.4). The `Key` helper object becomes Key* constants + KeyCtrl/KeyCtrlShift/... helper functions.
- `_kittyProtocolActive` global → atomic.Bool (pi relies on the single event loop; tests are sequential, atomics keep -race clean).
- `_lastEventType` in pi is written by parseKittySequence but never read (isKeyRelease/isKeyRepeat inspect the raw data string instead) — not ported.
pi: packages/tui/src/latex.ts — LaTeX math → terminal-friendly Unicode text rendering (renderLatex + LatexParser + multi-line layout engine). Ported 2026-09-10 (was the renderLatexFn seam deferral in markdown.go, see docs/feat/LATEX.md). The seam below is wired in init(), matching pi where markdown.ts imports renderLatex directly.
Porting notes (§3.4):
- TS operates on UTF-16 code units; the parser works on []rune (pig convention). All marker characters (U+F0000–F0005) are single runes.
- The two JS lookaround spacing patterns (NAMED_OPERATOR_LEFT/RIGHT_SPACING_PATTERN) have no RE2 equivalent — replaced by manual rune scans (latexNamedOperatorSpacingLeft/Right).
- `\b` in the cases condition regex has no RE2 equivalent — replaced by an explicit non-word-character class.
tui/layout.go (pi: packages/tui/src/layout.ts)
tui/layout_node.go (pi: packages/tui/src/layout-node.ts)
Layout-node protocol shared between Stack components (this batch, T3) and the ScrollView / renderLayoutFrame machinery (pi: layout.ts — deferred to T4 with the interactive components; the scroll half of this file is deferred with it, see the section comment below).
tui/loader.go (pi: packages/tui/src/components/loader.ts)
Loader component that updates with an optional spinning animation.
Concurrency note (pig adaptation, declared): pi uses setInterval on the JS event loop; pig runs the animation on a timer goroutine. Text's render cache is mutex-guarded (see text.go); the loader's own animation state is guarded by its own mutex.
tui/markdown.go (pi: packages/tui/src/components/markdown.ts)
Markdown component: parses with the marked Lexer port (marked.go / marked_tokenizer.go / marked_rules.go) and renders the token stream to styled terminal lines itself.
Deferred (declared): pi imports renderLatex from ../latex.ts (~1380 lines, README Phase 6 "可砍/延后"). The seam below is a package-level var; the nil default makes every LaTeX token fall back to its raw text — the same rendering path pi takes for unsupported/incomplete expressions. Tests that need real math rendering stay skipped until latex.ts lands.
tui/marked.go (pi dependency: npm marked@18.0.5 — src/Lexer.js subset)
pi's Markdown component consumes `marked`'s Lexer only (it renders the token stream itself), so pig ports the Lexer: token model, block/inline tokenizers, and the lex loop. The rule tables live in marked_rules.go (generated from node dumps of the final composed regex sources).
Porting notes (declared deviations):
- JS strings index by UTF-16 code units; pig operates in rune space (helpers below). Identical for BMP characters; astral characters (emoji) shift absolute offsets — no pi test covers emoji in markdown, and token boundaries remain correct.
- JS `g`-flag regexes carry stateful lastIndex; pig passes explicit start positions (reExecFrom / scan loops).
- normal/pedantic rule variants are not ported (pi pins gfm=true, breaks=false, pedantic=false); the corresponding option checks are resolved to their gfm branches.
- marked throws on infinite-loop guards; pig panics with the same message (doRender-throw precedent).
tui/marked_rules.go — regular-expression rule tables for the marked Lexer port (pi consumes npm marked@18.0.5; pig vendors the rule table).
GENERATION: the pattern strings below are the FINAL composed regex sources dumped from node (`Lexer` default options: gfm=true, breaks=false, pedantic=false) — i.e. exactly what marked's internal regex-builder chain (`d()` + string replaces) produces at module load. Regenerating after a marked upgrade: dump `new Lexer({}).tokenizer.rules` with `v.source` / `v.flags` and re-emit. The normal/pedantic block+inline sets are not ported (pi never sets those options); declared in the file header of marked.go.
Engine note: RE2 cannot run these (backreferences \1 / \k<a>, lookaheads), so the tables compile with github.com/dlclark/regexp2 in ECMAScript mode (verified: \s incl. NBSP/BOM, \p{L/P/N/S}, named groups, backrefs, IgnoreCase).
tui/marked_tokenizer.go (marked: src/Lexer.js Tokenizer class — part of the marked.go port; see the header notes there)
tui/mouse_region.go (pi: packages/tui/src/components/mouse-region.ts)
tui/native_modifiers.go (pi: packages/tui/src/native-modifiers.ts) — native modifier-key probing helper.
pi v0.86.0 moved the platform helper loading to native-platform.ts and native-modifiers.ts became a thin delegate over getNativePlatformHelper(). pig's stub story lives in native_platform.go (no native modules in Go — see the file header there): IsNativeModifierPressed always returns false, which matches pi's "helper not available" degradation path (Shift+Enter detection falls back to the non-native input normalization).
tui/native_platform.go (pi v0.86.0: packages/tui/src/native-platform.ts) — unified native platform helper surface (clipboard + Windows VT input + modifier probing).
Declared deviation (extends the v0.85.1 native_modifiers.go note): pi loads platform .node modules (darwin-platform / win32-platform / linux-platform-x11) through native-module-path.ts candidate resolution. Go has no counterpart for that machinery — every accessor here returns nil / false. pig reaches the same functional outcomes differently:
- clipboard text/image: external platform tools (codingagent/utils/ clipboard.go, clipboard_image.go — xclip/xsel/wl-*/pbcopy/clip, osascript/pngpaste) plus OSC 52 fallbacks;
- Shift+Enter detection degrades per pi's "native helper not available" path (IsNativeModifierPressed always false);
- Windows VT input enabling (pi: enableVirtualTerminalInput) is a no-op here (see terminal.go header; WINDOWS-SUPPORT covers the size-poll half in terminal_windows.go).
The NativeClipboard interface and GetNativeClipboard are declared for structural parity with pi v0.86.0's index.ts export; the coding-agent clipboard consumers (pi: utils/clipboard.ts, utils/clipboard-image.ts) keep their external-tool paths in pig (S6-3 re-examines the seam).
tui/oklab.go (pi: packages/tui/src/oklab.ts) — Oklab and OKHSL <-> sRGB conversion. colors.go builds its OKLCH, OKHSL, and color mixing on it.
Oklab and OKHSL are Björn Ottosson's color spaces; OKHSL's saturation is relative to the sRGB gamut at each hue and lightness. This is a port of his reference implementation (https://bottosson.github.io/posts/colorpicker/), Copyright (c) 2021 Björn Ottosson, used under the MIT license:
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.
tui/program_status (pi: packages/tui/src/program-status.ts, S17 503c60552) — Program Status Protocol (OSC 7501): a program tells the terminal whether it is idle, working, blocked on the user, done, or failed. Only the root record is supported.
Spec: https://www.superlogical.com/rex/docs/build/program-status
tui/scroll_view.go (pi: packages/tui/src/components/scroll-view.ts)
Porting notes (declared deviations):
- Concurrency: pi serializes ScrollView access on the JS event loop. pig guards the state with its own mutex. requestRenderCallback is always invoked OUTSIDE the lock: the layout engine calls UpdateLayout while holding the TUI lock, and a concurrent ScrollBy holding the ScrollView lock must not block on the TUI lock inside the callback (deadlock).
- NodeJS.Timeout.unref() has no Go equivalent (timers don't keep a Go process alive); dropped.
tui/settings_list.go (pi: packages/tui/src/components/settings-list.ts)
tui/spacer.go (pi: packages/tui/src/components/spacer.ts)
Spacer component that renders empty lines.
tui/stack.go (pi: packages/tui/src/components/stack.ts)
Stack flex-layout base shared by VStack and HStack (pi: abstract class Stack extends Container). Go has no abstract classes: the layoutType is a plain field set by the subclass constructors, and Stack itself is only embedded.
tui/stdin_buffer.go (pi: packages/tui/src/stdin-buffer.ts) — buffers input and emits complete sequences.
Stdin data events can arrive in partial chunks, especially for escape sequences like mouse events. Without buffering, partial sequences can be misinterpreted as regular keypresses. For example, the mouse SGR sequence `\x1b[<35;20;5m` might arrive as three chunks.
Based on code from OpenTUI (https://github.com/anomalyco/opentui) MIT License - Copyright (c) 2025 opentui
Porting notes:
- EventEmitter ('data'/'paste') → single handler functions registered via OnData/OnPaste (pi has exactly one listener per event; multi-listener EventEmitter semantics unused — declared deviation).
- setTimeout flush timers → time.AfterFunc; process/flush/timer callbacks are serialized with a single mutex (pi: event loop ordering).
- Events are collected during Process and dispatched after the mutex is released, in emission order (pi emits synchronously inside process; ordering is preserved).
- Process takes []byte: the single-high-byte → ESC+(b-128) legacy meta conversion is kept. Raw multi-byte input is assumed to arrive on valid UTF-8 boundaries; ProcessTerminal pre-decodes partial UTF-8 tails (Node's setEncoding semantics).
tui/terminal.go (pi: packages/tui/src/terminal.ts) — minimal terminal interface for the TUI plus the real-terminal implementation.
Porting notes (declared deviations):
- Node process.stdin/stdout → injectable in/out io.Reader/io.Writer fields (default os.Stdin/os.Stdout). pi's tests monkey-patch process.stdout.write / process.stdin.on; Go tests inject pipes instead.
- Node raw mode → golang.org/x/term MakeRaw/Restore (saved termios is the wasRaw equivalent).
- process.stdout 'resize' event → SIGWINCH via signal.Notify goroutine (POSIX half lives in terminal_unix.go; Windows polls the console size instead — terminal_windows.go, WINDOWS-SUPPORT 2026-09-14).
- setEncoding('utf8') → incremental UTF-8 decode in the stdin read loop (StringDecoder semantics for multibyte sequences split across reads).
- enableWindowsVTInput and the win32-console-mode native helper have no Go counterpart — no-op (see native_platform.go).
- drainInput returns Promise<void> → blocking method.
tui/terminal_colors.go (pi: packages/tui/src/terminal-colors.ts) — colors the terminal reports for its current theme: OSC 10/11/4 color replies and color-scheme reports (CSI ? 997 n).
tui/terminal_image.go (pi: packages/tui/src/terminal-image.ts) — minimal subset consumed by the T1 core (tui.ts / tui-main-screen.ts) plus the Kitty metadata/registration/placement/crop half consumed by the alt-screen layout machinery (T4): Kitty image line detection, image deletion escapes, Kitty image encoding, cell dimensions, capability cache, and the registered-metadata placement/crop helpers.
Porting scope (declared, README §4 Phase 8):
- The image half of the terminal detection machinery (OSC queries, tmux probing, iTerm2 protocol, Image component, sixel/iterm rendering) is deferred to Phase 8 with the image pipeline. GetCapabilities returns a non-image result until then; SetCapabilities keeps the test seam. The metadata/registry functions ported here are pure string/escape helpers with no detection dependency.
- The `trueColor` branch of pi's detectCapabilitiesFromEnvironment *is* ported (2026-10-01 fix): the theme picked its color mode from it, so leaving it at false silently quantized every theme color to the 256-color palette. The `hyperlinks` branch is ported for the terminals S16-3 brought (Herdr, pi b2363841a); its remaining branches (the tmux client_termfeatures probe and the kitty/ghostty/... families) stay deferred together with the images half and the Phase 8 image pipeline.
tui/text.go (pi: packages/tui/src/components/text.ts)
Text component - displays multi-line text with word wrapping.
Concurrency note (pig adaptation, declared): pi runs everything on the JS event loop, so the render cache needs no guarding. Loader embeds Text and advances its spinner from a timer goroutine that calls SetText while the render goroutine may be inside Render — the cache fields are guarded by a mutex here (behavior identical in single-threaded use).
tui/truncated_text.go (pi: packages/tui/src/components/truncated-text.ts)
Text component that truncates to fit viewport width.
tui/tui.go (pi: packages/tui/src/tui.ts) — minimal TUI implementation with differential rendering: Component model, overlay stack, focus handling, render scheduling, and terminal query helpers.
Porting notes (declared deviations):
- Concurrency: pi serializes everything on the JS event loop. pig uses a single TUI mutex; TUI methods are executed through tui.lock(), which runs inline when already dispatching on the same goroutine — this reproduces the event-loop reentrancy (component input handlers may call back into TUI methods) without deadlocks.
- process.nextTick → goroutine; the 16ms render throttle uses time.AfterFunc. The JS microtask coalescing order is preserved by the same renderRequested/immediateRenderScheduled flags.
- Component optional members (handleInput/wantsKeyRelease/focused) → capability interfaces InputHandler / KeyReleaseOptIn / Focusable.
- The `Key` struct of overlay options unions `number | "50%"` → any (int or percent string), type-switched in parseSizeValue.
- queryTerminalBackgroundColor/queryTerminalColorScheme return Promises → blocking calls resolving on reply or timeout (channel + timer).
- ViewportTUI is the marker interface for viewport-scrolling TUIs (pi: VIEWPORT_TUI symbol); TuiAltScreen implements it (T4); the RPC client consumes it (Phase 5, deferred).
- containsComponent traverses children through the childContainer interface (Container embedders expose it via method promotion); pi duck-types on the .children property, which covers the same set of components in practice.
- terminal-image detection is a Phase 8 stub (see terminal_image.go); queryCellSize is a no-op until image capabilities exist.
tui/tui_alt_screen.go (pi: packages/tui/src/tui-alt-screen.ts) — alternate-screen TUI with a scrollable, application-owned viewport: mouse wheel routing/overscroll chaining, SGR mouse selection (character/ word/line granularity + drag auto-scroll), scrollbar hit-testing and dragging, OSC 8 hyperlink activation, transcript search overlay, flash messages, Kitty image placement reuse/eviction, and full/differential rendering with search + selection + flash compositing.
Porting notes (declared deviations):
- Concurrency: pi serializes all state on the JS event loop; every input listener invocation, render, and timer callback shares one thread. pig guards the subclass state with the inherited TuiBase mutex: input dispatch and doRender run under b.lock(); the selection auto-scroll interval and flash expiry run on goroutines that re-enter b.lock() (same serialization). State accessors lock; doRender does NOT re-lock (TuiMainScreen locking note applies).
- copySelection returns Promise<boolean> → synchronous callback (repo rule: pi promise callbacks → sync signatures).
- process.platform → altScreenPlatform package var (test seam); env probes use os.Getenv.
- The two Image-component-driven paths (constructing Image components) are exercised only by tests skipped for Phase 8; the placement/crop machinery itself is fully ported.
tui/tui_main_screen.go (pi: packages/tui/src/tui-main-screen.ts) — TUI implementation that renders into the terminal's main screen and scrollback.
Porting notes:
- pi's doRender throws on over-wide rendered lines (crashes the process); the Go doRender returns the error and the render scheduler panics with it (equivalent process-fatal behavior, see tui.go doRenderOrPanic).
- PI_TUI_DEBUG_REDRAW / PI_TUI_DEBUG file logging and the crash log are kept (fs → os). logDirectory empty disables debug logging; the crash log falls back to os.TempDir() (pi: logDirectory ?? os.tmpdir(), pi-tui-crash.log).
- Kitty image handling uses the terminal_image.go subset (Phase 8 keeps full image rendering out of scope; placement sequences remain opaque strings and are diffed/cleared exactly as pi does).
tui/v_stack.go (pi: packages/tui/src/components/v-stack.ts)
tui/virtual_terminal_test.go — Go replacement for pi's test/virtual-terminal.ts (which wraps @xterm/headless). Implements the Terminal interface backed by a minimal VT emulator covering exactly the control sequences the TUI emits:
printable text (with autowrap + wide-char placeholders) CSI A/B (cursor up/down), G (CHA), H (home), J (0/2/3 erase), K (erase line) CSI ?2004h/l (bracketed paste), ?2026h/l (sync output), ?25l/h (cursor), ?2031h/l (color scheme), 16t (cell size query) OSC ... BEL / OSC ... ST (titles, hyperlinks, color reports) — skipped APC/DCS ... ST (cursor marker, Kitty graphics) — skipped \r, \n (+ scroll at bottom), BEL
Attribute tracking (SGR) is limited to italic/underline/bold/inverse — enough for applyLineResets assertions (pi uses cell.isItalic()).
tui/wheel_scroll.go (pi: packages/tui/src/wheel-scroll.ts) — wheel event acceleration: converts wheel events into line counts, with `"auto"` mode following event velocity for terminals that send one event per notch.
Index ¶
- Constants
- Variables
- func AllocateImageId() int
- func AllocateStackSizes(entries []StackLayoutEntry, intrinsicSizes []int, availableSize *int, gap int) []int
- func ApplyBackgroundToLine(line string, width int, bgFn func(text string) string) string
- func BackgroundAnsi(color Color, mode TerminalColorMode) string
- func ColorToHex(color Color) string
- func CompositeTuiLine(baseLine string, overlayLine string, startCol int, overlayWidth int, ...) string
- func CropKittyImageLine(line string, hiddenRows int, visibleRows int) string
- func DecodeKittyPrintable(data string) (string, bool)
- func DecodePrintableKey(data string) (string, bool)
- func DeleteAllKittyImages() string
- func DeleteAllKittyPlacements() string
- func DeleteKittyImage(imageId int) string
- func EncodeKitty(base64Data string, options EncodeKittyParams) string
- func FindWordBackward(text string, cursor int, options *WordNavigationOptions) int
- func FindWordForward(text string, cursor int, options *WordNavigationOptions) int
- func ForegroundAnsi(color Color, mode TerminalColorMode) string
- func FuzzyFilter[T any](items []T, query string, getText func(item T) string) []T
- func GetActiveBackgroundAnsi(text string) string
- func GetAltScreenSearchMatchKey(match AltScreenSearchMatch) string
- func GetKittyImagePlacementRows(line string) int
- func GetOsc8LinkAtColumn(line string, column int) string
- func Hyperlink(text string, url string) string
- func ImageFallback(mimeType string, dimensions *ImageDimensions, filename string) string
- func IsAppleTerminalSession() bool
- func IsImageLine(line string) bool
- func IsKeyRelease(data string) bool
- func IsKeyRepeat(data string) bool
- func IsKittyProtocolActive() bool
- func IsNativeModifierPressed(key ModifierKey) bool
- func IsPunctuationChar(char string) bool
- func IsValidKeyId(keyId string) bool
- func IsWhitespaceChar(char string) bool
- func KeyAlt(key string) string
- func KeyAltCtrl(key string) string
- func KeyAltShift(key string) string
- func KeyAltSuper(key string) string
- func KeyCtrl(key string) string
- func KeyCtrlAlt(key string) string
- func KeyCtrlShift(key string) string
- func KeyCtrlShiftAlt(key string) string
- func KeyCtrlShiftSuper(key string) string
- func KeyCtrlSuper(key string) string
- func KeyShift(key string) string
- func KeyShiftAlt(key string) string
- func KeyShiftCtrl(key string) string
- func KeyShiftSuper(key string) string
- func KeySuper(key string) string
- func KeySuperAlt(key string) string
- func KeySuperCtrl(key string) string
- func KeySuperShift(key string) string
- func MatchesKey(data string, keyId KeyId) bool
- func NormalizeAppleTerminalInput(data string, isAppleTerminal bool, isShiftPressed bool) string
- func NormalizeNativeShiftEnterInput(data string, shouldDetectNativeShiftEnter bool, isShiftPressed bool) string
- func NormalizeTerminalOutput(str string) string
- func NowMillis() float64
- func OklabToLinearSrgb(lab vector3) vector3
- func OklabToOkhslLightness(x float64) float64
- func ParseKey(data string) (string, bool)
- func ParseOscColorResponse(data string) (OscColorTarget, *RgbColor, bool)
- func RegisterKittyImageMetadata(metadata KittyImageMetadata)
- func RenderFakeCursor(text string) string
- func RenderLatex(source string, display bool) (string, bool)
- func ResetCapabilitiesCache()
- func ResolveEscapeTimeoutMs() int
- func RestoreActiveOnExit()
- func RgbToOklab(c RgbColor) vector3
- func SetCJKSegmenterMode(value string)
- func SetCapabilities(caps TerminalCapabilities)
- func SetCapabilityOverrides(overrides TerminalCapabilityOverrides)
- func SetCellDimensions(dims CellDimensions)
- func SetKeybindings(keybindings *KeybindingsManager)
- func SetKittyProtocolActive(active bool)
- func SliceByColumn(line string, startCol int, length int, strict bool) string
- func StripTerminalSequences(str string) string
- func StyleText(text string, options TextStyle, mode TerminalColorMode) string
- func StyleTextWithAnsi(text string, fgAnsi string, bgAnsi string, options TextAttributes) string
- func TruncateToWidth(text string, maxWidth int, ellipsis string, pad bool) string
- func VisibleWidth(str string) int
- func WrapTextWithAnsi(text string, width int) []string
- type AltScreenFlashContainer
- type AltScreenSearchComponent
- func (c *AltScreenSearchComponent) GetFocused() bool
- func (c *AltScreenSearchComponent) GetNavigationDirectionAt(row int, column int) int
- func (c *AltScreenSearchComponent) HandleInput(data string)
- func (c *AltScreenSearchComponent) Invalidate()
- func (c *AltScreenSearchComponent) Render(width int) []string
- func (c *AltScreenSearchComponent) SetFocused(value bool)
- func (c *AltScreenSearchComponent) SetHoveredNavigationDirection(direction int) bool
- func (c *AltScreenSearchComponent) SetResult(index int, count int)
- type AltScreenSearchIndex
- type AltScreenSearchMatch
- type AltScreenSearchResult
- type AltScreenSearchSegment
- type AnsiCode
- type AutocompleteApplyResult
- type AutocompleteGetSuggestionsOptions
- type AutocompleteItem
- type AutocompleteProvider
- type AutocompleteSuggestions
- type Box
- func (b *Box) AddChild(component Component)
- func (b *Box) Clear()
- func (b *Box) HandleMouse(event *TuiMouseEvent) *TuiMouseEventResult
- func (b *Box) Invalidate()
- func (b *Box) RemoveChild(component Component)
- func (b *Box) Render(width int) []string
- func (b *Box) SetBgFn(bgFn func(text string) string)
- type CancellableLoader
- type CellDimensions
- type Color
- func MixColors(first, second Color, amount float64, space ColorMixSpace) (Color, error)
- func NewIndexedColor(index int) (Color, error)
- func NewOkhslColor(h, s, l float64) (Color, error)
- func NewOklchColor(l, c, h float64) (Color, error)
- func NewRgbColor(r, g, b int) (Color, error)
- func ParseColor(value any) (Color, error)
- type ColorKind
- type ColorMixSpace
- type CombinedAutocompleteProvider
- func (p *CombinedAutocompleteProvider) ApplyCompletion(lines []string, cursorLine int, cursorCol int, item AutocompleteItem, ...) AutocompleteApplyResult
- func (p *CombinedAutocompleteProvider) GetSuggestions(ctx context.Context, lines []string, cursorLine int, cursorCol int, ...) *AutocompleteSuggestions
- func (p *CombinedAutocompleteProvider) SetTriggerCharacters(chars []string)
- func (p *CombinedAutocompleteProvider) ShouldTriggerFileCompletion(lines []string, cursorLine int, cursorCol int) bool
- func (p *CombinedAutocompleteProvider) TriggerCharacters() []string
- type Component
- type Container
- type CopySelectionResult
- type CursorPosition
- type DefaultTextStyle
- type Editor
- func (e *Editor) AddToHistory(text string)
- func (e *Editor) GetAutocompleteMaxVisible() int
- func (e *Editor) GetAutocompleteProvider() AutocompleteProvider
- func (e *Editor) GetCursor() EditorCursor
- func (e *Editor) GetExpandedText() string
- func (e *Editor) GetFocused() bool
- func (e *Editor) GetLines() []string
- func (e *Editor) GetPaddingX() int
- func (e *Editor) GetText() string
- func (e *Editor) HandleInput(data string)
- func (e *Editor) HandleMouse(event *TuiMouseEvent) *TuiMouseEventResult
- func (e *Editor) InsertTextAtCursor(text string)
- func (e *Editor) Invalidate()
- func (e *Editor) IsShowingAutocomplete() bool
- func (e *Editor) Render(width int) []string
- func (e *Editor) SetAutocompleteMaxVisible(maxVisible int)
- func (e *Editor) SetAutocompleteProvider(provider AutocompleteProvider)
- func (e *Editor) SetFocused(focused bool)
- func (e *Editor) SetPaddingX(padding int)
- func (e *Editor) SetText(text string)
- type EditorComponent
- type EditorComponentAppearance
- type EditorComponentAutocomplete
- type EditorComponentExpandedText
- type EditorComponentHistory
- type EditorComponentTextInsertion
- type EditorCursor
- type EditorOptions
- type EditorTheme
- type EncodeKittyParams
- type ExitRestorer
- type FileCompletionTriggerer
- type Focusable
- type FuzzyMatch
- type GraphemeCellRange
- type GraphemeSegmenter
- type HStack
- type ImageDimensions
- func GetGifDimensions(base64Data string) *ImageDimensions
- func GetImageDimensions(base64Data string, mimeType string) *ImageDimensions
- func GetJpegDimensions(base64Data string) *ImageDimensions
- func GetPngDimensions(base64Data string) *ImageDimensions
- func GetWebpDimensions(base64Data string) *ImageDimensions
- type Input
- func (i *Input) GetFocused() bool
- func (i *Input) GetValue() string
- func (i *Input) HandleInput(data string)
- func (i *Input) HandleMouse(event *TuiMouseEvent) *TuiMouseEventResult
- func (i *Input) Invalidate()
- func (i *Input) Render(width int) []string
- func (i *Input) SetFocused(focused bool)
- func (i *Input) SetValue(value string)
- type InputHandler
- type InputOptions
- type KeyEventType
- type KeyId
- type KeyReleaseOptIn
- type Keybinding
- type KeybindingConflict
- type KeybindingDefinition
- type KeybindingDefinitions
- type KeybindingsConfig
- type KeybindingsManager
- func (m *KeybindingsManager) GetConflicts() []KeybindingConflict
- func (m *KeybindingsManager) GetDefinition(keybinding Keybinding) KeybindingDefinition
- func (m *KeybindingsManager) GetKeys(keybinding Keybinding) []KeyId
- func (m *KeybindingsManager) GetResolvedBindings() KeybindingsConfig
- func (m *KeybindingsManager) GetUserBindings() KeybindingsConfig
- func (m *KeybindingsManager) Matches(data string, keybinding Keybinding) bool
- func (m *KeybindingsManager) SetUserBindings(userBindings KeybindingsConfig)
- type KeyboardProtocolNegotiationSequence
- type KillRing
- type KillRingPushOptions
- type KittyImageMetadata
- type KittyImagePlacement
- type LayoutBox
- type LayoutComponent
- type LayoutFrame
- type LayoutNode
- type LayoutRect
- type LayoutViewport
- type Loader
- type LoaderIndicatorOptions
- type Markdown
- type MarkdownOptions
- type MarkdownTheme
- type MarkedToken
- type ModifierKey
- type MouseHandler
- type MouseRegion
- type MouseRegionHandler
- type NativeClipboard
- type OkhslChannels
- type OklchChannels
- type OscColorTarget
- type OverlayAnchor
- type OverlayBounds
- type OverlayHandle
- type OverlayMargin
- type OverlayOptions
- type OverlayUnfocusOptions
- type ProcessTerminal
- func (t *ProcessTerminal) ClearFromCursor()
- func (t *ProcessTerminal) ClearLine()
- func (t *ProcessTerminal) ClearScreen()
- func (t *ProcessTerminal) Columns() int
- func (t *ProcessTerminal) DrainInput(maxMs int, idleMs int)
- func (t *ProcessTerminal) HideCursor()
- func (t *ProcessTerminal) KittyProtocolActive() bool
- func (t *ProcessTerminal) ModifyOtherKeysActive() bool
- func (t *ProcessTerminal) MoveBy(lines int)
- func (t *ProcessTerminal) RestoreOnExit(before string, after string)
- func (t *ProcessTerminal) Rows() int
- func (t *ProcessTerminal) SetProgramStatus(status ProgramStatus)
- func (t *ProcessTerminal) SetProgress(active bool)
- func (t *ProcessTerminal) SetTitle(title string)
- func (t *ProcessTerminal) ShowCursor()
- func (t *ProcessTerminal) Start(onInput func(data string), onResize func())
- func (t *ProcessTerminal) Stop()
- func (t *ProcessTerminal) Write(data string)
- type ProgramStatus
- type ProgramStatusBlockedKind
- type ProgramStatusState
- type RgbColor
- type ScrollLayoutNode
- type ScrollLayoutState
- type ScrollView
- func (s *ScrollView) AddChild(_ Component)
- func (s *ScrollView) Clear()
- func (s *ScrollView) FollowEnd() bool
- func (s *ScrollView) GetContentWidth(width int) int
- func (s *ScrollView) IsFollowingEnd() bool
- func (s *ScrollView) IsScrollbarActive() bool
- func (s *ScrollView) IsScrollbarVisible() bool
- func (s *ScrollView) LayoutNode() LayoutNode
- func (s *ScrollView) Overscroll() string
- func (s *ScrollView) Primary() bool
- func (s *ScrollView) RemoveChild(_ Component)
- func (s *ScrollView) Render(width int) []string
- func (s *ScrollView) ScrollBy(lines int) int
- func (s *ScrollView) ScrollTo(scrollTop int, options *ScrollViewScrollToOptions)
- func (s *ScrollView) ScrollToEnd()
- func (s *ScrollView) ScrollToStart()
- func (s *ScrollView) ScrollTop() int
- func (s *ScrollView) Scrollbar() ScrollViewScrollbar
- func (s *ScrollView) ScrollbarThumbStyle(text string) string
- func (s *ScrollView) ScrollbarTrackStyle(text string) string
- func (s *ScrollView) SetScrollbar(scrollbar ScrollViewScrollbar)
- func (s *ScrollView) SetScrollbarActive(active bool)
- func (s *ScrollView) UpdateLayout(contentHeight int, viewportHeight int, requestRender func())
- func (s *ScrollView) ViewportHeight() int
- type ScrollViewOptions
- type ScrollViewScrollToOptions
- type ScrollViewScrollbar
- type ScrollbarGeometry
- type SegmentData
- type SegmenterFunc
- type SegmentsResult
- type SelectItem
- type SelectList
- func (s *SelectList) GetSelectedItem() *SelectItem
- func (s *SelectList) HandleInput(keyData string)
- func (s *SelectList) HandleMouse(event *TuiMouseEvent) *TuiMouseEventResult
- func (s *SelectList) Invalidate()
- func (s *SelectList) Render(width int) []string
- func (s *SelectList) SetFilter(filter string)
- func (s *SelectList) SetSelectedIndex(index int)
- type SelectListLayoutOptions
- type SelectListTheme
- type SelectListTruncatePrimaryContext
- type SettingItem
- type SettingsList
- func (l *SettingsList) HandleInput(data string)
- func (l *SettingsList) HandleMouse(event *TuiMouseEvent) *TuiMouseEventResult
- func (l *SettingsList) Invalidate()
- func (l *SettingsList) Render(width int) []string
- func (l *SettingsList) SelectItem(id string)
- func (l *SettingsList) UpdateValue(id string, newValue string)
- type SettingsListOptions
- type SettingsListTheme
- type SettingsSubmenuDoneOptions
- type SlashCommand
- type SlashCommandOrItem
- type SliceResult
- type Spacer
- type Stack
- type StackChild
- type StackEntry
- type StackEntryOptions
- type StackLayoutEntry
- type StackLayoutNode
- type StackOptions
- type StdinBuffer
- func (b *StdinBuffer) Clear()
- func (b *StdinBuffer) Destroy()
- func (b *StdinBuffer) Flush() []string
- func (b *StdinBuffer) GetBuffer() string
- func (b *StdinBuffer) OnData(handler func(string))
- func (b *StdinBuffer) OnPaste(handler func(string))
- func (b *StdinBuffer) Process(data []byte)
- func (b *StdinBuffer) ProcessString(data string)
- type TUI
- type Terminal
- type TerminalCapabilities
- type TerminalCapabilityOverrides
- type TerminalColorMode
- type TerminalColorScheme
- type TerminalColors
- type Text
- type TextAttributes
- type TextChunk
- type TextStyle
- type TriggerCharactersProvider
- type TriggerCharactersSetter
- type TruncatedText
- type TuiAltScreen
- func (t *TuiAltScreen) CopyActiveSelectionToClipboard() bool
- func (t *TuiAltScreen) Flash(message string, durationMs int)
- func (t *TuiAltScreen) GetCopyOnSelect() bool
- func (t *TuiAltScreen) HasActiveSelection() bool
- func (t *TuiAltScreen) IsFollowingOutput() bool
- func (t *TuiAltScreen) Render(width int) []string
- func (t *TuiAltScreen) ResetTextSelection()
- func (t *TuiAltScreen) ScrollBy(lines int)
- func (t *TuiAltScreen) ScrollToBottom()
- func (t *TuiAltScreen) ScrollToEndIndicatorRect() *altScrollToEndIndicatorRect
- func (t *TuiAltScreen) ScrollToTop()
- func (t *TuiAltScreen) SetCopyOnSelect(enabled bool)
- func (t *TuiAltScreen) SetLayoutRoot(component Component)
- func (t *TuiAltScreen) SetWheelScrollLines(lines int)
- func (t *TuiAltScreen) ViewportTop() int
- type TuiAltScreenOptions
- type TuiBase
- func (b *TuiBase) AddInputListener(listener TuiInputListener) func()
- func (b *TuiBase) FullRedraws() int
- func (b *TuiBase) GetClearOnShrink() bool
- func (b *TuiBase) GetFocusedComponent() Component
- func (b *TuiBase) GetShowHardwareCursor() bool
- func (b *TuiBase) HasOverlay() bool
- func (b *TuiBase) HasOverlayEntries() bool
- func (b *TuiBase) HideOverlay()
- func (b *TuiBase) Invalidate()
- func (b *TuiBase) Mode() TuiMode
- func (b *TuiBase) OnTerminalColorSchemeChange(listener func(scheme TerminalColorScheme)) func()
- func (b *TuiBase) QueryTerminalColors(timeoutMs int, onLateReply func(TerminalColors)) TerminalColors
- func (b *TuiBase) RemoveInputListener(listener TuiInputListener)
- func (b *TuiBase) RenderNow(force bool)
- func (b *TuiBase) RequestRender(force bool)
- func (b *TuiBase) RunExclusive(fn func())
- func (b *TuiBase) SetClearOnShrink(enabled bool)
- func (b *TuiBase) SetFocus(component Component)
- func (b *TuiBase) SetShowHardwareCursor(enabled bool)
- func (b *TuiBase) SetTerminalColorSchemeNotifications(enabled bool)
- func (b *TuiBase) ShowOverlay(component Component, options *OverlayOptions) OverlayHandle
- func (b *TuiBase) Start()
- func (b *TuiBase) Stop(options *TuiStopOptions)
- func (b *TuiBase) Terminal() Terminal
- type TuiInputListener
- type TuiInputListenerResult
- type TuiMainScreen
- type TuiMainScreenRenderState
- type TuiMode
- type TuiMouseButton
- type TuiMouseDispatchTarget
- type TuiMouseEvent
- type TuiMouseEventResult
- type TuiMouseEventType
- type TuiStopOptions
- type UndoStack
- type VStack
- type ViewportTUI
- type VirtualTerminal
- func (v *VirtualTerminal) ClearFromCursor()
- func (v *VirtualTerminal) ClearLine()
- func (v *VirtualTerminal) ClearScreen()
- func (v *VirtualTerminal) ClearWrites()
- func (v *VirtualTerminal) Columns() int
- func (v *VirtualTerminal) DrainInput(maxMs int, idleMs int)
- func (v *VirtualTerminal) GetCellBold(row, col int) bool
- func (v *VirtualTerminal) GetCellItalic(row, col int) bool
- func (v *VirtualTerminal) GetCellUnderline(row, col int) bool
- func (v *VirtualTerminal) GetCursorPosition() (x, y int)
- func (v *VirtualTerminal) GetCursorVisible() bool
- func (v *VirtualTerminal) GetScrollBuffer() []string
- func (v *VirtualTerminal) GetViewport() []string
- func (v *VirtualTerminal) GetWrites() string
- func (v *VirtualTerminal) HideCursor()
- func (v *VirtualTerminal) KittyProtocolActive() bool
- func (v *VirtualTerminal) MoveBy(lines int)
- func (v *VirtualTerminal) Resize(columns, rows int)
- func (v *VirtualTerminal) Rows() int
- func (v *VirtualTerminal) SendInput(data string)
- func (v *VirtualTerminal) SetProgramStatus(status ProgramStatus)
- func (v *VirtualTerminal) SetProgress(active bool)
- func (v *VirtualTerminal) SetTitle(title string)
- func (v *VirtualTerminal) ShowCursor()
- func (v *VirtualTerminal) Start(onInput func(data string), onResize func())
- func (v *VirtualTerminal) Stop()
- func (v *VirtualTerminal) WaitForRender()
- func (v *VirtualTerminal) Write(data string)
- type WheelScrollAccelerator
- type WordNavigationOptions
- type WordSegmenter
Constants ¶
const CursorMarker = "\x1b_pi:c\x07"
CursorMarker is a zero-width APC escape sequence that terminals ignore. Components emit this at the cursor position when focused. TUI finds and strips this marker, then positions the hardware cursor there. (pi: CURSOR_MARKER)
const FakeCursorEnd = "\x1b_pi:/fc\x07"
const FakeCursorStart = "\x1b_pi:fc\x07"
Fake cursor markers - zero-width APC sequences around the text drawn as the cursor. See resolveFakeCursors. (pi: FAKE_CURSOR_START / FAKE_CURSOR_END)
const ProgramStatusQuery = "\x1b]7501;?\x1b\\"
ProgramStatusQuery is the feature detection query. A supporting terminal replies with the same body (pi: PROGRAM_STATUS_QUERY).
const WheelScrollLinesAuto = 0
WheelScrollLinesAuto is the sentinel for `"auto"`: lines per wheel event follow event velocity (pi: WheelScrollLines = number | "auto"). Fixed settings use 1-100; values below 1 behave as 1.
Variables ¶
var PUNCTUATION_REGEX = regexp.MustCompile("[(){}\\[\\]<>.,;:'\"!?+\\-=*/\\\\|&%^$#@~\x60]")
PUNCTUATION_REGEX matches pi's /[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/.
var TUIKeyBindings = KeybindingDefinitions{ "tui.editor.cursorUp": {DefaultKeys: []KeyId{"up"}, Description: "Move cursor up"}, "tui.editor.cursorDown": {DefaultKeys: []KeyId{"down"}, Description: "Move cursor down"}, "tui.editor.historyPrevious": {DefaultKeys: []KeyId{}, Description: "Select previous prompt history entry"}, "tui.editor.historyNext": {DefaultKeys: []KeyId{}, Description: "Select next prompt history entry"}, "tui.editor.cursorLeft": {DefaultKeys: []KeyId{"left", "ctrl+b"}, Description: "Move cursor left"}, "tui.editor.cursorRight": {DefaultKeys: []KeyId{"right", "ctrl+f"}, Description: "Move cursor right"}, "tui.editor.cursorWordLeft": {DefaultKeys: []KeyId{"alt+left", "ctrl+left", "alt+b"}, Description: "Move cursor word left"}, "tui.editor.cursorWordRight": {DefaultKeys: []KeyId{"alt+right", "ctrl+right", "alt+f"}, Description: "Move cursor word right"}, "tui.editor.cursorLineStart": {DefaultKeys: []KeyId{"home", "ctrl+a"}, Description: "Move to line start"}, "tui.editor.cursorLineEnd": {DefaultKeys: []KeyId{"end", "ctrl+e"}, Description: "Move to line end"}, "tui.editor.jumpForward": {DefaultKeys: []KeyId{"ctrl+]"}, Description: "Jump forward to character"}, "tui.editor.jumpBackward": {DefaultKeys: []KeyId{"ctrl+alt+]"}, Description: "Jump backward to character"}, "tui.editor.pageUp": {DefaultKeys: []KeyId{"pageUp", "ctrl+pageUp"}, Description: "Page up"}, "tui.editor.pageDown": {DefaultKeys: []KeyId{"pageDown", "ctrl+pageDown"}, Description: "Page down"}, "tui.editor.deleteCharBackward": {DefaultKeys: []KeyId{"backspace"}, Description: "Delete character backward"}, "tui.editor.deleteCharForward": {DefaultKeys: []KeyId{"delete", "ctrl+d"}, Description: "Delete character forward"}, "tui.editor.deleteWordBackward": {DefaultKeys: []KeyId{"ctrl+w", "alt+backspace"}, Description: "Delete word backward"}, "tui.editor.deleteWordForward": {DefaultKeys: []KeyId{"alt+d", "alt+delete"}, Description: "Delete word forward"}, "tui.editor.deleteToLineStart": {DefaultKeys: []KeyId{"ctrl+u"}, Description: "Delete to line start"}, "tui.editor.deleteToLineEnd": {DefaultKeys: []KeyId{"ctrl+k"}, Description: "Delete to line end"}, "tui.editor.yank": {DefaultKeys: []KeyId{"ctrl+y"}, Description: "Yank"}, "tui.editor.yankPop": {DefaultKeys: []KeyId{"alt+y"}, Description: "Yank pop"}, "tui.editor.undo": {DefaultKeys: []KeyId{"ctrl+-"}, Description: "Undo"}, "tui.input.newLine": {DefaultKeys: []KeyId{"shift+enter", "ctrl+j"}, Description: "Insert newline"}, "tui.input.submit": {DefaultKeys: []KeyId{"enter"}, Description: "Submit input"}, "tui.input.tab": {DefaultKeys: []KeyId{"tab"}, Description: "Tab / autocomplete"}, "tui.input.copy": {DefaultKeys: []KeyId{"ctrl+c"}, Description: "Copy selection"}, "tui.select.up": {DefaultKeys: []KeyId{"up"}, Description: "Move selection up"}, "tui.select.down": {DefaultKeys: []KeyId{"down"}, Description: "Move selection down"}, "tui.select.pageUp": {DefaultKeys: []KeyId{"pageUp"}, Description: "Selection page up"}, "tui.select.pageDown": {DefaultKeys: []KeyId{"pageDown"}, Description: "Selection page down"}, "tui.select.confirm": {DefaultKeys: []KeyId{"enter"}, Description: "Confirm selection"}, "tui.select.cancel": {DefaultKeys: []KeyId{"escape", "ctrl+c"}, Description: "Cancel selection"}, "tui.altScreen.pageUp": {DefaultKeys: []KeyId{"pageUp"}, Description: "Scroll viewport up one page"}, "tui.altScreen.pageDown": {DefaultKeys: []KeyId{"pageDown"}, Description: "Scroll viewport down one page"}, "tui.altScreen.halfPageUp": {DefaultKeys: []KeyId{}, Description: "Scroll viewport up half a page"}, "tui.altScreen.halfPageDown": {DefaultKeys: []KeyId{}, Description: "Scroll viewport down half a page"}, "tui.altScreen.lineUp": {DefaultKeys: []KeyId{}, Description: "Scroll viewport up one line"}, "tui.altScreen.lineDown": {DefaultKeys: []KeyId{}, Description: "Scroll viewport down one line"}, "tui.altScreen.previousPrompt": { DefaultKeys: []KeyId{"ctrl+shift+up", "ctrl+up"}, Description: "Jump to previous semantic prompt", }, "tui.altScreen.nextPrompt": { DefaultKeys: []KeyId{"ctrl+shift+down", "ctrl+down"}, Description: "Jump to next semantic prompt", }, "tui.altScreen.search": { DefaultKeys: []KeyId{"ctrl+shift+f"}, Description: "Search the primary scroll view", }, "tui.altScreen.searchNext": { DefaultKeys: []KeyId{"enter", "ctrl+g"}, Description: "Select the next search match", }, "tui.altScreen.searchPrevious": { DefaultKeys: []KeyId{"shift+enter", "ctrl+shift+g"}, Description: "Select the previous search match", }, "tui.altScreen.searchClose": {DefaultKeys: []KeyId{"escape"}, Description: "Close transcript search"}, "tui.altScreen.top": {DefaultKeys: []KeyId{"ctrl+home"}, Description: "Scroll viewport to top"}, "tui.altScreen.bottom": {DefaultKeys: []KeyId{"ctrl+end"}, Description: "Scroll viewport to bottom"}, }
TUIKeyBindings holds the default keybinding definitions (pi: TUI_KEYBINDINGS, declaration order preserved).
Functions ¶
func AllocateImageId ¶
func AllocateImageId() int
AllocateImageId generates a random image ID in range [1, 0xffffffff] to avoid collisions between different module instances.
func AllocateStackSizes ¶
func AllocateStackSizes(entries []StackLayoutEntry, intrinsicSizes []int, availableSize *int, gap int) []int
AllocateStackSizes computes per-entry sizes (pi: allocateStackSizes). availableSize is nil where pi passes undefined (VStack).
func ApplyBackgroundToLine ¶
ApplyBackgroundToLine applies background color to a line, padding to full width.
func BackgroundAnsi ¶ added in v1.0.0
func BackgroundAnsi(color Color, mode TerminalColorMode) string
BackgroundAnsi encodes a color as an SGR background sequence (pi: backgroundAnsi).
func ColorToHex ¶ added in v1.0.0
ColorToHex converts a color to a #rrggbb hex string (pi: colorToHex).
func CompositeTuiLine ¶
func CompositeTuiLine(baseLine string, overlayLine string, startCol int, overlayWidth int, totalWidth int) string
CompositeTuiLine composites overlay content into a terminal line at a fixed column.
func CropKittyImageLine ¶
CropKittyImageLine rewrites a Kitty image line to show only a window of rows (pi: cropKittyImageLine).
func DecodeKittyPrintable ¶
DecodeKittyPrintable decodes a Kitty CSI-u sequence into a printable character, if applicable.
When Kitty keyboard protocol flag 1 (disambiguate) is active, terminals send CSI-u sequences for all keys, including plain printable characters. This function extracts the printable character from such sequences.
Only accepts plain or Shift-modified keys. Rejects Ctrl, Alt, and unsupported modifier combinations (those are handled by keybinding matching instead). Prefers the shifted keycode when Shift is held and a shifted key is reported.
ok is false when data is not a printable CSI-u sequence (pi: undefined).
func DecodePrintableKey ¶
DecodePrintableKey decodes a printable key from Kitty CSI-u or xterm modifyOtherKeys sequences. ok is false when not decodable (pi: undefined).
func DeleteAllKittyImages ¶
func DeleteAllKittyImages() string
DeleteAllKittyImages deletes all visible Kitty graphics images (uppercase 'A' also frees the image data).
func DeleteAllKittyPlacements ¶
func DeleteAllKittyPlacements() string
DeleteAllKittyPlacements deletes all visible Kitty placements while retaining their uploaded image data.
func DeleteKittyImage ¶
DeleteKittyImage generates an escape deleting a Kitty graphics image by ID. Uses uppercase 'I' to also free the image data.
func EncodeKitty ¶
func EncodeKitty(base64Data string, options EncodeKittyParams) string
EncodeKitty encodes base64 image data as a Kitty graphics placement escape.
func FindWordBackward ¶
func FindWordBackward(text string, cursor int, options *WordNavigationOptions) int
FindWordBackward finds the cursor position after moving one word backward from cursor in text. Skips trailing whitespace, then stops at the next word/punctuation boundary.
Pure function - does not mutate any state.
func FindWordForward ¶
func FindWordForward(text string, cursor int, options *WordNavigationOptions) int
FindWordForward finds the cursor position after moving one word forward from cursor in text. Skips leading whitespace, then stops at the next word/punctuation boundary.
Pure function - does not mutate any state.
func ForegroundAnsi ¶ added in v1.0.0
func ForegroundAnsi(color Color, mode TerminalColorMode) string
ForegroundAnsi encodes a color as an SGR foreground sequence (pi: foregroundAnsi).
func FuzzyFilter ¶
FuzzyFilter filters and sorts items by fuzzy match quality, best matches first. Supports whitespace- and slash-separated tokens: all tokens must match (pi: fuzzyFilter).
func GetActiveBackgroundAnsi ¶
GetActiveBackgroundAnsi returns only the background color active at the end of an ANSI-styled string (pi: getActiveBackgroundAnsi).
func GetAltScreenSearchMatchKey ¶
func GetAltScreenSearchMatchKey(match AltScreenSearchMatch) string
GetAltScreenSearchMatchKey returns the stable identity key of a match (pi: getAltScreenSearchMatchKey).
func GetKittyImagePlacementRows ¶ added in v1.0.1
GetKittyImagePlacementRows reads the number of rows covered by an image placement without scanning its payload (pi: getKittyImagePlacementRows, #10319): the explicit `r=` control when present, else the registered metadata rows; 0 = the line places no known image.
func GetOsc8LinkAtColumn ¶
GetOsc8LinkAtColumn returns the OSC 8 hyperlink URL covering a visible terminal column, or "" when none (TS undefined).
func Hyperlink ¶
Hyperlink wraps text in an OSC 8 hyperlink sequence (pi: terminal-image.ts hyperlink — ported early because the Markdown component consumes it).
func ImageFallback ¶
func ImageFallback(mimeType string, dimensions *ImageDimensions, filename string) string
ImageFallback is the text fallback when the terminal cannot render inline images (pi: imageFallback). dimensions nil = unknown; filename "" = omitted.
func IsAppleTerminalSession ¶
func IsAppleTerminalSession() bool
IsAppleTerminalSession reports whether we run in Apple Terminal on macOS.
func IsImageLine ¶
IsImageLine reports whether the line contains a Kitty or iTerm2 image placement sequence.
func IsKeyRelease ¶
IsKeyRelease reports whether the data looks like a Kitty key release event. Only meaningful when Kitty keyboard protocol with flag 2 is active.
func IsKeyRepeat ¶
IsKeyRepeat reports whether the data looks like a Kitty key repeat event. Only meaningful when Kitty keyboard protocol with flag 2 is active.
func IsKittyProtocolActive ¶
func IsKittyProtocolActive() bool
IsKittyProtocolActive queries whether Kitty keyboard protocol is active.
func IsNativeModifierPressed ¶
func IsNativeModifierPressed(key ModifierKey) bool
IsNativeModifierPressed reports whether a native modifier key is physically held (pi: isNativeModifierPressed → helper.isModifierPressed). Always false in pig (see native_platform.go header).
func IsPunctuationChar ¶
IsPunctuationChar reports whether the character is ASCII punctuation (word-boundary classification).
func IsValidKeyId ¶ added in v1.2.0
IsValidKeyId reports whether keyId matches the key identifier grammar pi validates keybinding configs against (pi: KeyIdSchema): up to four distinct ctrl/shift/alt/super modifiers followed by a base key (a lowercase letter, a digit, or a named/symbolic key). Duplicate modifiers are rejected.
func IsWhitespaceChar ¶
IsWhitespaceChar reports whether the character is ECMAScript whitespace.
func KeyAltCtrl ¶
func KeyAltShift ¶
func KeyAltSuper ¶
func KeyCtrlAlt ¶
func KeyCtrlShift ¶
func KeyCtrlShiftAlt ¶
func KeyCtrlShiftSuper ¶
func KeyCtrlSuper ¶
func KeyShiftAlt ¶
func KeyShiftCtrl ¶
func KeyShiftSuper ¶
func KeySuperAlt ¶
func KeySuperCtrl ¶
func KeySuperShift ¶
func MatchesKey ¶
MatchesKey matches input data against a key identifier string.
Supported key identifiers:
- Single keys: "escape", "tab", "enter", "backspace", "delete", "home", "end", "space"
- Arrow keys: "up", "down", "left", "right"
- Ctrl combinations: "ctrl+c", "ctrl+z", etc.
- Shift combinations: "shift+tab", "shift+enter"
- Alt combinations: "alt+enter", "alt+backspace"
- Super combinations: "super+k", "super+enter"
- Combined modifiers: "shift+ctrl+p", "ctrl+alt+x", "ctrl+super+k"
Use the Key* constants/helpers for readability: KeyCtrl("c"), KeyEscape, KeyCtrlShift("p"), KeySuper("k").
func NormalizeAppleTerminalInput ¶
NormalizeAppleTerminalInput is NormalizeNativeShiftEnterInput for Apple Terminal sessions.
func NormalizeNativeShiftEnterInput ¶
func NormalizeNativeShiftEnterInput(data string, shouldDetectNativeShiftEnter bool, isShiftPressed bool) string
NormalizeNativeShiftEnterInput rewrites a bare Return to the CSI-u Shift+Enter sequence when native Shift detection is enabled and Shift is physically held.
func NormalizeTerminalOutput ¶
NormalizeTerminalOutput normalizes text for terminal output without changing logical editor content.
Some terminals render precomposed Thai/Lao AM vowels inconsistently during differential repaint. Their compatibility decompositions have the same cell width but avoid stale-cell artifacts in terminal renderers. Visible tabs are expanded to the fixed width used by layout so terminal tab stops cannot wrap a logical line, while tabs inside terminal string sequences stay untouched.
func NowMillis ¶ added in v1.0.0
func NowMillis() float64
NowMillis returns the current wall clock in milliseconds (pi's callers use performance.now(); the seam keeps the unit explicit for tests).
func OklabToLinearSrgb ¶ added in v1.0.0
func OklabToLinearSrgb(lab vector3) vector3
OklabToLinearSrgb converts Oklab [L, a, b] to linear sRGB [r, g, b] (0-1, may leave the gamut).
func OklabToOkhslLightness ¶ added in v1.0.0
OklabToOkhslLightness converts Oklab lightness to OKHSL lightness.
func ParseKey ¶
ParseKey parses input data and returns the key identifier if recognized. ok is false when the data does not correspond to a recognized key (pi: returns undefined).
func ParseOscColorResponse ¶ added in v1.0.0
func ParseOscColorResponse(data string) (OscColorTarget, *RgbColor, bool)
ParseOscColorResponse parses an OSC 10, 11, or 4 color reply. ok=false when data is not such a reply; rgb=nil when it is a reply with an unparseable color (pi: parseOscColorResponse).
func RegisterKittyImageMetadata ¶
func RegisterKittyImageMetadata(metadata KittyImageMetadata)
RegisterKittyImageMetadata records the metadata of a transmitted image (pi: registerKittyImageMetadata). Bumps the transmission generation and keeps at most 1000 entries (oldest inserted evicted first).
func RenderFakeCursor ¶ added in v1.2.0
RenderFakeCursor wraps text in fake cursor markers. (pi: renderFakeCursor)
func RenderLatex ¶
RenderLatex renders a basic LaTeX math expression as terminal-friendly Unicode text (pi: renderLatex). ok is false when the expression contains unsupported or malformed syntax (pi: undefined). pi's RenderLatexOptions has a single display option — collapsed into the display parameter (the markdown seam's signature).
func ResetCapabilitiesCache ¶
func ResetCapabilitiesCache()
ResetCapabilitiesCache drops the cached capabilities.
func ResolveEscapeTimeoutMs ¶
func ResolveEscapeTimeoutMs() int
ResolveEscapeTimeoutMs resolves how long to wait for the rest of an escape sequence before dispatching a lone ESC as the Escape key. Legacy Alt+key input is ESC plus another byte, so high-latency transports need a longer reassembly window.
func RestoreActiveOnExit ¶ added in v1.4.0
func RestoreActiveOnExit()
RestoreActiveOnExit restores every running TUI's terminal modes. Call it from the process exit path where pi's `exit` event would fire; hard kills and native aborts cannot run Go code either.
func RgbToOklab ¶ added in v1.0.0
func RgbToOklab(c RgbColor) vector3
RgbToOklab converts sRGB channels (0-255) to Oklab [L, a, b].
func SetCJKSegmenterMode ¶
func SetCJKSegmenterMode(value string)
SetCJKSegmenterMode records the settings-driven backend selection (pig extension; pi has no counterpart — Intl.Segmenter ships inside the JS runtime). Unrecognized values resolve to the bigram default (the configuration can only degrade word navigation, never break it). If the segmenter already resolved (a Han word operation ran this session), the change takes effect on the next pig start; before that, the very next word operation picks it up.
func SetCapabilities ¶
func SetCapabilities(caps TerminalCapabilities)
SetCapabilities overrides the cached capabilities (test seam, pi: same).
func SetCapabilityOverrides ¶
func SetCapabilityOverrides(overrides TerminalCapabilityOverrides)
SetCapabilityOverrides overrides selected auto-detected capabilities (pi: setCapabilityOverrides). Takes effect on the next capability cache fill.
func SetCellDimensions ¶
func SetCellDimensions(dims CellDimensions)
SetCellDimensions records the terminal cell size in pixels.
func SetKeybindings ¶
func SetKeybindings(keybindings *KeybindingsManager)
SetKeybindings replaces the global keybindings manager.
func SetKittyProtocolActive ¶
func SetKittyProtocolActive(active bool)
SetKittyProtocolActive sets the global Kitty keyboard protocol state. Called by ProcessTerminal after detecting protocol support.
func SliceByColumn ¶
SliceByColumn extracts a range of visible columns from a line. Handles ANSI codes and wide chars. strict: if true, exclude wide chars at boundary that would extend past the range.
func StripTerminalSequences ¶
StripTerminalSequences removes ANSI, OSC, and APC control sequences while preserving visible text.
func StyleText ¶ added in v1.0.0
func StyleText(text string, options TextStyle, mode TerminalColorMode) string
StyleText styles text with colors and attributes (pi: styleText).
func StyleTextWithAnsi ¶ added in v1.0.0
func StyleTextWithAnsi(text string, fgAnsi string, bgAnsi string, options TextAttributes) string
StyleTextWithAnsi is like StyleText, but with precomputed color escape sequences, e.g. cached theme colors. Colors in options are ignored (pi: styleTextWithAnsi).
func TruncateToWidth ¶
TruncateToWidth truncates text to fit within a maximum visible width, adding ellipsis if needed. Optionally pad with spaces to reach exactly maxWidth. Properly handles ANSI escape codes (they don't count toward width).
ellipsis: appended when truncating (pi default "..."); pad: pad result with spaces to exactly maxWidth (pi default false).
func VisibleWidth ¶
VisibleWidth calculates the visible width of a string in terminal columns.
func WrapTextWithAnsi ¶
WrapTextWithAnsi wraps text with ANSI codes preserved.
ONLY does word wrapping - NO padding, NO background colors. Returns lines where each line is <= width visible chars. Active ANSI codes are preserved across line breaks.
Types ¶
type AltScreenFlashContainer ¶
type AltScreenFlashContainer struct {
// contains filtered or unexported fields
}
AltScreenFlashContainer is the flash message stack (pi: AltScreenFlashContainer implements Component).
func NewAltScreenFlashContainer ¶
func NewAltScreenFlashContainer(requestRender func()) *AltScreenFlashContainer
NewAltScreenFlashContainer creates the container; requestRender is invoked whenever the visible set changes.
func (*AltScreenFlashContainer) Dispose ¶
func (f *AltScreenFlashContainer) Dispose()
Dispose clears all entries and cancels their timers (pi: dispose).
func (*AltScreenFlashContainer) Flash ¶
func (f *AltScreenFlashContainer) Flash(message string, durationMs int)
Flash shows a transient message (pi: flash).
func (*AltScreenFlashContainer) Invalidate ¶
func (f *AltScreenFlashContainer) Invalidate()
Invalidate implements Component (no cached state).
func (*AltScreenFlashContainer) Render ¶
func (f *AltScreenFlashContainer) Render(width int) []string
Render implements Component.
type AltScreenSearchComponent ¶
type AltScreenSearchComponent struct {
// contains filtered or unexported fields
}
AltScreenSearchComponent is the bordered search overlay input with navigation buttons (pi: AltScreenSearchComponent implements Component, Focusable).
func NewAltScreenSearchComponent ¶
func NewAltScreenSearchComponent(onQueryChange func(query string), navigationButtonStyle func(text string, hovered bool) string) *AltScreenSearchComponent
NewAltScreenSearchComponent creates the search component (pi constructor; navigationButtonStyle may be nil for identity styling).
func (*AltScreenSearchComponent) GetFocused ¶
func (c *AltScreenSearchComponent) GetFocused() bool
GetFocused implements Focusable.
func (*AltScreenSearchComponent) GetNavigationDirectionAt ¶
func (c *AltScreenSearchComponent) GetNavigationDirectionAt(row int, column int) int
GetNavigationDirectionAt reports which navigation button covers the given component-local cell (pi: getNavigationDirectionAt). Row 2 is the bottom border row where the buttons render. Returns -1 (previous), 1 (next), or 0 (none).
func (*AltScreenSearchComponent) HandleInput ¶
func (c *AltScreenSearchComponent) HandleInput(data string)
HandleInput implements InputHandler.
func (*AltScreenSearchComponent) Invalidate ¶
func (c *AltScreenSearchComponent) Invalidate()
Invalidate implements Component.
func (*AltScreenSearchComponent) Render ¶
func (c *AltScreenSearchComponent) Render(width int) []string
Render implements Component (pi: render — bordered box with the input on row 1 and the navigation buttons embedded in the bottom border).
func (*AltScreenSearchComponent) SetFocused ¶
func (c *AltScreenSearchComponent) SetFocused(value bool)
SetFocused implements Focusable.
func (*AltScreenSearchComponent) SetHoveredNavigationDirection ¶
func (c *AltScreenSearchComponent) SetHoveredNavigationDirection(direction int) bool
SetHoveredNavigationDirection updates the hovered button and reports whether the hover state changed (pi: setHoveredNavigationDirection). direction: -1 | 1 | 0 (none).
func (*AltScreenSearchComponent) SetResult ¶
func (c *AltScreenSearchComponent) SetResult(index int, count int)
SetResult records the match status shown in the search box (pi: setResult).
type AltScreenSearchIndex ¶
type AltScreenSearchIndex struct {
// contains filtered or unexported fields
}
AltScreenSearchIndex caches the searchable corpus and matches while rendered transcript lines remain unchanged (pi: AltScreenSearchIndex).
func NewAltScreenSearchIndex ¶
func NewAltScreenSearchIndex() *AltScreenSearchIndex
NewAltScreenSearchIndex creates the search index.
func (*AltScreenSearchIndex) Search ¶
func (idx *AltScreenSearchIndex) Search(lines []string, query string) AltScreenSearchResult
Search runs the query against lines, reusing the cached corpus when the source lines are unchanged (pi: AltScreenSearchIndex.search).
type AltScreenSearchMatch ¶
type AltScreenSearchMatch struct {
Segments []AltScreenSearchSegment
}
AltScreenSearchMatch is a query match spanning one or more segments (pi: AltScreenSearchMatch).
func FindAltScreenSearchMatches ¶
func FindAltScreenSearchMatches(lines []string, query string) []AltScreenSearchMatch
FindAltScreenSearchMatches finds all matches of query in the normalized rendered transcript text without caching (pi: findAltScreenSearchMatches).
type AltScreenSearchResult ¶
type AltScreenSearchResult struct {
Matches []AltScreenSearchMatch
Changed bool
}
AltScreenSearchResult carries the matches plus whether they changed since the previous search call (pi: AltScreenSearchResult).
type AltScreenSearchSegment ¶
AltScreenSearchSegment is one highlighted run within a source row (pi: AltScreenSearchSegment).
type AnsiCode ¶
AnsiCode is an escape sequence found at a position (Length is in bytes).
func ExtractAnsiCode ¶
ExtractAnsiCode extracts an ANSI escape sequence from a string at the given byte position, or nil when there is none.
type AutocompleteApplyResult ¶
AutocompleteApplyResult is the result of applyCompletion (pi: inline { lines, cursorLine, cursorCol }).
type AutocompleteGetSuggestionsOptions ¶
type AutocompleteGetSuggestionsOptions struct {
Force bool
}
AutocompleteGetSuggestionsOptions carries getSuggestions options; the abort signal moved to the ctx parameter (repo AbortSignal → context rule).
type AutocompleteItem ¶
type AutocompleteItem struct {
Value string
Label string
// Description is optional (pi: description?); "" means absent. TS falsy
// checks treat "" the same as undefined.
Description string
}
AutocompleteItem is one suggestion entry (pi: AutocompleteItem).
type AutocompleteProvider ¶
type AutocompleteProvider interface {
// GetSuggestions returns suggestions for the current text/cursor
// position, or nil if none are available. lines/cursor* arrive as a
// stable snapshot (pi reads live state on the event loop; see editor.go
// file header for the goroutine adaptation).
GetSuggestions(ctx context.Context, lines []string, cursorLine int, cursorCol int, options AutocompleteGetSuggestionsOptions) *AutocompleteSuggestions
// ApplyCompletion applies the selected item, returning the new text and
// cursor position.
ApplyCompletion(lines []string, cursorLine int, cursorCol int, item AutocompleteItem, prefix string) AutocompleteApplyResult
}
AutocompleteProvider provides autocomplete suggestions for the editor (pi: AutocompleteProvider).
type AutocompleteSuggestions ¶
type AutocompleteSuggestions struct {
Items []AutocompleteItem
// Prefix is what we're matching against (e.g. "/" or "src/").
Prefix string
}
AutocompleteSuggestions is a suggestion result (pi: AutocompleteSuggestions).
type Box ¶
type Box struct {
Children []Component
// contains filtered or unexported fields
}
Box is the padding/background container (pi: class Box implements Component).
func (*Box) HandleMouse ¶
func (b *Box) HandleMouse(event *TuiMouseEvent) *TuiMouseEventResult
HandleMouse implements MouseHandler: translate pointer coordinates into the padded content area and hit-test children by their rendered heights (pi: Box.handleMouse).
func (*Box) Invalidate ¶
func (b *Box) Invalidate()
func (*Box) RemoveChild ¶
type CancellableLoader ¶
type CancellableLoader struct {
// Embedded by pointer: Loader contains mutexes (pig concurrency
// adaptation), and value embedding would copy locks (pi: extends Loader).
*Loader
/** Called when user presses Escape (pi: onAbort?: () => void). */
OnAbort func()
// contains filtered or unexported fields
}
CancellableLoader is the escape-cancellable loader (pi: class CancellableLoader extends Loader).
func NewCancellableLoader ¶
func NewCancellableLoader(tui TUI, spinnerColorFn func(string) string, messageColorFn func(string) string, message string, indicator *LoaderIndicatorOptions) *CancellableLoader
NewCancellableLoader mirrors pi's constructor.
func (*CancellableLoader) Aborted ¶
func (c *CancellableLoader) Aborted() bool
Aborted reports whether the loader was aborted (pi: get aborted).
func (*CancellableLoader) Dispose ¶
func (c *CancellableLoader) Dispose()
Dispose stops the animation (pi: dispose).
func (*CancellableLoader) HandleInput ¶
func (c *CancellableLoader) HandleInput(data string)
HandleInput implements InputHandler (pi: handleInput).
func (*CancellableLoader) Signal ¶
func (c *CancellableLoader) Signal() context.Context
Signal returns the cancellation context, aborted when user presses Escape (pi: get signal — AbortSignal → context.Context).
type CellDimensions ¶
CellDimensions is the terminal cell size in pixels.
func GetCellDimensions ¶
func GetCellDimensions() *CellDimensions
GetCellDimensions returns the last reported cell size (nil = unknown).
type Color ¶ added in v1.0.0
type Color struct {
Kind ColorKind
Index int // indexed
R int // rgb
G int
B int
L float64 // oklch
C float64
H float64
}
Color is a concrete color: an ANSI palette index, sRGB channels, or OKLCH components (pi: Color = IndexedColor | RgbColorValue | OklchColorValue). Every color can be converted to sRGB, so color math never fails. The kind decides which fields are meaningful.
func MixColors ¶ added in v1.0.0
func MixColors(first, second Color, amount float64, space ColorMixSpace) (Color, error)
MixColors interpolates two colors in oklch (default) or srgb space (pi: mixColors). amount 0 = first, 1 = second.
func NewIndexedColor ¶ added in v1.0.0
NewIndexedColor builds an indexed (ANSI 256) color (pi: indexedColor).
func NewOkhslColor ¶ added in v1.0.0
NewOkhslColor builds an OKHSL color, converted to sRGB. Saturation is relative to the sRGB gamut at the hue and lightness, so equal saturation looks equally colorful across hues and lightness (pi: okhslColor).
- h: hue in degrees. s: saturation 0-1. l: lightness 0-1.
func NewOklchColor ¶ added in v1.0.0
NewOklchColor builds an OKLCH color (pi: oklchColor).
func NewRgbColor ¶ added in v1.0.0
NewRgbColor builds an sRGB color (pi: rgbColor).
func ParseColor ¶ added in v1.0.0
ParseColor parses a theme color value: a 256-color index (number), a #rgb/#rrggbb hex string, or an oklch()/okhsl() string (pi: parseColor).
type ColorKind ¶ added in v1.0.0
type ColorKind int
ColorKind discriminates the Color union (pi: kind: "indexed" | "rgb" | "oklch").
type ColorMixSpace ¶ added in v1.0.0
type ColorMixSpace = string
ColorMixSpace is the color space mixColors interpolates in (pi: ColorMixSpace = "oklch" | "srgb").
const ( MixSpaceOklch ColorMixSpace = "oklch" MixSpaceSrgb ColorMixSpace = "srgb" )
type CombinedAutocompleteProvider ¶
type CombinedAutocompleteProvider struct {
// contains filtered or unexported fields
}
CombinedAutocompleteProvider handles both slash commands and file paths (pi: CombinedAutocompleteProvider).
func NewCombinedAutocompleteProvider ¶
func NewCombinedAutocompleteProvider(commands []SlashCommandOrItem, basePath string, fdPath string) *CombinedAutocompleteProvider
NewCombinedAutocompleteProvider creates the combined provider (pi: constructor; commands defaults to an empty slice, fdPath "" = null).
func (*CombinedAutocompleteProvider) ApplyCompletion ¶
func (p *CombinedAutocompleteProvider) ApplyCompletion(lines []string, cursorLine int, cursorCol int, item AutocompleteItem, prefix string) AutocompleteApplyResult
ApplyCompletion implements AutocompleteProvider (pi: applyCompletion).
func (*CombinedAutocompleteProvider) GetSuggestions ¶
func (p *CombinedAutocompleteProvider) GetSuggestions(ctx context.Context, lines []string, cursorLine int, cursorCol int, options AutocompleteGetSuggestionsOptions) *AutocompleteSuggestions
GetSuggestions implements AutocompleteProvider (pi: getSuggestions).
func (*CombinedAutocompleteProvider) SetTriggerCharacters ¶
func (p *CombinedAutocompleteProvider) SetTriggerCharacters(chars []string)
SetTriggerCharacters installs the merged trigger characters (pig: pi assigns the property directly; capability setter per repo rule).
func (*CombinedAutocompleteProvider) ShouldTriggerFileCompletion ¶
func (p *CombinedAutocompleteProvider) ShouldTriggerFileCompletion(lines []string, cursorLine int, cursorCol int) bool
ShouldTriggerFileCompletion implements FileCompletionTriggerer (pi: shouldTriggerFileCompletion — called on Tab key).
func (*CombinedAutocompleteProvider) TriggerCharacters ¶
func (p *CombinedAutocompleteProvider) TriggerCharacters() []string
TriggerCharacters implements TriggerCharactersProvider.
type Component ¶
type Component interface {
// Render the component to lines for the given viewport width.
Render(width int) []string
// Invalidate any cached rendering state. Called when theme changes or
// when the component needs to re-render from scratch.
Invalidate()
}
Component is the interface all TUI components must implement.
type Container ¶
type Container struct {
Children []Component
// contains filtered or unexported fields
}
Container is a component that contains other components.
func (*Container) HandleMouse ¶
func (c *Container) HandleMouse(event *TuiMouseEvent) *TuiMouseEventResult
HandleMouse implements MouseHandler: hit-test children by their rendered heights and forward the event with child-local coordinates (pi: Container.handleMouse).
Deviation note: pi's focus override check reads `this.handleInput` on the outermost instance; in Go, promoted Container.HandleMouse only sees the *Container method set. No current component embeds Container while defining HandleInput; if one appears it should override HandleMouse.
func (*Container) Invalidate ¶
func (c *Container) Invalidate()
func (*Container) RemoveChild ¶
type CopySelectionResult ¶ added in v0.86.0
CopySelectionResult mirrors pi v0.86.0's boolean | string union return of the copySelection callback: Ok=true → success; Ok=false with a non-empty FailureMessage → that message is flashed; Ok=false otherwise → generic "Copy failed".
type CursorPosition ¶
CursorPosition is a hardware cursor position extracted from rendered lines.
type DefaultTextStyle ¶
type DefaultTextStyle struct {
// Foreground color function
Color func(text string) string
// Background color function
BgColor func(text string) string
// Bold text
Bold bool
// Italic text
Italic bool
// Strikethrough text
Strikethrough bool
// Underline text
Underline bool
}
DefaultTextStyle is the base styling applied to all text unless overridden by markdown formatting (pi: DefaultTextStyle).
type Editor ¶
type Editor struct {
// Focused is the Focusable flag - set by TUI when focus changes.
Focused bool
// BorderColor can be changed dynamically (pi: public borderColor).
BorderColor func(text string) string
// TopBorderOverride optionally replaces the default top border (pig
// addition: pi overrides protected renderTopBorder in CustomEditor; Go
// embedding has no virtual dispatch, so the override is injected as a
// callback. Return ok=false to fall through to the default border —
// that is the equivalent of calling super.renderTopBorder).
TopBorderOverride func(width int, hiddenLineCount int) (string, bool)
// ImagePlaceholderValidIds reports the registered [Image N] ids (pig-only;
// pi has no equivalent — docs/feat/CLIPBOARD-IMAGE-PLACEHOLDER.md).
// Placeholders with a valid id merge into a single atomic segment (same
// mechanics as paste markers); nil or missing ids leave the text fully
// editable. Backed by interactive mode's clipboard placeholder registry.
ImagePlaceholderValidIds func() map[int]bool
// OnSubmit is called when user submits (e.g. Enter).
OnSubmit func(text string)
// OnChange is called when text changes.
OnChange func(text string)
// DisableSubmit suppresses submission.
DisableSubmit bool
// contains filtered or unexported fields
}
Editor is a multi-line text editor component (pi: Editor class). It implements Component, InputHandler and Focusable.
func NewEditor ¶
func NewEditor(tui TUI, theme EditorTheme, options *EditorOptions) *Editor
NewEditor creates an editor bound to tui (pi: constructor; options is optional — pass nil for defaults).
func (*Editor) AddToHistory ¶
AddToHistory adds a prompt to history for up/down arrow navigation. Called after successful submission.
func (*Editor) GetAutocompleteMaxVisible ¶
GetAutocompleteMaxVisible returns the dropdown size (pi: getAutocompleteMaxVisible).
func (*Editor) GetAutocompleteProvider ¶
func (e *Editor) GetAutocompleteProvider() AutocompleteProvider
GetAutocompleteProvider returns the installed provider, or nil (pig addition for the interactive-mode tests; pi reads the private field from the same package).
func (*Editor) GetCursor ¶
func (e *Editor) GetCursor() EditorCursor
GetCursor returns the cursor position.
func (*Editor) GetExpandedText ¶
GetExpandedText gets text with paste markers expanded to their actual content. Use this when you need the full content (e.g., for external editor).
func (*Editor) GetFocused ¶
GetFocused reports the current focus state (pi: Focusable.focused property).
func (*Editor) GetPaddingX ¶
GetPaddingX returns the horizontal padding.
func (*Editor) HandleInput ¶
HandleInput implements InputHandler.
func (*Editor) HandleMouse ¶
func (e *Editor) HandleMouse(event *TuiMouseEvent) *TuiMouseEventResult
HandleMouse implements MouseHandler.
func (*Editor) InsertTextAtCursor ¶
InsertTextAtCursor inserts text at the current cursor position. Used for programmatic insertion (e.g., clipboard image markers). This is atomic for undo - single undo restores entire pre-insert state.
func (*Editor) Invalidate ¶
func (e *Editor) Invalidate()
Invalidate implements Component (no cached state to invalidate currently).
func (*Editor) IsShowingAutocomplete ¶
IsShowingAutocomplete reports whether the dropdown is open (pi: isShowingAutocomplete).
func (*Editor) SetAutocompleteMaxVisible ¶
SetAutocompleteMaxVisible sets the dropdown size (pi: setAutocompleteMaxVisible).
func (*Editor) SetAutocompleteProvider ¶
func (e *Editor) SetAutocompleteProvider(provider AutocompleteProvider)
SetAutocompleteProvider installs the autocomplete provider (pi: setAutocompleteProvider).
func (*Editor) SetFocused ¶
SetFocused is called by the TUI when focus changes.
func (*Editor) SetPaddingX ¶
SetPaddingX sets the horizontal padding.
type EditorComponent ¶
type EditorComponent interface {
Component
// GetText returns the current text content (pi: getText).
GetText() string
// SetText sets the text content (pi: setText).
SetText(text string)
// HandleInput handles raw terminal input (key presses, paste sequences,
// etc.) (pi: handleInput).
HandleInput(data string)
}
EditorComponent is the required core of a custom editor component (pi: EditorComponent extends Component).
type EditorComponentAppearance ¶
type EditorComponentAppearance interface {
// SetPaddingX sets horizontal padding.
SetPaddingX(padding int)
// SetAutocompleteMaxVisible sets the max visible items in the
// autocomplete dropdown.
SetAutocompleteMaxVisible(maxVisible int)
}
EditorComponentAppearance is the optional appearance capability (pi: optional setPaddingX? / setAutocompleteMaxVisible?).
type EditorComponentAutocomplete ¶
type EditorComponentAutocomplete interface {
// SetAutocompleteProvider sets the autocomplete provider.
SetAutocompleteProvider(provider AutocompleteProvider)
}
EditorComponentAutocomplete is the optional autocomplete capability (pi: optional setAutocompleteProvider?).
type EditorComponentExpandedText ¶
type EditorComponentExpandedText interface {
// GetExpandedText returns text with any markers expanded (e.g. paste
// markers).
GetExpandedText() string
}
EditorComponentExpandedText is the optional expanded-text capability (pi: optional getExpandedText? — falls back to getText() if not implemented).
type EditorComponentHistory ¶
type EditorComponentHistory interface {
// AddToHistory adds text to history for up/down navigation.
AddToHistory(text string)
}
EditorComponentHistory is the optional history capability (pi: optional addToHistory?).
type EditorComponentTextInsertion ¶
type EditorComponentTextInsertion interface {
// InsertTextAtCursor inserts text at the current cursor position.
InsertTextAtCursor(text string)
}
EditorComponentTextInsertion is the optional advanced text manipulation capability (pi: optional insertTextAtCursor?).
type EditorCursor ¶
EditorCursor is the return shape of GetCursor (pi: { line, col }).
type EditorOptions ¶
type EditorOptions struct {
PaddingX int
// AutocompleteMaxVisible clamps the autocomplete dropdown size (pi:
// autocompleteMaxVisible?, default 5; explicit 0 clamps to 3, so the
// pointer distinguishes unset from zero).
AutocompleteMaxVisible *int
}
EditorOptions configures the editor.
type EditorTheme ¶
type EditorTheme struct {
BorderColor func(text string) string
// SelectList colors the autocomplete dropdown (pi: selectList).
SelectList SelectListTheme
}
EditorTheme holds editor appearance hooks.
type EncodeKittyParams ¶
type EncodeKittyParams struct {
Columns int
Rows int
ImageId int
// MoveCursorOff mirrors pi's moveCursor: false (Kitty applies its default
// cursor movement after placement unless C=1 is sent).
MoveCursorOff bool
}
EncodeKittyParams are the optional parameters for EncodeKitty.
type ExitRestorer ¶ added in v1.4.0
ExitRestorer is implemented by terminals that can restore their modes from a process exit handler after Stop did not run (pi: Terminal.restoreOnExit?).
type FileCompletionTriggerer ¶
type FileCompletionTriggerer interface {
// ShouldTriggerFileCompletion reports whether file completion should
// trigger (called on Tab key).
ShouldTriggerFileCompletion(lines []string, cursorLine int, cursorCol int) bool
}
FileCompletionTriggerer is the optional capability for providers that control explicit Tab file-completion triggering (pi: optional shouldTriggerFileCompletion member → capability interface, repo rule).
type Focusable ¶
type Focusable interface {
Component
// GetFocused reports the current focus state (set by TUI on focus change).
GetFocused() bool
// SetFocused is called by the TUI when focus changes.
SetFocused(focused bool)
}
Focusable is implemented by components that can receive focus and display a hardware cursor. When focused, the component should emit CURSOR_MARKER at the cursor position in its render output. TUI finds this marker and positions the hardware cursor there for proper IME candidate window positioning (pi: Focusable interface + focused property).
func AsFocusable ¶
AsFocusable returns the component as Focusable, or nil (pi: isFocusable).
type FuzzyMatch ¶
FuzzyMatch is one fuzzy-match outcome (pi: FuzzyMatch).
func FuzzyMatchScore ¶
func FuzzyMatchScore(query, text string) FuzzyMatch
FuzzyMatchScore computes the match of query against text (pi: fuzzyMatch's matchQuery helper folded into the exported function shape — pi's fuzzyMatch returns matchQuery's result or the swapped-retry result).
type GraphemeCellRange ¶
GraphemeCellRange is the terminal-cell range occupied by a grapheme (Start/End are visible columns, not byte offsets).
func GetGraphemeCellRange ¶
func GetGraphemeCellRange(line string, column int) *GraphemeCellRange
GetGraphemeCellRange returns the terminal-cell range occupied by the grapheme at a visible column, or nil when no grapheme covers it.
type GraphemeSegmenter ¶
GraphemeSegmenter mirrors the Intl.Segmenter (granularity: "grapheme") face pi-tui consumes: Segments splits s into extended grapheme clusters.
func GetGraphemeSegmenter ¶
func GetGraphemeSegmenter() GraphemeSegmenter
GetGraphemeSegmenter returns the shared grapheme segmenter instance.
type HStack ¶
type HStack struct {
Stack
}
HStack lays out children horizontally (pi: class HStack extends Stack).
func NewHStack ¶
func NewHStack(children []StackChild, options *StackOptions) *HStack
NewHStack mirrors pi's constructor; options may be nil.
type ImageDimensions ¶
ImageDimensions describes an image's pixel size (pi: ImageDimensions).
func GetGifDimensions ¶
func GetGifDimensions(base64Data string) *ImageDimensions
GetGifDimensions reads the LE size from the GIF header (pi: getGifDimensions).
func GetImageDimensions ¶
func GetImageDimensions(base64Data string, mimeType string) *ImageDimensions
GetImageDimensions dispatches on the mime type (pi: getImageDimensions).
func GetJpegDimensions ¶
func GetJpegDimensions(base64Data string) *ImageDimensions
GetJpegDimensions scans SOF0-SOF2 markers for the size (pi: getJpegDimensions).
func GetPngDimensions ¶
func GetPngDimensions(base64Data string) *ImageDimensions
GetPngDimensions parses the IHDR size from a base64 PNG (pi: getPngDimensions).
func GetWebpDimensions ¶
func GetWebpDimensions(base64Data string) *ImageDimensions
GetWebpDimensions reads VP8/VP8L/VP8X chunk sizes (pi: getWebpDimensions).
type Input ¶
type Input struct {
// OnSubmit is called when the user submits (pi: public onSubmit?).
OnSubmit func(value string)
// OnEscape is called on escape (pi: public onEscape?).
OnEscape func()
// Focused is the Focusable flag - set by TUI when focus changes (pi:
// focused public property).
Focused bool
// contains filtered or unexported fields
}
Input is a single-line text input with horizontal scrolling (pi: Input). It implements Component, InputHandler and Focusable.
func NewInput ¶
func NewInput(options ...*InputOptions) *Input
NewInput creates an input component (pi: constructor with an optional InputOptions parameter → variadic to keep existing NewInput() callers working).
func (*Input) GetFocused ¶
GetFocused reports the current focus state (pi: Focusable.focused).
func (*Input) HandleInput ¶
HandleInput implements InputHandler (pi: handleInput).
func (*Input) HandleMouse ¶
func (i *Input) HandleMouse(event *TuiMouseEvent) *TuiMouseEventResult
HandleMouse implements MouseHandler (pi: Input.handleMouse). A left press on the input row positions the cursor under the pointer.
func (*Input) Invalidate ¶
func (i *Input) Invalidate()
Invalidate clears cached render state (pi: invalidate — no cached state).
func (*Input) SetFocused ¶
SetFocused is called by the TUI when focus changes (pi: Focusable.focused).
type InputHandler ¶
type InputHandler interface {
HandleInput(data string)
}
InputHandler is the optional capability for components that receive keyboard input when they have focus (pi: handleInput?).
type InputOptions ¶
type InputOptions struct {
// Prompt rendered before the value (pi: prompt?; TS `?? ""` keeps an
// explicit empty prompt, so pig uses *string). Default "> ".
Prompt *string
// Placeholder rendered when the value is empty (pi: placeholder?).
Placeholder string
// PlaceholderStyle styles the placeholder text (pi: placeholderStyle?).
PlaceholderStyle func(text string) string
}
InputOptions configures an Input (pi: InputOptions).
type KeyEventType ¶
type KeyEventType = string
KeyEventType are event types from Kitty keyboard protocol (flag 2): 1 = key press, 2 = key repeat, 3 = key release.
const ( KeyEventPress KeyEventType = "press" KeyEventRepeat KeyEventType = "repeat" KeyEventRelease KeyEventType = "release" )
type KeyId ¶
type KeyId = string
KeyId is a key identifier string such as "escape", "ctrl+c", "shift+enter". (pi: union type KeyId — open string alias in Go.)
const ( KeyEscape KeyId = "escape" KeyEsc KeyId = "esc" KeyEnter KeyId = "enter" KeyReturn KeyId = "return" KeyTab KeyId = "tab" KeySpace KeyId = "space" KeyBackspace KeyId = "backspace" KeyDelete KeyId = "delete" KeyInsert KeyId = "insert" KeyClear KeyId = "clear" KeyHome KeyId = "home" KeyEnd KeyId = "end" KeyPageUp KeyId = "pageUp" KeyPageDown KeyId = "pageDown" KeyUp KeyId = "up" KeyDown KeyId = "down" KeyLeft KeyId = "left" KeyRight KeyId = "right" KeyF1 KeyId = "f1" KeyF2 KeyId = "f2" KeyF3 KeyId = "f3" KeyF4 KeyId = "f4" KeyF5 KeyId = "f5" KeyF6 KeyId = "f6" KeyF7 KeyId = "f7" KeyF8 KeyId = "f8" KeyF9 KeyId = "f9" KeyF10 KeyId = "f10" KeyF11 KeyId = "f11" KeyF12 KeyId = "f12" )
Special key constants (pi: Key object).
const ( KeyBacktick KeyId = "`" KeyHyphen KeyId = "-" KeyEquals KeyId = "=" KeyLeftBracket KeyId = "[" KeyRightBracket KeyId = "]" KeyBackslash KeyId = "\\" KeySemicolon KeyId = ";" KeyQuote KeyId = "'" KeyComma KeyId = "," KeyPeriod KeyId = "." KeySlash KeyId = "/" KeyExclamation KeyId = "!" KeyAt KeyId = "@" KeyHash KeyId = "#" KeyDollar KeyId = "$" KeyPercent KeyId = "%" KeyCaret KeyId = "^" KeyAmpersand KeyId = "&" KeyAsterisk KeyId = "*" KeyLeftParen KeyId = "(" KeyRightParen KeyId = ")" KeyUnderscore KeyId = "_" KeyPlus KeyId = "+" KeyPipe KeyId = "|" KeyTilde KeyId = "~" KeyLeftBrace KeyId = "{" KeyRightBrace KeyId = "}" KeyColon KeyId = ":" KeyLessThan KeyId = "<" KeyGreaterThan KeyId = ">" KeyQuestion KeyId = "?" )
Symbol key constants (pi: Key object symbol members).
type KeyReleaseOptIn ¶
type KeyReleaseOptIn interface {
WantsKeyRelease() bool
}
KeyReleaseOptIn is the optional capability marking components that want to receive key release events (Kitty protocol). Default is filtered out (pi: wantsKeyRelease?: boolean).
type Keybinding ¶
type Keybinding = string
Keybinding identifies a bindable action (pi: keyof Keybindings).
type KeybindingConflict ¶
KeybindingConflict reports a key claimed by multiple user bindings.
type KeybindingDefinition ¶
KeybindingDefinition holds the default keys and a description. DefaultKeys is a slice to express pi's KeyId | KeyId[] union.
type KeybindingDefinitions ¶
type KeybindingDefinitions map[string]KeybindingDefinition
KeybindingDefinitions maps keybinding ids to definitions (pi: Record<string, KeybindingDefinition>; DefaultKeys uses a []KeyId slice to express pi's KeyId | KeyId[] union).
type KeybindingsConfig ¶
KeybindingsConfig maps keybinding ids to user-chosen keys (pi: Record<string, KeyId | KeyId[] | undefined>; a nil slice = undefined).
type KeybindingsManager ¶
type KeybindingsManager struct {
// contains filtered or unexported fields
}
KeybindingsManager resolves keybinding ids to key sequences.
func GetKeybindings ¶
func GetKeybindings() *KeybindingsManager
GetKeybindings returns the global keybindings manager, lazily initialized with the defaults.
func NewKeybindingsManager ¶
func NewKeybindingsManager(definitions KeybindingDefinitions, userBindings KeybindingsConfig) *KeybindingsManager
NewKeybindingsManager creates a manager for the given definitions and user overrides.
func (*KeybindingsManager) GetConflicts ¶
func (m *KeybindingsManager) GetConflicts() []KeybindingConflict
GetConflicts returns the current user-binding conflicts (defensive copy).
func (*KeybindingsManager) GetDefinition ¶
func (m *KeybindingsManager) GetDefinition(keybinding Keybinding) KeybindingDefinition
GetDefinition returns the definition for the keybinding.
func (*KeybindingsManager) GetKeys ¶
func (m *KeybindingsManager) GetKeys(keybinding Keybinding) []KeyId
GetKeys returns the keys bound to the keybinding (defensive copy).
func (*KeybindingsManager) GetResolvedBindings ¶
func (m *KeybindingsManager) GetResolvedBindings() KeybindingsConfig
GetResolvedBindings returns the effective bindings per keybinding (pi: single key as scalar is folded back into a one-element slice).
func (*KeybindingsManager) GetUserBindings ¶
func (m *KeybindingsManager) GetUserBindings() KeybindingsConfig
GetUserBindings returns the user overrides (defensive copy).
func (*KeybindingsManager) Matches ¶
func (m *KeybindingsManager) Matches(data string, keybinding Keybinding) bool
Matches reports whether data matches any key bound to the keybinding.
func (*KeybindingsManager) SetUserBindings ¶
func (m *KeybindingsManager) SetUserBindings(userBindings KeybindingsConfig)
SetUserBindings replaces the user overrides and re-resolves.
type KeyboardProtocolNegotiationSequence ¶
type KeyboardProtocolNegotiationSequence struct {
Type string // "kitty-flags" | "device-attributes"
Flags int // only for "kitty-flags"
}
KeyboardProtocolNegotiationSequence is a parsed keyboard-protocol response. pi: tagged union { type: "kitty-flags" | "device-attributes", ... }.
func ParseKeyboardProtocolNegotiationSequence ¶
func ParseKeyboardProtocolNegotiationSequence(sequence string) *KeyboardProtocolNegotiationSequence
ParseKeyboardProtocolNegotiationSequence parses a Kitty flags reply (CSI ? <flags> u) or a device-attributes reply (CSI ? <attrs> c). Returns nil when the sequence is not a negotiation response.
type KillRing ¶
type KillRing struct {
// contains filtered or unexported fields
}
KillRing is a ring buffer for Emacs-style kill/yank operations.
Tracks killed (deleted) text entries. Consecutive kills can accumulate into a single entry. Supports yank (paste most recent) and yank-pop (cycle through older entries).
func (*KillRing) Push ¶
func (k *KillRing) Push(text string, opts KillRingPushOptions)
Push adds text to the kill ring.
type KillRingPushOptions ¶
type KillRingPushOptions struct {
// Prepend: if accumulating, prepend (backward deletion) or append (forward deletion).
Prepend bool
// Accumulate merges with the most recent entry instead of creating a new one.
Accumulate bool
}
KillRingPushOptions mirrors pi's push opts parameter.
type KittyImageMetadata ¶
KittyImageMetadata describes a registered Kitty image's cell footprint (pi: KittyImageMetadata).
func GetKittyImageMetadata ¶
func GetKittyImageMetadata(line string) *KittyImageMetadata
GetKittyImageMetadata returns the registered metadata referenced by a Kitty image line (pi: getKittyImageMetadata).
type KittyImagePlacement ¶
type KittyImagePlacement struct {
ImageId int
TransmissionGeneration int
TransmissionBytes int
EstimatedDecodedBytes int
// Rows is the number of terminal rows the placement covers (explicit
// `r=` control when present, else the registered metadata rows).
Rows int
Sequence string
ReplacementLine string
}
KittyImagePlacement describes a placement-only retransmission for an image line emitted by the image renderer (pi: KittyImagePlacement).
func GetKittyImagePlacement ¶
func GetKittyImagePlacement(line string) *KittyImagePlacement
GetKittyImagePlacement builds a placement-only command for an image line emitted by the image renderer (pi: getKittyImagePlacement).
type LayoutBox ¶
type LayoutBox struct {
Component Component
Rect LayoutRect
Clip LayoutRect
Children []*LayoutBox
Parent *LayoutBox
Lines []string // nil = container box
LineOffset int
ScrollView *ScrollView
ScrollContentLines []string
Layer int
}
LayoutBox is one laid-out component in the frame tree (pi: LayoutBox).
func GetLayoutBoxesAt ¶
func GetLayoutBoxesAt(frame *LayoutFrame, x int, y int) []*LayoutBox
GetLayoutBoxesAt returns the visual hit path from the deepest component to the layout root (pi: getLayoutBoxesAt). Boxes are ordered outermost-layer first, deepest-node first within a layer.
func GetScrollViewBox ¶
func GetScrollViewBox(frame *LayoutFrame, scrollView *ScrollView) *LayoutBox
GetScrollViewBox finds the LayoutBox for a scroll view in the frame (pi: getScrollViewBox).
type LayoutComponent ¶
type LayoutComponent interface {
Component
LayoutNode() LayoutNode
}
LayoutComponent is implemented by components that expose a layout node (pi: LayoutComponent with the LAYOUT_NODE symbol; Go has no symbol injection, so the protocol is an interface method).
type LayoutFrame ¶
type LayoutFrame struct {
Root *LayoutBox
Width int
Height int
Lines []string
PrimaryScrollView *ScrollView
}
LayoutFrame is the result of renderLayoutFrame (pi: LayoutFrame).
func RenderLayoutFrame ¶
func RenderLayoutFrame(root Component, width int, height int, requestRender func()) *LayoutFrame
RenderLayoutFrame lays out the component tree and paints it into a screen buffer of height rows (pi: renderLayoutFrame).
type LayoutNode ¶
type LayoutNode interface {
// contains filtered or unexported methods
}
LayoutNode is pi's `StackLayoutNode | ScrollLayoutNode` union.
func GetLayoutNode ¶
func GetLayoutNode(component Component) LayoutNode
GetLayoutNode returns the layout node of a component implementing LayoutComponent, or nil (pi: getLayoutNode).
type LayoutRect ¶
LayoutRect is an axis-aligned rectangle in screen coordinates.
type LayoutViewport ¶
LayoutViewport is the visible region passed to entry visibility predicates.
type Loader ¶
type Loader struct {
Text
// contains filtered or unexported fields
}
Loader is the spinning loader (pi: class Loader extends Text).
func NewLoader ¶
func NewLoader(ui TUI, spinnerColorFn func(string) string, messageColorFn func(string) string, message string, indicator *LoaderIndicatorOptions) *Loader
NewLoader mirrors pi's constructor (indicator may be nil).
func (*Loader) GetRenderedIndicator ¶
GetRenderedIndicator exposes the current colorized frame (pi: protected getRenderedIndicator; consumed by WorkingStatusIndicator's renderSpinnerInBorder, which subclasses Loader in pi but embeds it in pig).
func (*Loader) Invalidate ¶
func (l *Loader) Invalidate()
Invalidate implements Component: theme changes must re-render the loader text with the new color functions (pi: override invalidate).
func (*Loader) SetIndicator ¶
func (l *Loader) SetIndicator(indicator *LoaderIndicatorOptions)
func (*Loader) SetMessage ¶
type LoaderIndicatorOptions ¶
type LoaderIndicatorOptions struct {
/** Animation frames. Use an empty array to hide the indicator. */
Frames []string
/** Frame interval in milliseconds for animated indicators. */
IntervalMs int
}
LoaderIndicatorOptions mirrors pi's LoaderIndicatorOptions.
type Markdown ¶
type Markdown struct {
// contains filtered or unexported fields
}
Markdown is the markdown component (pi: class Markdown implements Component).
func NewMarkdown ¶
func NewMarkdown(text string, paddingX int, paddingY int, theme MarkdownTheme, defaultTextStyle *DefaultTextStyle, options *MarkdownOptions) *Markdown
NewMarkdown mirrors pi's constructor (defaultTextStyle/options may be nil).
func (*Markdown) Invalidate ¶
func (m *Markdown) Invalidate()
type MarkdownOptions ¶
type MarkdownOptions struct {
// Preserve source list markers instead of normalizing them.
PreserveOrderedListMarkers bool
// Preserve source backslash escapes instead of normalizing escaped
// punctuation.
PreserveBackslashEscapes bool
// Transform source Markdown before parsing, with the exact width
// available for content.
Transform func(markdown string, availableWidth int) string
// RenderLatex renders supported LaTeX math expressions as Unicode text
// (default true; nil = default).
RenderLatex *bool
}
MarkdownOptions mirrors pi's MarkdownOptions.
type MarkdownTheme ¶
type MarkdownTheme struct {
Heading func(text string) string
Link func(text string) string
LinkURL func(text string) string
Code func(text string) string
CodeBlock func(text string) string
CodeBlockBorder func(text string) string
Quote func(text string) string
QuoteBorder func(text string) string
Hr func(text string) string
ListBullet func(text string) string
Bold func(text string) string
Italic func(text string) string
Strikethrough func(text string) string
Underline func(text string) string
HighlightCode func(code string, lang string) []string
// CodeBlockIndent is the prefix applied to each rendered code block line
// (default " ").
CodeBlockIndent string
}
MarkdownTheme holds theme functions for markdown elements. Each function takes text and returns styled text with ANSI codes (pi: MarkdownTheme).
type MarkedToken ¶
type MarkedToken struct {
Type string
Raw string
Text string
Tokens []*MarkedToken
Depth int // heading
Lang string // code (fences)
Tag string // def
Href string // link
Title string // def / link title ("" = none; pi: string|null)
Block bool // html
InLink bool // html (inline)
InRawBlock bool // html (inline)
Escaped bool // text (inline): follows a raw block
Ordered bool // list
Start any // list: int when ordered (pi: typeof start === "number"), "" otherwise
Loose bool // list
Items []*MarkedToken
Task bool // list_item
Checked bool // list_item / checkbox
Header *bool // table cell (header vs body)
Align string // table cell: "right"|"center"|"" (left and null share "")
// table
HeaderCells []*MarkedToken
Rows [][]*MarkedToken
Aligns []string
// extensions (latex, markdown.ts)
Pending bool
}
MarkedToken models marked's token objects. Fields are zero for token types that don't carry them (pi: `token.text`, `token.tokens`, ... optional members). The latex extension (markdown.ts) uses Pending.
func MarkedLex ¶
func MarkedLex(src string) []*MarkedToken
MarkedLex is the stock marked lexer entry (pi: `new Marked().lexer(src)` in components/mermaid.ts — the npm marked package re-exported by pi-tui). pig addition: markedLex is unexported and the markdown component's latex extension must NOT run here, so this wrapper lexes with no extensions (stock marked defaults: gfm=true, breaks=false).
func (*MarkedToken) HasTextProperty ¶
func (t *MarkedToken) HasTextProperty() bool
HasTextProperty reports whether the underlying marked token object carries a `text` property (pi: `'text' in token`). Go structs always have their fields, so this is derived from the token type; the checkbox token is the case observable through renderToken/renderInlineTokens defaults.
func (*MarkedToken) StartNumber ¶
func (t *MarkedToken) StartNumber() (int, bool)
StartNumber returns the list start when numeric (pi: typeof token.start === "number").
type ModifierKey ¶ added in v0.86.0
type ModifierKey string
ModifierKey is a physically probeable modifier key (pi: type ModifierKey = "shift" | "command" | "control" | "option").
const ( ModifierKeyShift ModifierKey = "shift" ModifierKeyCommand ModifierKey = "command" ModifierKeyControl ModifierKey = "control" ModifierKeyOption ModifierKey = "option" )
type MouseHandler ¶
type MouseHandler interface {
Component
HandleMouse(event *TuiMouseEvent) *TuiMouseEventResult
}
MouseHandler is the optional capability for components that receive normalized mouse events (pi: handleMouse?).
type MouseRegion ¶
type MouseRegion struct {
// contains filtered or unexported fields
}
MouseRegion adds mouse handling to an existing component without changing its rendering (pi: MouseRegion implements Component).
func NewMouseRegion ¶
func NewMouseRegion(child Component, onMouse MouseRegionHandler) *MouseRegion
NewMouseRegion wraps child with a mouse handler.
func (*MouseRegion) HandleMouse ¶
func (m *MouseRegion) HandleMouse(event *TuiMouseEvent) *TuiMouseEventResult
HandleMouse implements MouseHandler: try the child first, then the region's own handler (pi: handleMouse).
func (*MouseRegion) Invalidate ¶
func (m *MouseRegion) Invalidate()
Invalidate implements Component (delegates to the child).
func (*MouseRegion) Render ¶
func (m *MouseRegion) Render(width int) []string
Render implements Component (delegates to the child).
type MouseRegionHandler ¶
type MouseRegionHandler = func(event *TuiMouseEvent) *TuiMouseEventResult
MouseRegionHandler handles a mouse event targeted at the wrapped child region (pi: MouseRegionHandler).
type NativeClipboard ¶ added in v0.86.0
type NativeClipboard interface {
GetText() (text *string, ok bool, err error)
GetImage() (image []byte, ok bool, err error)
// SetText writes text to the system clipboard. Only Linux lacks it:
// command-line tools are used there to retain clipboard ownership
// (pi: setText? optional member).
SetText(text string) error
}
NativeClipboard mirrors pi v0.86.0's NativeClipboard interface. Three-state semantics (pi: string | null | undefined):
- ok == false → helper/display unavailable (pi undefined);
- ok == true, nil value → empty clipboard (pi null);
- ok == true, value → payload. Transfer failures surface as err (pi: promise rejection).
func GetNativeClipboard ¶ added in v0.86.0
func GetNativeClipboard() NativeClipboard
GetNativeClipboard returns the platform clipboard helper without opening the display until a read is requested (pi: getNativeClipboard — Linux requires DISPLAY for the X11 helper). Always nil in pig: there is no native helper to load (see file header).
type OkhslChannels ¶ added in v1.0.0
OkhslChannels holds OKHSL channels: hue h in degrees, saturation s and lightness l 0-1.
func ColorToOkhsl ¶ added in v1.0.0
func ColorToOkhsl(color Color) OkhslChannels
ColorToOkhsl reads a color's OKHSL channels (pi: colorToOkhsl).
func RgbToOkhsl ¶ added in v1.0.0
func RgbToOkhsl(c RgbColor) OkhslChannels
RgbToOkhsl converts sRGB channels (0-255) to OKHSL. Hue is in degrees (0 for grays); saturation and lightness are 0-1.
type OklchChannels ¶ added in v1.0.0
OklchChannels holds OKLCH channels (pi: OklchChannels).
func ColorToOklch ¶ added in v1.0.0
func ColorToOklch(color Color) OklchChannels
ColorToOklch converts any color to OKLCH (pi: colorToOklch).
type OscColorTarget ¶ added in v1.0.0
type OscColorTarget struct {
// PaletteIndex >= 0 selects the palette slot; -1 means foreground or background.
PaletteIndex int
// Foreground distinguishes foreground from background when PaletteIndex < 0.
Foreground bool
}
OscColorTarget is what an OSC color reply reports: the default foreground (OSC 10), background (OSC 11), or a palette index (OSC 4) (pi: OscColorTarget = "foreground" | "background" | number).
type OverlayAnchor ¶
type OverlayAnchor = string
OverlayAnchor is the anchor position for overlays.
const ( OverlayAnchorCenter OverlayAnchor = "center" OverlayAnchorTopLeft OverlayAnchor = "top-left" OverlayAnchorTopRight OverlayAnchor = "top-right" OverlayAnchorBottomLeft OverlayAnchor = "bottom-left" OverlayAnchorBottomRight OverlayAnchor = "bottom-right" OverlayAnchorTopCenter OverlayAnchor = "top-center" OverlayAnchorBottomCenter OverlayAnchor = "bottom-center" OverlayAnchorLeftCenter OverlayAnchor = "left-center" OverlayAnchorRightCenter OverlayAnchor = "right-center" )
type OverlayBounds ¶
OverlayBounds is the last rendered terminal-relative overlay rectangle (pi: OverlayBounds).
type OverlayHandle ¶
type OverlayHandle interface {
// Hide permanently removes the overlay (cannot be shown again).
Hide()
// SetHidden temporarily hides or shows the overlay.
SetHidden(hidden bool)
// IsHidden reports whether the overlay is temporarily hidden.
IsHidden() bool
// Focus focuses this overlay and brings it to the visual front.
Focus()
// Unfocus releases focus to the next visible capturing overlay or
// previous target, or to an explicit target when provided.
Unfocus(options *OverlayUnfocusOptions)
// IsFocused reports whether this overlay currently has focus.
IsFocused() bool
// GetBounds returns the most recent rendered bounds for a visible
// overlay (pi: getBounds). Nil when not currently rendered/visible.
GetBounds() *OverlayBounds
}
OverlayHandle is returned by ShowOverlay for controlling the overlay.
type OverlayMargin ¶
OverlayMargin is margin configuration for overlays. Nil members mean unset.
type OverlayOptions ¶
type OverlayOptions struct {
// === Sizing ===
// Width in columns, or percentage of terminal width (e.g., "50%").
Width any
// Minimum width in columns.
MinWidth int
// Maximum height in rows, or percentage of terminal height.
MaxHeight any
// === Positioning - anchor-based ===
// Anchor point for positioning (default: center).
Anchor OverlayAnchor
// Horizontal offset from anchor position (positive = right).
OffsetX int
// Vertical offset from anchor position (positive = down).
OffsetY int
// === Positioning - percentage or absolute ===
// Row position: absolute number, or percentage (e.g., "25%" = 25% from top).
Row any
// Column position: absolute number, or percentage (e.g., "50%" = centered).
Col any
// === Margin from terminal edges ===
// Margin from terminal edges: int applies to all sides, or *OverlayMargin.
Margin any
// === Visibility ===
// Visible controls overlay visibility based on terminal dimensions.
// If provided, the overlay is only rendered when it returns true.
// Called each render cycle with current terminal dimensions.
Visible func(termWidth int, termHeight int) bool
// NonCapturing: if true, don't capture keyboard focus when shown.
NonCapturing bool
}
OverlayOptions configures overlay positioning and sizing. Size fields (Width/MaxHeight/Row/Col) accept an absolute int or a percentage string like "50%" (pi: SizeValue = number | `${number}%`).
type OverlayUnfocusOptions ¶
type OverlayUnfocusOptions struct {
// Target is the component to focus after releasing this overlay.
Target Component
}
OverlayUnfocusOptions carries the explicit target for OverlayHandle.Unfocus.
type ProcessTerminal ¶
type ProcessTerminal struct {
// contains filtered or unexported fields
}
ProcessTerminal is the real terminal using stdin/stdout.
func NewProcessTerminal ¶
func NewProcessTerminal() *ProcessTerminal
NewProcessTerminal creates a ProcessTerminal bound to stdin/stdout.
func (*ProcessTerminal) ClearFromCursor ¶
func (t *ProcessTerminal) ClearFromCursor()
func (*ProcessTerminal) ClearLine ¶
func (t *ProcessTerminal) ClearLine()
func (*ProcessTerminal) ClearScreen ¶
func (t *ProcessTerminal) ClearScreen()
func (*ProcessTerminal) Columns ¶
func (t *ProcessTerminal) Columns() int
func (*ProcessTerminal) DrainInput ¶
func (t *ProcessTerminal) DrainInput(maxMs int, idleMs int)
DrainInput drains stdin before exiting. See Terminal.
func (*ProcessTerminal) HideCursor ¶
func (t *ProcessTerminal) HideCursor()
func (*ProcessTerminal) KittyProtocolActive ¶
func (t *ProcessTerminal) KittyProtocolActive() bool
func (*ProcessTerminal) ModifyOtherKeysActive ¶
func (t *ProcessTerminal) ModifyOtherKeysActive() bool
ModifyOtherKeysActive reports whether the modifyOtherKeys fallback is on.
func (*ProcessTerminal) MoveBy ¶
func (t *ProcessTerminal) MoveBy(lines int)
func (*ProcessTerminal) RestoreOnExit ¶ added in v1.4.0
func (t *ProcessTerminal) RestoreOnExit(before string, after string)
RestoreOnExit synchronously restores terminal modes when the process exits without Stop (pi: ProcessTerminal.restoreOnExit, #11170).
func (*ProcessTerminal) Rows ¶
func (t *ProcessTerminal) Rows() int
func (*ProcessTerminal) SetProgramStatus ¶ added in v1.1.0
func (t *ProcessTerminal) SetProgramStatus(status ProgramStatus)
SetProgramStatus reports what the program is doing (OSC 7501) (pi: setProgramStatus).
func (*ProcessTerminal) SetProgress ¶
func (t *ProcessTerminal) SetProgress(active bool)
func (*ProcessTerminal) SetTitle ¶
func (t *ProcessTerminal) SetTitle(title string)
func (*ProcessTerminal) ShowCursor ¶
func (t *ProcessTerminal) ShowCursor()
func (*ProcessTerminal) Start ¶
func (t *ProcessTerminal) Start(onInput func(data string), onResize func())
func (*ProcessTerminal) Stop ¶
func (t *ProcessTerminal) Stop()
func (*ProcessTerminal) Write ¶
func (t *ProcessTerminal) Write(data string)
type ProgramStatus ¶ added in v1.1.0
type ProgramStatus struct {
// State reports idle/working/blocked/done/error/clear.
State ProgramStatusState
// App is the stable program name, `[A-Za-z0-9_.+-]{1,32}`. Other values
// are omitted.
App string
// Kind is what a blocked program waits for; omitted for other states.
Kind ProgramStatusBlockedKind
// Message is one human-readable line. Control characters become spaces;
// longer text is cut to the spec limit.
Message string
}
ProgramStatus is one OSC 7501 report (pi: ProgramStatus).
type ProgramStatusBlockedKind ¶ added in v1.1.0
type ProgramStatusBlockedKind string
ProgramStatusBlockedKind is what a blocked program waits for (pi: ProgramStatus["kind"]; omitted for other states).
const ( ProgramStatusBlockedPermission ProgramStatusBlockedKind = "permission" ProgramStatusBlockedQuestion ProgramStatusBlockedKind = "question" ProgramStatusBlockedAuth ProgramStatusBlockedKind = "auth" )
type ProgramStatusState ¶ added in v1.1.0
type ProgramStatusState string
ProgramStatusState is the state pair of a status report. "clear" removes the status instead of reporting one (pi: ProgramStatus["state"]).
const ( ProgramStatusIdle ProgramStatusState = "idle" ProgramStatusWorking ProgramStatusState = "working" ProgramStatusBlocked ProgramStatusState = "blocked" ProgramStatusDone ProgramStatusState = "done" ProgramStatusError ProgramStatusState = "error" ProgramStatusClear ProgramStatusState = "clear" )
type RgbColor ¶
RgbColor is an 8-bit RGB color triple.
func ColorToRgb ¶ added in v1.0.0
ColorToRgb converts any color to its sRGB channels (pi: colorToRgb).
func LinearSrgbToRgb ¶ added in v1.0.0
func LinearSrgbToRgb(linear vector3) RgbColor
LinearSrgbToRgb converts linear sRGB [r, g, b] to sRGB channels (0-255, rounded), clipping out-of-gamut channels.
func OkhslToRgb ¶ added in v1.0.0
OkhslToRgb converts OKHSL to sRGB channels (0-255, rounded), clipping out-of-gamut channels.
- hue: hue in degrees.
- saturation: saturation, 0-1.
- lightness: lightness, 0-1.
type ScrollLayoutNode ¶
type ScrollLayoutNode struct {
Type string // "scroll"
Component Component
State ScrollLayoutState
}
ScrollLayoutNode is the layout description produced by ScrollView.
type ScrollLayoutState ¶
type ScrollLayoutState interface {
ScrollTop() int
Primary() bool
Overscroll() string // "chain" | "contain"
ViewportHeight() int
GetContentWidth(width int) int
UpdateLayout(contentHeight int, viewportHeight int, requestRender func())
}
ScrollLayoutState is the state protocol a scroll container exposes to the layout engine (pi: ScrollLayoutState). *ScrollView is the only implementation.
type ScrollView ¶
type ScrollView struct {
Container
// contains filtered or unexported fields
}
ScrollView is a vertical scrolling container for a single child (pi: ScrollView extends Container).
func GetScrollViewsAt ¶
func GetScrollViewsAt(frame *LayoutFrame, x int, y int) []*ScrollView
GetScrollViewsAt returns the scroll views whose rects contain the point, deepest first (pi: getScrollViewsAt).
func NewScrollView ¶
func NewScrollView(component Component, options *ScrollViewOptions) *ScrollView
NewScrollView creates a ScrollView wrapping component.
func (*ScrollView) AddChild ¶
func (s *ScrollView) AddChild(_ Component)
AddChild overrides Container.AddChild: ScrollView has exactly one child.
func (*ScrollView) FollowEnd ¶
func (s *ScrollView) FollowEnd() bool
FollowEnd reports whether the view tracks the content end (pi: readonly followEnd).
func (*ScrollView) GetContentWidth ¶
func (s *ScrollView) GetContentWidth(width int) int
GetContentWidth returns the content width given the viewport width, reserving one column for an always-visible scrollbar (pi: getContentWidth).
func (*ScrollView) IsFollowingEnd ¶
func (s *ScrollView) IsFollowingEnd() bool
IsFollowingEnd reports whether the view tracks the content end (pi: isFollowingEnd getter).
func (*ScrollView) IsScrollbarActive ¶
func (s *ScrollView) IsScrollbarActive() bool
IsScrollbarActive reports whether the pointer is interacting with the scrollbar (pi: isScrollbarActive getter).
func (*ScrollView) IsScrollbarVisible ¶
func (s *ScrollView) IsScrollbarVisible() bool
IsScrollbarVisible reports whether the scrollbar paints this frame (pi: isScrollbarVisible getter).
func (*ScrollView) LayoutNode ¶
func (s *ScrollView) LayoutNode() LayoutNode
LayoutNode implements LayoutComponent (pi: [LAYOUT_NODE]()).
func (*ScrollView) Overscroll ¶
func (s *ScrollView) Overscroll() string
Overscroll returns the overscroll chaining mode (pi: readonly overscroll).
func (*ScrollView) Primary ¶
func (s *ScrollView) Primary() bool
Primary reports whether this is the primary scroll view (pi: readonly primary).
func (*ScrollView) RemoveChild ¶
func (s *ScrollView) RemoveChild(_ Component)
RemoveChild overrides Container.RemoveChild.
func (*ScrollView) Render ¶
func (s *ScrollView) Render(width int) []string
Render implements Component (pi: render override).
func (*ScrollView) ScrollBy ¶
func (s *ScrollView) ScrollBy(lines int) int
ScrollBy scrolls by a relative amount and returns the unused delta (pi: scrollBy).
func (*ScrollView) ScrollTo ¶
func (s *ScrollView) ScrollTo(scrollTop int, options *ScrollViewScrollToOptions)
ScrollTo scrolls to an absolute offset (pi: scrollTo).
func (*ScrollView) ScrollToEnd ¶
func (s *ScrollView) ScrollToEnd()
ScrollToEnd scrolls to the bottom (pi: scrollToEnd).
func (*ScrollView) ScrollToStart ¶
func (s *ScrollView) ScrollToStart()
ScrollToStart scrolls to the top (pi: scrollToStart).
func (*ScrollView) ScrollTop ¶
func (s *ScrollView) ScrollTop() int
ScrollTop returns the current scroll offset (pi: scrollTop getter).
func (*ScrollView) Scrollbar ¶
func (s *ScrollView) Scrollbar() ScrollViewScrollbar
Scrollbar returns the current scrollbar mode (pi: scrollbar getter).
func (*ScrollView) ScrollbarThumbStyle ¶
func (s *ScrollView) ScrollbarThumbStyle(text string) string
ScrollbarThumbStyle returns the scrollbar thumb cell styler (pi: readonly scrollbarThumbStyle).
func (*ScrollView) ScrollbarTrackStyle ¶
func (s *ScrollView) ScrollbarTrackStyle(text string) string
ScrollbarTrackStyle returns the scrollbar track cell styler (pi: readonly scrollbarTrackStyle).
func (*ScrollView) SetScrollbar ¶
func (s *ScrollView) SetScrollbar(scrollbar ScrollViewScrollbar)
SetScrollbar switches the scrollbar mode (pi: setScrollbar).
func (*ScrollView) SetScrollbarActive ¶
func (s *ScrollView) SetScrollbarActive(active bool)
SetScrollbarActive marks pointer interaction with the scrollbar (pi: setScrollbarActive). Activity changes request a render so hover states paint promptly.
func (*ScrollView) UpdateLayout ¶
func (s *ScrollView) UpdateLayout(contentHeight int, viewportHeight int, requestRender func())
UpdateLayout is the ScrollLayoutState callback invoked by the layout engine (pi: updateLayout).
func (*ScrollView) ViewportHeight ¶
func (s *ScrollView) ViewportHeight() int
ViewportHeight returns the last laid-out viewport height (pi: viewportHeight getter).
type ScrollViewOptions ¶
type ScrollViewOptions struct {
Axis any // "vertical" only; nil = default. Any other value panics in the constructor.
Follow string // "none" | "end"; "" = "none"
Primary bool
Overscroll string // "chain" | "contain"; "" = "chain"
Scrollbar ScrollViewScrollbar
ScrollbarTrackStyle func(text string) string
ScrollbarThumbStyle func(text string) string
ScrollbarHideDelayMs *int
}
ScrollViewOptions configures a ScrollView (pi: ScrollViewOptions).
type ScrollViewScrollToOptions ¶
type ScrollViewScrollToOptions struct {
// DisableFollow keeps follow-end disabled even when the target is the
// current content end.
DisableFollow bool
}
ScrollViewScrollToOptions carries pi's scrollTo options.
type ScrollViewScrollbar ¶
type ScrollViewScrollbar = string
ScrollViewScrollbar selects scrollbar visibility (pi: ScrollViewScrollbar).
const ( ScrollViewScrollbarHidden ScrollViewScrollbar = "hidden" ScrollViewScrollbarAuto ScrollViewScrollbar = "auto" ScrollViewScrollbarAlways ScrollViewScrollbar = "always" )
type ScrollbarGeometry ¶
type ScrollbarGeometry struct {
Column int
TrackTop int
TrackHeight int
ThumbTop int
ThumbHeight int
MaxScrollTop int
}
ScrollbarGeometry describes a painted scrollbar (pi: ScrollbarGeometry).
func GetScrollbarGeometry ¶
func GetScrollbarGeometry(box *LayoutBox, includeHiddenAuto ...bool) *ScrollbarGeometry
GetScrollbarGeometry computes the scrollbar geometry for a laid-out scroll view box (pi: getScrollbarGeometry). includeHiddenAuto also reveals auto-scrollbars whose content overflows but whose transient visibility is currently off (used for track hit-testing). Returns nil when no scrollbar paints.
type SegmentData ¶
type SegmentData struct {
// Segment is the segment text.
Segment string
// Index is the byte offset of the segment start in the segmented input.
Index int
// IsWordLike reports whether the segment is word-like (letters/numbers).
// Always false for grapheme segmentation (pi: undefined for graphemes).
IsWordLike bool
}
SegmentData is the Go equivalent of the Intl.SegmentData entries produced by Intl.Segmenter.segment() (pi consumes { segment, index, isWordLike }).
type SegmenterFunc ¶
type SegmenterFunc func(text string) []SegmentData
SegmenterFunc produces segments for text (the Go stand-in for passing an Intl.Segmenter around).
type SegmentsResult ¶
SegmentsResult carries the "before" and "after" slices produced by ExtractSegments.
func ExtractSegments ¶
func ExtractSegments(line string, beforeEnd int, afterStart int, afterLen int, strictAfter bool) SegmentsResult
ExtractSegments extracts "before" and "after" segments from a line in a single pass. Used for overlay compositing where we need content before and after the overlay region. Preserves styling from before the overlay that should affect content after it.
type SelectItem ¶
SelectItem is one selectable entry (pi: SelectItem). Description is optional (pi: description?); "" means absent (TS falsy equivalent).
type SelectList ¶
type SelectList struct {
// OnSelect is called on confirm (pi: public onSelect?).
OnSelect func(item SelectItem)
// OnCancel is called on cancel (pi: public onCancel?).
OnCancel func()
// OnSelectionChange is called when the selection moves (pi: public
// onSelectionChange?).
OnSelectionChange func(item SelectItem)
// contains filtered or unexported fields
}
SelectList is a scrollable list of selectable items (pi: SelectList). It implements Component and InputHandler.
func NewSelectList ¶
func NewSelectList(items []SelectItem, maxVisible int, theme SelectListTheme, layout *SelectListLayoutOptions) *SelectList
NewSelectList creates a select list (pi: constructor; layout optional — pass nil for defaults).
func (*SelectList) GetSelectedItem ¶
func (s *SelectList) GetSelectedItem() *SelectItem
GetSelectedItem returns the selected item or nil (pi: getSelectedItem — item || null, i.e. undefined when out of range).
func (*SelectList) HandleInput ¶
func (s *SelectList) HandleInput(keyData string)
HandleInput implements InputHandler (pi: handleInput).
func (*SelectList) HandleMouse ¶
func (s *SelectList) HandleMouse(event *TuiMouseEvent) *TuiMouseEventResult
HandleMouse implements MouseHandler (pi: SelectList.handleMouse): wheel moves the selection, left press/click select and confirm.
func (*SelectList) Invalidate ¶
func (s *SelectList) Invalidate()
Invalidate clears cached render state (pi: invalidate — no cached state).
func (*SelectList) Render ¶
func (s *SelectList) Render(width int) []string
Render implements Component (pi: render).
func (*SelectList) SetFilter ¶
func (s *SelectList) SetFilter(filter string)
SetFilter filters items by case-insensitive value prefix and resets the selection (pi: setFilter).
func (*SelectList) SetSelectedIndex ¶
func (s *SelectList) SetSelectedIndex(index int)
SetSelectedIndex clamps and sets the selection (pi: setSelectedIndex).
type SelectListLayoutOptions ¶
type SelectListLayoutOptions struct {
MinPrimaryColumnWidth int
MaxPrimaryColumnWidth int
TruncatePrimary func(context SelectListTruncatePrimaryContext) string
}
SelectListLayoutOptions configures the primary column layout (pi: SelectListLayoutOptions). Zero-value fields mean "not provided" (pi: optional members).
type SelectListTheme ¶
type SelectListTheme struct {
SelectedPrefix func(text string) string
SelectedText func(text string) string
Description func(text string) string
ScrollInfo func(text string) string
NoMatch func(text string) string
}
SelectListTheme colors the select list output (pi: SelectListTheme).
type SelectListTruncatePrimaryContext ¶
type SelectListTruncatePrimaryContext struct {
Text string
MaxWidth int
ColumnWidth int
Item SelectItem
IsSelected bool
}
SelectListTruncatePrimaryContext is the argument of a custom truncatePrimary hook (pi: SelectListTruncatePrimaryContext).
type SettingItem ¶
type SettingItem struct {
// Id is the unique identifier for this setting.
Id string
// Label is the display label (left side).
Label string
// Description is shown when selected (empty = none).
Description string
// CurrentValue is the value to display (right side).
CurrentValue string
// Values cycle on Enter when non-empty.
Values []string
// accepts an optional selectedValue and an optional navigateTo id to
// move the cursor after close (pi: done(selectedValue?, options?)).
Submenu func(currentValue string, done func(selectedValue string, options *SettingsSubmenuDoneOptions)) Component
}
SettingItem is one row of a SettingsList (pi: SettingItem).
type SettingsList ¶
type SettingsList struct {
// contains filtered or unexported fields
}
SettingsList is a scrollable list of settings with optional cycling values, submenus, and search (pi: SettingsList implements Component).
func NewSettingsList ¶
func NewSettingsList( items []*SettingItem, maxVisible int, theme SettingsListTheme, onChange func(id string, newValue string), onCancel func(), options *SettingsListOptions, ) *SettingsList
NewSettingsList creates a SettingsList.
func (*SettingsList) HandleInput ¶
func (l *SettingsList) HandleInput(data string)
HandleInput implements InputHandler (pi: handleInput).
func (*SettingsList) HandleMouse ¶
func (l *SettingsList) HandleMouse(event *TuiMouseEvent) *TuiMouseEventResult
HandleMouse implements MouseHandler (pi: SettingsList.handleMouse): submenu rows take priority, then the search row, then wheel/press/click on items.
func (*SettingsList) Invalidate ¶
func (l *SettingsList) Invalidate()
Invalidate implements Component.
func (*SettingsList) Render ¶
func (l *SettingsList) Render(width int) []string
Render implements Component (pi: render).
func (*SettingsList) SelectItem ¶
func (l *SettingsList) SelectItem(id string)
SelectItem moves selection to the item with the given id (no-op if not found) (pi: selectItem).
func (*SettingsList) UpdateValue ¶
func (l *SettingsList) UpdateValue(id string, newValue string)
UpdateValue updates an item's currentValue (pi: updateValue).
type SettingsListOptions ¶
type SettingsListOptions struct {
EnableSearch bool
}
SettingsListOptions carries pi's SettingsListOptions.
type SettingsListTheme ¶
type SettingsListTheme struct {
Label func(text string, selected bool) string
Value func(text string, selected bool) string
Description func(text string) string
Cursor string
Hint func(text string) string
}
SettingsListTheme styles a SettingsList (pi: SettingsListTheme).
type SettingsSubmenuDoneOptions ¶
type SettingsSubmenuDoneOptions struct {
NavigateTo string
}
SettingsSubmenuDoneOptions carries pi's done() options (undefined → nil).
type SlashCommand ¶
type SlashCommand struct {
Name string
Description string
ArgumentHint string
// GetArgumentCompletions returns argument completions for this command;
// nil means no argument completion is available (pi: Awaitable<
// AutocompleteItem[] | null> → synchronous nil, see file header).
GetArgumentCompletions func(argumentPrefix string) []AutocompleteItem
}
SlashCommand describes a slash command with optional argument completions (pi: SlashCommand).
type SlashCommandOrItem ¶
type SlashCommandOrItem interface {
// contains filtered or unexported methods
}
SlashCommandOrItem is the union of slash commands and plain items accepted by CombinedAutocompleteProvider (pi: SlashCommand | AutocompleteItem). Discrimination follows pi's `"name" in cmd` probe via a type switch.
type SliceResult ¶
SliceResult is the text and visible width produced by SliceWithWidth.
func SliceWithWidth ¶
func SliceWithWidth(line string, startCol int, length int, strict bool) SliceResult
SliceWithWidth is like SliceByColumn but also returns the actual visible width of the result.
type Spacer ¶
type Spacer struct {
// contains filtered or unexported fields
}
Spacer is the empty-lines component (pi: class Spacer implements Component).
func (*Spacer) Invalidate ¶
func (s *Spacer) Invalidate()
type Stack ¶
type Stack struct {
Container
// contains filtered or unexported fields
}
Stack is the abstract base (pi: abstract class Stack).
func (*Stack) AddChild ¶
AddChild overrides Container.AddChild to also register a layout entry (pi: addChild override with default options).
func (*Stack) AddChildWithOptions ¶
func (s *Stack) AddChildWithOptions(component Component, options *StackEntryOptions)
AddChildWithOptions is pi's addChild(component, options).
func (*Stack) LayoutNode ¶
func (s *Stack) LayoutNode() LayoutNode
LayoutNode implements LayoutComponent (pi: [LAYOUT_NODE]()).
func (*Stack) RemoveChild ¶
type StackChild ¶
type StackChild any
StackChild is pi's `Component | StackEntry` union: a bare Component value or a *StackEntry built with StackEntryOf.
type StackEntry ¶
type StackEntry struct {
StackEntryOptions
Component Component
}
StackEntry is pi's `interface StackEntry extends StackEntryOptions`.
func StackEntryOf ¶
func StackEntryOf(component Component, options *StackEntryOptions) *StackEntry
StackEntryOf wraps a component with entry options (pi: the object-literal `{ component, ...options }` form in the children array).
type StackEntryOptions ¶
type StackEntryOptions struct {
Basis any // nil = absent (intrinsic), int = fixed basis, "auto" = intrinsic
Grow int
Shrink *int
MinSize int
MaxSize *int
Visible func(viewport LayoutViewport) bool
}
StackEntryOptions mirrors pi's StackEntryOptions. Shrink/MaxSize use pointers because an explicit 0 differs from absent (defaults 1 / max): Grow/MinSize collapse to the same default (0) either way, so plain ints.
type StackLayoutEntry ¶
type StackLayoutEntry struct {
Component Component
// Basis is pi's `basis?: number | "auto"`: nil = not provided (use the
// intrinsic size), int = fixed basis, "auto" = same as nil.
Basis any
// Normalized flex options. pi stores them as optional keys and defaults
// at read sites (`entry.grow ?? 0` / `?? 1` / `?? 0` / `?? MAX`); since
// Stack.AddChild normalizes with exactly those fallbacks, absent keys and
// defaults collapse to the same values, so plain ints suffice.
Grow int
Shrink int
MinSize int
MaxSize int
// Visible hides the entry from layout when it returns false
// (pi: visible?: (viewport) => boolean). nil = always visible.
Visible func(LayoutViewport) bool
}
StackLayoutEntry is one child of a Stack with its flex options (pi: StackLayoutEntry).
func VisibleStackEntries ¶
func VisibleStackEntries(entries []StackLayoutEntry, viewport LayoutViewport) []StackLayoutEntry
VisibleStackEntries filters entries by their visibility predicates (pi: visibleStackEntries).
type StackLayoutNode ¶
type StackLayoutNode struct {
Type string // "vstack" | "hstack"
Entries []StackLayoutEntry
Gap int
Align string // "stretch" | "start" | "center" | "end"
}
StackLayoutNode is the layout description produced by VStack/HStack.
type StackOptions ¶
type StackOptions struct {
Gap *int
Align string // "stretch" | "start" | "center" | "end"; "" = default "stretch"
}
StackOptions mirrors pi's StackOptions.
type StdinBuffer ¶
type StdinBuffer struct {
// contains filtered or unexported fields
}
StdinBuffer buffers stdin input and emits complete sequences via the data handler. Handles partial escape sequences that arrive across multiple chunks.
func NewStdinBuffer ¶
func NewStdinBuffer(options *stdinBufferOptions) *StdinBuffer
NewStdinBuffer creates a StdinBuffer. options may be nil for defaults.
func (*StdinBuffer) Clear ¶
func (b *StdinBuffer) Clear()
Clear drops buffered content without emitting.
func (*StdinBuffer) Destroy ¶
func (b *StdinBuffer) Destroy()
Destroy clears the buffer and stops timers.
func (*StdinBuffer) Flush ¶
func (b *StdinBuffer) Flush() []string
Flush returns and clears any buffered incomplete sequence.
func (*StdinBuffer) GetBuffer ¶
func (b *StdinBuffer) GetBuffer() string
GetBuffer returns the pending (incomplete) buffer contents.
func (*StdinBuffer) OnData ¶
func (b *StdinBuffer) OnData(handler func(string))
OnData registers the handler for complete input sequences.
func (*StdinBuffer) OnPaste ¶
func (b *StdinBuffer) OnPaste(handler func(string))
OnPaste registers the handler for bracketed paste content.
func (*StdinBuffer) Process ¶
func (b *StdinBuffer) Process(data []byte)
Process feeds input data through the buffer.
func (*StdinBuffer) ProcessString ¶
func (b *StdinBuffer) ProcessString(data string)
ProcessString feeds already-decoded input through the buffer (used by ProcessTerminal after incremental UTF-8 decoding).
type TUI ¶
type TUI interface {
Component
Mode() TuiMode
Terminal() Terminal
FullRedraws() int
AddChild(component Component)
RemoveChild(component Component)
Clear()
GetShowHardwareCursor() bool
SetShowHardwareCursor(enabled bool)
GetClearOnShrink() bool
SetClearOnShrink(enabled bool)
SetFocus(component Component)
ShowOverlay(component Component, options *OverlayOptions) OverlayHandle
HideOverlay()
HasOverlay() bool
Start()
Stop(options *TuiStopOptions)
RenderNow(force bool)
RequestRender(force bool)
AddInputListener(listener TuiInputListener) func()
RemoveInputListener(listener TuiInputListener)
OnTerminalColorSchemeChange(listener func(scheme TerminalColorScheme)) func()
SetTerminalColorSchemeNotifications(enabled bool)
QueryTerminalColors(timeoutMs int, onLateReply func(TerminalColors)) TerminalColors
}
TUI is the main interface for managing terminal UI with differential rendering.
type Terminal ¶
type Terminal interface {
// Start the terminal with input and resize handlers
Start(onInput func(data string), onResize func())
// Stop the terminal and restore state
Stop()
// DrainInput drains stdin before exiting to prevent Kitty key release
// events from leaking to the parent shell over slow SSH connections.
// maxMs: maximum time to drain (default 1000ms); idleMs: exit early if no
// input arrives within this time (default 50ms).
DrainInput(maxMs int, idleMs int)
// Write output to terminal
Write(data string)
// Terminal dimensions
Columns() int
Rows() int
// Whether Kitty keyboard protocol is active
KittyProtocolActive() bool
// Cursor positioning (relative to current position)
MoveBy(lines int) // Move cursor up (negative) or down (positive) by N lines
// Cursor visibility
HideCursor() // Hide the cursor
ShowCursor() // Show the cursor
// Clear operations
ClearLine() // Clear current line
ClearFromCursor() // Clear from cursor to end of screen
ClearScreen() // Clear entire screen and move cursor to (0,0)
// Title operations
SetTitle(title string) // Set terminal window title
// Progress indicator (OSC 9;4)
SetProgress(active bool)
// Report what the program is doing (OSC 7501). Sent only to terminals
// that support it; the latest status is re-sent when support is confirmed
// or the terminal restarts (pi: setProgramStatus, S17 503c60552).
SetProgramStatus(status ProgramStatus)
}
Terminal is the minimal terminal interface for the TUI.
type TerminalCapabilities ¶
type TerminalCapabilities struct {
Images any // pi: boolean | "kitty" | "iterm2"; nil until detected (Herdr → "kitty"; other families deferred to Phase 8)
TrueColor bool
Hyperlinks bool
}
TerminalCapabilities describes detected terminal features.
func GetCapabilities ¶
func GetCapabilities() TerminalCapabilities
GetCapabilities returns the cached terminal capabilities. TrueColor is auto-detected from the environment (detectTrueColorCapability) with the PI_TRUE_COLOR override on top, and Hyperlinks from detectHyperlinksCapability with PI_HYPERLINKS; what a caller forces via SetCapabilityOverrides (user settings' `terminal.*`) wins over both (pi: getCapabilities spreads capabilityOverrides over detectCapabilities). Images detection is currently limited to the Herdr branch (detectImagesCapability); the other image families remain deferred to Phase 8, so Images stays nil there unless overridden.
type TerminalCapabilityOverrides ¶
TerminalCapabilityOverrides carries user-forced capability overrides (pi: Partial<TerminalCapabilities> in setCapabilityOverrides; nil fields leave auto-detection in force). Images mirrors pi's boolean | "kitty" | "iterm2" | null union flattened for Go: nil = no override, false = force off (pi images:null), true/"kitty"/"iterm2" = force on.
type TerminalColorMode ¶ added in v1.0.0
type TerminalColorMode = string
TerminalColorMode is the ANSI color encoding mode (pi: TerminalColorMode = "256color" | "truecolor").
const ( ColorMode256color TerminalColorMode = "256color" ColorModeTruecolorN TerminalColorMode = "truecolor" )
type TerminalColorScheme ¶
type TerminalColorScheme = string
TerminalColorScheme is the terminal's color-scheme preference (pi: TerminalColorScheme = "dark" | "light").
const ( TerminalColorSchemeDark TerminalColorScheme = "dark" TerminalColorSchemeLight TerminalColorScheme = "light" )
func ParseTerminalColorSchemeReport ¶
func ParseTerminalColorSchemeReport(data string) (TerminalColorScheme, bool)
ParseTerminalColorSchemeReport parses a color-scheme report (CSI ? 997 ; 1 n dark / CSI ? 997 ; 2 n light). Returns ok=false when absent.
type TerminalColors ¶ added in v1.0.0
type TerminalColors struct {
// Foreground is the default foreground (OSC 10); nil = not reported.
Foreground *RgbColor
// Background is the default background (OSC 11); nil = not reported.
Background *RgbColor
// Palette is ANSI colors 0-15 (OSC 4); nil = not all reported.
Palette []RgbColor
}
TerminalColors holds the colors the terminal reports for its current theme (pi: TerminalColors). Palette is only set when the terminal reported all 16 entries.
type Text ¶
type Text struct {
// contains filtered or unexported fields
}
Text is the text component (pi: class Text implements Component).
func NewText ¶
NewText mirrors pi's constructor defaults (text "", paddingX 1, paddingY 1); customBgFn is optional (pi: customBgFn? → variadic).
func (*Text) Invalidate ¶
func (t *Text) Invalidate()
func (*Text) SetCustomBgFn ¶
type TextAttributes ¶ added in v1.0.0
type TextAttributes struct {
Bold bool
Dim bool
Italic bool
Underline bool
Inverse bool
Strikethrough bool
}
TextAttributes carries the text attributes styleTextWithAnsi applies (pi: TextAttributes).
type TextChunk ¶
TextChunk represents a chunk of text for word-wrap layout. Tracks both the text content and its position in the original line.
func WordWrapLine ¶
func WordWrapLine(line string, maxWidth int, preSegmented []SegmentData) []TextChunk
WordWrapLine splits a line into word-wrapped chunks. Wraps at word boundaries when possible, falling back to character-level wrapping for words longer than the available width.
line - The text line to wrap maxWidth - Maximum visible width per chunk preSegmented - Optional pre-segmented graphemes (e.g. with paste-marker awareness). When nil the default grapheme segmenter is used.
Returns chunks with text and position information (byte offsets).
type TextStyle ¶ added in v1.0.0
type TextStyle struct {
TextAttributes
Fg *Color
Bg *Color
}
TextStyle is TextAttributes plus foreground/background colors (pi: TextStyle).
type TriggerCharactersProvider ¶
type TriggerCharactersProvider interface {
// TriggerCharacters returns the characters that should naturally trigger
// this provider at token boundaries.
TriggerCharacters() []string
}
TriggerCharactersProvider is the optional capability exposing the natural trigger characters (pi: optional triggerCharacters member → capability interface, repo rule).
type TriggerCharactersSetter ¶
type TriggerCharactersSetter interface {
SetTriggerCharacters(chars []string)
}
TriggerCharactersSetter is the writable half of the trigger-character capability (pig: pi assigns provider.triggerCharacters directly).
type TruncatedText ¶
type TruncatedText struct {
// contains filtered or unexported fields
}
TruncatedText is the single-line truncating text component (pi: class TruncatedText implements Component).
func NewTruncatedText ¶
func NewTruncatedText(text string, paddingX int, paddingY int) *TruncatedText
NewTruncatedText mirrors pi's constructor defaults (paddingX 0, paddingY 0).
func (*TruncatedText) Invalidate ¶
func (t *TruncatedText) Invalidate()
func (*TruncatedText) Render ¶
func (t *TruncatedText) Render(width int) []string
type TuiAltScreen ¶
type TuiAltScreen struct {
TuiBase
// contains filtered or unexported fields
}
TuiAltScreen is the alternate-screen renderer (pi: TuiAltScreen extends TuiBase implements ViewportTUI).
func NewTuiAltScreen ¶
func NewTuiAltScreen(terminal Terminal, showHardwareCursor *bool, logDirectory string, options *TuiAltScreenOptions) *TuiAltScreen
NewTuiAltScreen creates a TuiAltScreen (pi constructor; showHardwareCursor nil = env default, logDirectory "" = env or ~/.pi/agent, options nil = defaults).
func (*TuiAltScreen) CopyActiveSelectionToClipboard ¶
func (t *TuiAltScreen) CopyActiveSelectionToClipboard() bool
CopyActiveSelectionToClipboard copies the active selection, if any (pi: copyActiveSelectionToClipboard). Reports success.
func (*TuiAltScreen) Flash ¶
func (t *TuiAltScreen) Flash(message string, durationMs int)
Flash shows a transient message in the alternate-screen flash stack (pi: flash). durationMs <= 0 uses the default duration.
func (*TuiAltScreen) GetCopyOnSelect ¶
func (t *TuiAltScreen) GetCopyOnSelect() bool
GetCopyOnSelect reports whether selection copies on release (pi: getCopyOnSelect).
func (*TuiAltScreen) HasActiveSelection ¶
func (t *TuiAltScreen) HasActiveSelection() bool
HasActiveSelection reports whether a non-empty text selection exists (pi: hasActiveSelection).
func (*TuiAltScreen) IsFollowingOutput ¶
func (t *TuiAltScreen) IsFollowingOutput() bool
IsFollowingOutput reports whether the primary scroll view tracks the end (pi: isFollowingOutput getter).
func (*TuiAltScreen) Render ¶
func (t *TuiAltScreen) Render(width int) []string
Render implements Component (pi: render override).
func (*TuiAltScreen) ResetTextSelection ¶ added in v1.1.0
func (t *TuiAltScreen) ResetTextSelection()
ResetTextSelection drops the text selection and multi-click history, e.g. before the host replaces the transcript (pi: resetTextSelection).
func (*TuiAltScreen) ScrollBy ¶
func (t *TuiAltScreen) ScrollBy(lines int)
ScrollBy scrolls the primary scroll view by lines (pi: scrollBy).
func (*TuiAltScreen) ScrollToBottom ¶
func (t *TuiAltScreen) ScrollToBottom()
ScrollToEnd scrolls to the end (pi: scrollToBottom).
func (*TuiAltScreen) ScrollToEndIndicatorRect ¶ added in v1.0.0
func (t *TuiAltScreen) ScrollToEndIndicatorRect() *altScrollToEndIndicatorRect
ScrollToEndIndicatorRect returns a copy of the last rendered jump-to-end indicator rect, or nil when the indicator is not currently composited (pig test seam: compositeScrollToEndIndicator resets the field to nil at frame start and re-assigns it mid-render, so an unsynchronized external read both races with the render goroutine and can observe the transient nil).
func (*TuiAltScreen) ScrollToTop ¶
func (t *TuiAltScreen) ScrollToTop()
ScrollToTop scrolls to the start (pi: scrollToTop).
func (*TuiAltScreen) SetCopyOnSelect ¶
func (t *TuiAltScreen) SetCopyOnSelect(enabled bool)
SetCopyOnSelect toggles copy-on-select (pi: setCopyOnSelect).
func (*TuiAltScreen) SetLayoutRoot ¶
func (t *TuiAltScreen) SetLayoutRoot(component Component)
SetLayoutRoot replaces the layout root component (pi: setLayoutRoot).
func (*TuiAltScreen) SetWheelScrollLines ¶ added in v1.0.0
func (t *TuiAltScreen) SetWheelScrollLines(lines int)
SetWheelScrollLines updates the lines-per-wheel setting and resets the acceleration gesture state (pi: setWheelScrollLines).
func (*TuiAltScreen) ViewportTop ¶
func (t *TuiAltScreen) ViewportTop() int
ViewportTop returns the primary scroll view's offset (pi: viewportTop getter).
type TuiAltScreenOptions ¶
type TuiAltScreenOptions struct {
// WheelScrollLines is the number of logical lines moved for each
// mouse-wheel event. WheelScrollLinesAuto (0) accelerates fast wheel
// spins on terminals that send one event per notch (pi:
// WheelScrollLines = number | "auto", v0.99.1 #9758).
WheelScrollLines int
// Mouse captures mouse events for viewport scrolling and
// application-owned text selection.
Mouse *bool
// SearchMatchStyle styles a non-current transcript search match.
SearchMatchStyle func(text string) string
// SearchCurrentMatchStyle styles the current transcript search match.
SearchCurrentMatchStyle func(text string) string
// button (v0.85.1). Nil = identity.
SearchNavigationButtonStyle func(text string, hovered bool) string
// ScrollToEndIndicator renders a clickable jump-to-end label. It is
// centered on the last row of a follow-end primary scroll view while
// that view is scrolled away from its end (v0.85.1).
ScrollToEndIndicator func() string
// OpenUrl opens an OSC 8 hyperlink activated with a primary-button click.
OpenUrl func(url string)
// OnRightClickPaste handles an unmodified secondary-button press for
// clipboard paste. Currently enabled on Windows only.
OnRightClickPaste func()
// CopyOnSelect automatically copies selected text to the clipboard on
// mouse release (default: true) (v0.85.1).
CopyOnSelect *bool
// CopySelection copies selected text to the system clipboard. Return Ok
// on success, a FailureMessage string to display on failure, or a bare
// false for a generic error. When nil, the selection is copied via an
// OSC 52 write. (pi v0.86.0: Promise<boolean | string> → sync callback.)
CopySelection func(text string) CopySelectionResult
}
TuiAltScreenOptions configures the alternate-screen TUI (pi: TuiAltScreenOptions).
type TuiBase ¶
type TuiBase struct {
Container
// OnDebug is the global callback for debug key (Shift+Ctrl+D). Called
// before input is forwarded to the focused component.
OnDebug func()
// contains filtered or unexported fields
}
TuiBase is the shared TUI machinery; concrete renderers subclass it (pi: abstract class TuiBase).
func (*TuiBase) AddInputListener ¶
func (b *TuiBase) AddInputListener(listener TuiInputListener) func()
AddInputListener registers an input interceptor; returns the unsubscribe fn.
func (*TuiBase) FullRedraws ¶
func (*TuiBase) GetClearOnShrink ¶
func (*TuiBase) GetFocusedComponent ¶
func (*TuiBase) GetShowHardwareCursor ¶
func (*TuiBase) HasOverlay ¶
HasOverlay checks if there are any visible overlays.
func (*TuiBase) HasOverlayEntries ¶
HasOverlayEntries reports whether any overlay entries exist (visible or not).
func (*TuiBase) HideOverlay ¶
func (b *TuiBase) HideOverlay()
HideOverlay hides the topmost overlay and restores previous focus.
func (*TuiBase) Invalidate ¶
func (b *TuiBase) Invalidate()
Invalidate overrides Container.Invalidate to also invalidate overlays. Uses the reentrant b.lock: it is invoked both externally and from within the dispatch (e.g. beforeTerminalStart under Start's lock).
func (*TuiBase) OnTerminalColorSchemeChange ¶
func (b *TuiBase) OnTerminalColorSchemeChange(listener func(scheme TerminalColorScheme)) func()
func (*TuiBase) QueryTerminalColors ¶ added in v1.0.0
func (b *TuiBase) QueryTerminalColors(timeoutMs int, onLateReply func(TerminalColors)) TerminalColors
QueryTerminalColors queries the terminal's theme colors: the default foreground (OSC 10), the default background (OSC 11), and ANSI colors 0-15 (OSC 4), followed by a DA1 request that marks the end of the replies (pi: queryTerminalColors). Blocks until the DA1 reply or all color replies arrive, or when timeoutMs elapses. Colors the terminal did not report are nil; the palette is only set when all 16 arrived. A reply arriving after the timeout (e.g. over slow links) is delivered through onLateReply.
Dispatch-safe (pig addition, same rationale as the v0.87.1 blocking queries): when called from inside input dispatch (b.mu held by the dispatching goroutine), it still returns after timeoutMs — the timeout settle path uses its own query mutex and CAS and never takes b.mu. The late-reply callback runs on the input-dispatch goroutine.
func (*TuiBase) RemoveInputListener ¶
func (b *TuiBase) RemoveInputListener(listener TuiInputListener)
RemoveInputListener unregisters a previously added listener.
func (*TuiBase) RequestRender ¶
RequestRender schedules a render (throttled), or renders immediately when force is set.
func (*TuiBase) RunExclusive ¶
func (b *TuiBase) RunExclusive(fn func())
lock runs fn under the TUI mutex. When the calling goroutine already holds the mutex (inside a dispatch), fn runs inline — reproducing JS event-loop reentrancy. Re-entrancy is detected by goroutine ID (goid.go): a plain in-dispatch flag cannot distinguish same-goroutine re-entry from a concurrent call on another goroutine (e.g. the editor autocomplete continuation calling RequestRender while dispatch is in progress), which would run the callback unlocked. The mutex release is panic-safe (pig panic containment): a panicking fn must not brick the renderer mutex — the panic keeps unwinding (the spawn-site RecoverPanic guard logs and contains it), but lock state is restored here. pi's single-threaded event loop has no equivalent failure mode. See docs/feat/PANIC-RESILIENCE.md. RunExclusive runs fn while holding the renderer lock (pig addition: the serializer for cross-goroutine component-tree mutations — pi performs them on the single event loop; pig serializes against the render/input pipeline instead). Re-entrant on the calling goroutine via lock.
func (*TuiBase) SetClearOnShrink ¶
SetClearOnShrink sets whether to trigger full re-render when content shrinks. When true, empty rows are cleared when content shrinks. When false (default), empty rows remain (reduces redraws on slower terminals).
func (*TuiBase) SetShowHardwareCursor ¶
func (*TuiBase) SetTerminalColorSchemeNotifications ¶
func (*TuiBase) ShowOverlay ¶
func (b *TuiBase) ShowOverlay(component Component, options *OverlayOptions) OverlayHandle
ShowOverlay shows an overlay component with configurable positioning and sizing. Returns a handle to control the overlay's visibility.
func (*TuiBase) Stop ¶
func (b *TuiBase) Stop(options *TuiStopOptions)
Stop ends the terminal session and restores terminal state.
type TuiInputListener ¶
type TuiInputListener func(data string) *TuiInputListenerResult
TuiInputListener intercepts input before it reaches the focused component.
type TuiInputListenerResult ¶
type TuiInputListenerResult struct {
Consume bool
// Data replaces the input being forwarded. Nil = leave unchanged.
Data *string
}
TuiInputListenerResult is the result of an input listener (pi: { consume?: boolean; data?: string } | undefined). Nil means undefined.
type TuiMainScreen ¶
type TuiMainScreen struct {
TuiBase
// contains filtered or unexported fields
}
TuiMainScreen renders into the terminal's main screen and scrollback.
func NewTuiMainScreen ¶
func NewTuiMainScreen(terminal Terminal, showHardwareCursor *bool, logDirectory string) *TuiMainScreen
NewTuiMainScreen creates a TuiMainScreen. showHardwareCursor (nil = false, v0.85.1 removed the env default) and logDirectory ("" = debug logging disabled, crash log falls back to os.TempDir) mirror the pi constructor's optional parameters.
func (*TuiMainScreen) CaptureRenderState ¶
func (m *TuiMainScreen) CaptureRenderState() TuiMainScreenRenderState
CaptureRenderState snapshots the renderer state.
Locking note: the embedded TuiBase's mutex guards BOTH the base and the renderer state (m.mu resolves to the promoted TuiBase.mu). doRender always runs under b.lock() (scheduler/renderNow/stop guarantee this), so it must NOT re-lock; only externally-called state accessors lock here.
func (*TuiMainScreen) RestoreRenderState ¶
func (m *TuiMainScreen) RestoreRenderState(state TuiMainScreenRenderState)
RestoreRenderState restores a snapshot taken by CaptureRenderState.
type TuiMainScreenRenderState ¶
type TuiMainScreenRenderState struct {
PreviousLines []string
PreviousWidth int
PreviousHeight int
CursorRow int
HardwareCursorRow int
MaxLinesRendered int
PreviousViewportTop int
}
TuiMainScreenRenderState is a snapshot of the differential renderer state (used by session replacement / suspend-resume flows).
type TuiMouseButton ¶
type TuiMouseButton = string
TuiMouseButton is the normalized mouse button (pi: TuiMouseButton).
const ( MouseButtonLeft TuiMouseButton = "left" MouseButtonMiddle TuiMouseButton = "middle" MouseButtonRight TuiMouseButton = "right" MouseButtonNone TuiMouseButton = "none" )
type TuiMouseDispatchTarget ¶
type TuiMouseDispatchTarget struct {
Component Component
OriginX int
OriginY int
Width int
Height int
}
TuiMouseDispatchTarget is internal target metadata used by containers and alternate-screen dispatch (pi: TuiMouseDispatchTarget).
type TuiMouseEvent ¶
type TuiMouseEvent struct {
Type TuiMouseEventType
Button TuiMouseButton
// Coordinates local to the receiving component.
X int
Y int
// Absolute terminal coordinates.
ScreenX int
ScreenY int
// Current component bounds.
Width int
Height int
Shift bool
Alt bool
Ctrl bool
// Logical lines. Negative values scroll up. (pi: wheelDelta?)
WheelDelta *int
// Consecutive click count when type is click. (pi: clickCount?)
ClickCount *int
}
TuiMouseEvent is a normalized cell-based mouse event. Coordinates are zero-based (pi: TuiMouseEvent).
func RetargetMouseEvent ¶
func RetargetMouseEvent(event *TuiMouseEvent, target *TuiMouseDispatchTarget) *TuiMouseEvent
RetargetMouseEvent recreates local coordinates for a previously dispatched mouse target (pi: retargetMouseEvent).
type TuiMouseEventResult ¶
type TuiMouseEventResult struct {
// Handled stops propagation and suppresses renderer-level fallback
// behavior. (pi: handled?)
Handled bool
// Capture routes subsequent drag/release events to this component.
// Implies handled. (pi: capture?)
Capture bool
// Focus gives keyboard focus to this component. Implies handled.
// (pi: focus?)
Focus bool
// Render explicitly requests or suppresses a render. Move and release
// default to false; press, click, drag, and wheel default to true.
// Nil = unset (pi: render? → *bool).
Render *bool
// HasTarget mirrors pi's `"target" in result` discrimination.
HasTarget bool
// Target is the exact dispatch target retained for later
// retargeting (pi: TuiMouseDispatchResult.target).
Target *TuiMouseDispatchTarget
// FocusTarget is the keyboard focus target, which may be a delegating
// parent container (pi: TuiMouseDispatchResult.focusTarget?).
FocusTarget Component
}
TuiMouseEventResult is the result returned by a component's mouse handler (pi: TuiMouseEventResult). The dispatch-result members (HasTarget/Target/ FocusTarget) are only set by DispatchMouseEvent; handlers themselves return the plain result and DispatchMouseEvent folds it into a dispatch result.
func DispatchMouseEvent ¶
func DispatchMouseEvent(component Component, event *TuiMouseEvent) *TuiMouseEventResult
DispatchMouseEvent dispatches an event to a component and retains the exact target and coordinate transform. Containers use this when forwarding events to nested children (pi: dispatchMouseEvent).
type TuiMouseEventType ¶
type TuiMouseEventType = string
TuiMouseEventType is the normalized mouse event kind (pi: TuiMouseEventType).
const ( MouseEventTypePress TuiMouseEventType = "press" MouseEventTypeRelease TuiMouseEventType = "release" MouseEventTypeMove TuiMouseEventType = "move" MouseEventTypeDrag TuiMouseEventType = "drag" MouseEventTypeClick TuiMouseEventType = "click" MouseEventTypeWheel TuiMouseEventType = "wheel" )
type TuiStopOptions ¶
type TuiStopOptions struct {
// PreserveScreen leaves renderer output in place for another TUI taking
// over the same terminal.
PreserveScreen bool
}
TuiStopOptions configure TUI stop behavior.
type UndoStack ¶
type UndoStack[S any] struct { // contains filtered or unexported fields }
UndoStack is a generic undo stack with clone-on-push semantics.
Stores deep clones of state snapshots. Popped snapshots are returned directly (no re-cloning) since they are already detached.
func NewUndoStack ¶
NewUndoStack creates an undo stack that deep-clones snapshots with the given function on push.
type VStack ¶
type VStack struct {
Stack
}
VStack lays out children vertically (pi: class VStack extends Stack).
func NewVStack ¶
func NewVStack(children []StackChild, options *StackOptions) *VStack
NewVStack mirrors pi's constructor; options may be nil.
type ViewportTUI ¶
type ViewportTUI interface {
// contains filtered or unexported methods
}
ViewportTUI marks TUI implementations with a scrollable, application-owned viewport (pi: VIEWPORT_TUI symbol + ViewportTUI interface). TuiAltScreen implements it.
type VirtualTerminal ¶
type VirtualTerminal struct {
// contains filtered or unexported fields
}
VirtualTerminal is the in-memory terminal used by render tests.
func NewVirtualTerminal ¶
func NewVirtualTerminal(columns, rows int) *VirtualTerminal
NewVirtualTerminal creates a virtual terminal with the given dimensions.
func (*VirtualTerminal) ClearFromCursor ¶
func (v *VirtualTerminal) ClearFromCursor()
func (*VirtualTerminal) ClearLine ¶
func (v *VirtualTerminal) ClearLine()
func (*VirtualTerminal) ClearScreen ¶
func (v *VirtualTerminal) ClearScreen()
func (*VirtualTerminal) ClearWrites ¶
func (v *VirtualTerminal) ClearWrites()
ClearWrites forgets recorded output (test convenience).
func (*VirtualTerminal) Columns ¶
func (v *VirtualTerminal) Columns() int
func (*VirtualTerminal) DrainInput ¶
func (v *VirtualTerminal) DrainInput(maxMs int, idleMs int)
func (*VirtualTerminal) GetCellBold ¶
func (v *VirtualTerminal) GetCellBold(row, col int) bool
GetCellBold reports the bold attribute of a cell (pi: cell.isBold).
func (*VirtualTerminal) GetCellItalic ¶
func (v *VirtualTerminal) GetCellItalic(row, col int) bool
GetCellItalic reports the italic attribute of a cell (pi: cell.isItalic()).
func (*VirtualTerminal) GetCellUnderline ¶
func (v *VirtualTerminal) GetCellUnderline(row, col int) bool
GetCellUnderline reports the underline attribute of a cell (pi: cell.isUnderline — consumed by the markdown style-leak tests).
func (*VirtualTerminal) GetCursorPosition ¶
func (v *VirtualTerminal) GetCursorPosition() (x, y int)
GetCursorPosition returns the 0-based cursor position within the viewport.
func (*VirtualTerminal) GetCursorVisible ¶
func (v *VirtualTerminal) GetCursorVisible() bool
GetCursorVisible reports the hardware cursor visibility state.
func (*VirtualTerminal) GetScrollBuffer ¶
func (v *VirtualTerminal) GetScrollBuffer() []string
GetScrollBuffer returns the entire scroll buffer (right-trimmed).
func (*VirtualTerminal) GetViewport ¶
func (v *VirtualTerminal) GetViewport() []string
GetViewport returns the visible viewport (right-trimmed lines, translateToString(true) semantics).
func (*VirtualTerminal) GetWrites ¶
func (v *VirtualTerminal) GetWrites() string
GetWrites returns all raw output written so far, concatenated.
func (*VirtualTerminal) HideCursor ¶
func (v *VirtualTerminal) HideCursor()
func (*VirtualTerminal) KittyProtocolActive ¶
func (v *VirtualTerminal) KittyProtocolActive() bool
func (*VirtualTerminal) MoveBy ¶
func (v *VirtualTerminal) MoveBy(lines int)
func (*VirtualTerminal) Resize ¶
func (v *VirtualTerminal) Resize(columns, rows int)
Resize changes the terminal dimensions and fires the resize handler.
func (*VirtualTerminal) Rows ¶
func (v *VirtualTerminal) Rows() int
func (*VirtualTerminal) SendInput ¶
func (v *VirtualTerminal) SendInput(data string)
SendInput simulates keyboard input.
func (*VirtualTerminal) SetProgramStatus ¶ added in v1.1.0
func (v *VirtualTerminal) SetProgramStatus(status ProgramStatus)
func (*VirtualTerminal) SetProgress ¶
func (v *VirtualTerminal) SetProgress(active bool)
func (*VirtualTerminal) SetTitle ¶
func (v *VirtualTerminal) SetTitle(title string)
func (*VirtualTerminal) ShowCursor ¶
func (v *VirtualTerminal) ShowCursor()
func (*VirtualTerminal) Start ¶
func (v *VirtualTerminal) Start(onInput func(data string), onResize func())
func (*VirtualTerminal) Stop ¶
func (v *VirtualTerminal) Stop()
func (*VirtualTerminal) WaitForRender ¶
func (v *VirtualTerminal) WaitForRender()
WaitForRender waits for the TUI's throttled render pipeline to settle (pi: nextTick + 20ms + flush; the Go pipeline needs a real 16ms-throttle window plus goroutine scheduling margin).
func (*VirtualTerminal) Write ¶
func (v *VirtualTerminal) Write(data string)
type WheelScrollAccelerator ¶ added in v1.0.0
type WheelScrollAccelerator struct {
// contains filtered or unexported fields
}
WheelScrollAccelerator converts wheel events into line counts (pi: WheelScrollAccelerator).
In `"auto"` mode on terminals that do not accelerate wheel input, the count follows event velocity: an isolated notch moves one line, while a fast spin moves up to six lines per event. For example, notches 100 ms apart move 1 line each, 50 ms apart move 2, and 20 ms apart move 5.
func NewWheelScrollAccelerator ¶ added in v1.0.0
func NewWheelScrollAccelerator(lines int) *WheelScrollAccelerator
NewWheelScrollAccelerator builds the accelerator. lines == 0 ("auto") accelerates unless the terminal accelerates wheel input itself.
func NewWheelScrollAcceleratorWithAcceleration ¶ added in v1.0.0
func NewWheelScrollAcceleratorWithAcceleration(lines int, accelerate bool) *WheelScrollAccelerator
NewWheelScrollAcceleratorWithAcceleration is the constructor with the acceleration override (pi's constructor second parameter; used by tests).
func (*WheelScrollAccelerator) Next ¶ added in v1.0.0
func (a *WheelScrollAccelerator) Next(direction int, now float64) int
Next returns the positive line count for a wheel event in `direction` at time `now` (milliseconds) (pi: next).
func (*WheelScrollAccelerator) SetLines ¶ added in v1.0.0
func (a *WheelScrollAccelerator) SetLines(lines int)
SetLines updates the lines setting and resets the gesture state (pi: setLines).
type WordNavigationOptions ¶
type WordNavigationOptions struct {
// (pi: custom segmenter returning word segments.)
Segment func(text string) []SegmentData
// single units (e.g. paste markers).
IsAtomicSegment func(segment string) bool
}
WordNavigationOptions are options for word navigation functions. When nil, uses the default word segmentation.
type WordSegmenter ¶
WordSegmenter mirrors Intl.Segmenter (granularity: "word"). Known gap vs ICU: no CJK dictionary breaking (UAX #29 word rules only, CJK breaks per character); see README §4 Phase 6 for the enhancement plan.
func GetWordSegmenter ¶
func GetWordSegmenter() WordSegmenter
GetWordSegmenter returns the shared word segmenter instance.
Source Files
¶
- alt_screen_flash.go
- alt_screen_search.go
- autocomplete.go
- box.go
- cancellable_loader.go
- cjk_segmenter.go
- cjk_segmenter_sst.go
- colors.go
- doc.go
- editor.go
- editor_component.go
- fuzzy.go
- goid.go
- h_stack.go
- input.go
- keybindings.go
- keys.go
- kill_ring.go
- latex.go
- layout.go
- layout_node.go
- loader.go
- markdown.go
- marked.go
- marked_rules.go
- marked_tokenizer.go
- mouse_region.go
- native_modifiers.go
- native_platform.go
- oklab.go
- program_status.go
- scroll_view.go
- select_list.go
- settings_list.go
- spacer.go
- stack.go
- stdin_buffer.go
- tables_generated.go
- terminal.go
- terminal_colors.go
- terminal_image.go
- terminal_unix.go
- text.go
- truncated_text.go
- tui.go
- tui_alt_screen.go
- tui_main_screen.go
- undo_stack.go
- utils.go
- v_stack.go
- virtual_terminal.go
- wheel_scroll.go
- word_navigation.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Ported from pi node_modules/grok-mermaid/src/ansi.ts (grok-mermaid v0.2.2, Apache-2.0) as part of T5b-4.
|
Ported from pi node_modules/grok-mermaid/src/ansi.ts (grok-mermaid v0.2.2, Apache-2.0) as part of T5b-4. |
|
scripts
|
|
|
generatetables
command
tui/scripts/generatetables — regenerates tui/tables_generated.go.
|
tui/scripts/generatetables — regenerates tui/tables_generated.go. |