portalis

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2026 License: MIT Imports: 23 Imported by: 0

README

Portalis

A built-in terminal emulator for Go. Runs a shell in a PTY, parses ANSI output, and renders the result through Bubble Tea. Designed to be embedded into a host application that allocates a rectangle and forwards keyboard, mouse and resize events.

Features

  • PTY-backed session via creack/pty
  • Bounded ANSI/VT subset: CSI, OSC, SGR colors (16 / 256 / 24-bit), UTF-8
  • Child processes default to TERM=ansi (8-color terminfo), not xterm-256color; callers can override TERM
  • xterm-compatible key encoding (Ctrl/Alt/Shift/F-keys, application cursor mode)
  • DEC modes: ?1 application cursor, ?6 origin, ?7 autowrap, ?25 cursor visibility, ?1000/1002/1003/1006 mouse, ?1004 focus, ?1047 alternate buffer, ?1048 cursor save/restore, ?1049 alternate buffer with independent cursor/parser save, ?2004 bracketed paste, ?2026 synchronized output
  • Editing sequences: insert mode, tab stops, ICH (CSI @), DCH (CSI P), ECH (CSI X), IL (CSI L), DL (CSI M), SU (CSI S), SD (CSI T), VPA (CSI d), HPA (CSI G)
  • RIS/DECSTR resets, scroll regions, index/reverse index, DEC Special Graphics charset; DECSTR preserves screen text, current cursor position and tab stops
  • OSC 0/2 title tracking and structured OSC 7 locations (Host, Path, Local)
  • System clipboard selection and explicit paste integration (macOS, Wayland, X11)
  • Synchronized output (CSI ? 2026 h/l)
  • Mouse-drag selection, DEC mouse reporting, focus reporting, and host-driven cursor blinking
  • Scrollback capped at 10 000 lines and 1 048 576 cells; alternate screen and bracketed paste
  • Heuristic command capture from the visible prompt line (not shell history), capped at 1 000 entries
  • Interactive key/mouse writes are admitted without waiting for PTY I/O; a shared FIFO writer preserves payload order
  • Render dirty-cache and ordered 4 KiB PTY reads for responsive streaming
  • Embeddable Bubble Tea component: the host owns its model, forwards messages and calls View(w, h) to render

Installation

go get github.com/starframe-dev/portalis

Requires Go 1.26.8 or later. PTY process support currently targets Unix-like systems (Linux and macOS); Windows is not supported.

Quick start

Emulator is an embeddable terminal component, not a tea.Model by itself. A host model forwards Bubble Tea messages, sends the allocated content size as ResizeMsg, and renders with View(width, height). Resize errors are reported through SetOnError without stopping the PTY; the screen keeps its last successfully applied size:

package main

import (
    "log"

    tea "github.com/charmbracelet/bubbletea"
    "github.com/starframe-dev/portalis"
)

type model struct {
    term *portalis.Emulator
    w, h int
}

func newModel() *model {
    term := portalis.NewEmulator("session-1", "build", "bash", []string{"-l"})
    term.SetOnError(func(err error) { log.Printf("terminal: %v", err) })
    return &model{term: term}
}

func (m *model) Init() tea.Cmd {
    return m.term.Start()
}

func (m *model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
    switch msg := msg.(type) {
    case tea.WindowSizeMsg:
        m.w, m.h = msg.Width, msg.Height
        return m, m.term.Update(portalis.ResizeMsg{Width: m.w, Height: m.h})
    default:
        return m, m.term.Update(msg)
    }
}

func (m *model) View() string {
    return m.term.View(m.w, m.h)
}

func main() {
    if _, err := tea.NewProgram(
        newModel(),
        tea.WithAltScreen(),
        tea.WithMouseCellMotion(),
        tea.WithReportFocus(),
    ).Run(); err != nil {
        log.Fatal(err)
    }
}

The returned commands produce PtyReadyMsg, PtyOutputMsg, PtyExitMsg, clipboard errors, and other internal messages; route those messages back through Emulator.Update. System clipboard paste is explicit via PasteFromClipboard(); ordinary Ctrl+V is forwarded to the child. The Quick Start enables mouse-cell motion for drag selection and focus messages for child focus reporting. Portalis does not create a cursor timer: a host that wants blinking should broadcast portalis.CursorBlinkMsg{} from one shared timer.

Resource limits and diagnostics

  • A terminal grid is limited to 262 144 cells; scrollback has a separate 1 048 576-cell cap, even if its line-count limit is disabled. Grapheme payloads are capped at 64 bytes per cell (about 96 MiB worst-case across primary, alternate and scrollback buffers, excluding runtime/cell overhead).
  • Clipboard subprocesses time out after 5 seconds. Clipboard text/image bytes are capped at 100 MiB; PNGs are limited to 25 million pixels and 128 MiB of worst-case decoded RGBA64 data. Per-emulator clipboard temp storage defaults to 16 files, 256 MiB total, and a one-hour TTL in a private 0700 directory.
  • Bulk PTY writes are bounded to 100 MiB and 64 queued requests; interactive writes have a separate 64 KiB reserve and fail fast under overload.
  • Setting PORTALIS_RAW_TRACE=<base> writes <base>.<pid> and a .chunks sidecar with mode 0600. Each trace defaults to 16 MiB per file and 3 retained files; PORTALIS_RAW_TRACE_MAX_BYTES and PORTALIS_RAW_TRACE_MAX_FILES can tune those bounded limits. Trace warnings go to SetOnError. Traces include child output and may contain secrets; enable only for diagnostics.

API migration

The API was tightened before v1: mutable Screen and Pty fields are private, Emulator.Pty() was removed, callbacks use setters, and OSC 7 callbacks now receive WorkingDirectory. See MIGRATION.md for before/after examples and the command-history limitation.

Architecture

File Responsibility
emulator.go Top-level controller. Coordinates Screen, Parser and PTY.
screen.go 2D cell grid, scrollback, selection, rendering, dirty cache.
ansi.go ANSI/VT escape parser (CSI, OSC, SGR, UTF-8, DEC modes).
pty.go PTY spawn / ordered reads / write / resize / lifecycle.
clipboard.go System clipboard backends and explicit paste/copy integration.
┌────────────────── Emulator ──────────────────┐
│  Parser  ──▶  Screen  ◀──  PTY (process I/O) │
└──────────────────────────────────────────────┘

Documentation

Project specs live under specs/ and per-file specs under code-specs/:

Testing

go test ./...
go test -race ./...
go vet ./...
staticcheck ./...
govulncheck ./...
go test -run=^$ -fuzz=FuzzParserFeed -fuzztime=5s .

CI also runs Linux PTY lifecycle tests and Linux/ARM64 cross-compilation; manual and v* tag-triggered verification cross-compiles test binaries for Linux/macOS on amd64/arm64. No workflow creates or publishes a release. For visual TUI integration, install cuetty-cli and run go test -tags cuetty -run '^TestANSIStressCueTTY$' .; it regenerates the ignored cuetty-artifacts/ansi-stress/ outputs. See specs/ansi-stress-cue-tty.md. The live Pi test requires an authenticated Pi installation and is intentionally not part of CI. clipboard_mac_test.go live tests are macOS-only and skipped by default; they replace the system clipboard, so run them only explicitly with PORTALIS_RUN_CLIPBOARD_INTEGRATION=1. Other unit tests are portable.

License

MIT (see project root).

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultShell

func DefaultShell() (string, []string)

DefaultShell returns a usable login shell, preferring absolute paths so it works even when the parent PTY provides a minimal or empty PATH.

func SendBytes

func SendBytes(p *Pty, data []byte) tea.Cmd

SendBytes sends raw bytes to the PTY.

Types

type Cell

type Cell struct {
	Rune         rune
	Combining    string
	FG           lipgloss.Color
	BG           lipgloss.Color
	Style        StyleBits
	Continuation bool
}

Cell is a single character cell on the terminal screen.

func (Cell) Empty

func (c Cell) Empty() bool

Empty returns true if the cell has no visible content.

type ClipboardErrorMsg

type ClipboardErrorMsg struct {
	Err error
}

ClipboardErrorMsg reports a system clipboard failure without terminating PTY.

type ClipboardTempPolicy

type ClipboardTempPolicy struct {
	MaxFiles int
	MaxBytes int64
	TTL      time.Duration
}

ClipboardTempPolicy bounds clipboard image files created for one Emulator.

func DefaultClipboardTempPolicy

func DefaultClipboardTempPolicy() ClipboardTempPolicy

DefaultClipboardTempPolicy returns the default per-emulator clipboard limits.

type Cursor

type Cursor struct {
	Row   int
	Col   int
	FG    lipgloss.Color
	BG    lipgloss.Color
	Style StyleBits
}

Cursor represents the terminal cursor position.

type CursorBlinkMsg

type CursorBlinkMsg struct{}

CursorBlinkMsg is sent by the host to toggle the cursor blink state. A single host-level timer should broadcast this message to all visible terminal emulators so their cursors blink in sync.

type Emulator

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

Emulator is a built-in terminal emulator. It runs a shell/command in a PTY and renders the output. It is independent of any UI framework; hosts feed it keyboard/mouse/resize messages and call View(width, height) to render it.

func NewEmulator

func NewEmulator(sessionID, chatName, command string, args []string) *Emulator

func (*Emulator) Blur

func (e *Emulator) Blur() tea.Cmd

Blur marks the emulator as blurred and returns a command that reports blur to the child when DECSET ?1004 is active.

func (*Emulator) CWD

func (e *Emulator) CWD() string

CWD returns the directory path without authority metadata. Use CurrentWorkingDirectory to distinguish local and remote locations.

func (*Emulator) ChatName

func (e *Emulator) ChatName() string

ChatName returns the immutable display name supplied at construction.

func (*Emulator) Close

func (e *Emulator) Close() error

Close closes the PTY and removes this Emulator's private clipboard files.

func (*Emulator) CommandHistorySnapshot

func (e *Emulator) CommandHistorySnapshot() []string

CommandHistorySnapshot returns a copy of the command list. New captures are heuristically scraped from the visible prompt line, not read from shell history.

func (*Emulator) CurrentWorkingDirectory

func (e *Emulator) CurrentWorkingDirectory() (WorkingDirectory, bool)

CurrentWorkingDirectory returns the last OSC 7 location, falling back to the configured initial directory. The boolean is false when neither is known.

func (*Emulator) Focus

func (e *Emulator) Focus() tea.Cmd

Focus marks the emulator as focused and returns a command that reports focus to the child when DECSET ?1004 is active.

func (*Emulator) Listen

func (e *Emulator) Listen() tea.Cmd

Listen returns a command that waits for the next PTY output. At most one returned command may be waiting for a given Emulator.

func (*Emulator) PasteFromClipboard

func (e *Emulator) PasteFromClipboard() tea.Cmd

PasteFromClipboard asynchronously reads the system clipboard and writes its text (or an image temp-file path) to the current PTY.

func (*Emulator) PtyState

func (e *Emulator) PtyState() PtyState

PtyState returns an immutable snapshot of the attached PTY.

func (*Emulator) SessionID

func (e *Emulator) SessionID() string

SessionID returns the immutable session identifier supplied at construction.

func (*Emulator) SetClipboardTempPolicy

func (e *Emulator) SetClipboardTempPolicy(policy ClipboardTempPolicy) error

PasteFromClipboard asynchronously reads the system clipboard and writes its text (or an image temp-file path) to the current PTY.

func (*Emulator) SetCommandHistory

func (e *Emulator) SetCommandHistory(history []string)

SetCommandHistory restores a previously saved heuristic command list, keeping only the newest maxCommandHistory entries.

func (*Emulator) SetInitialCWD

func (e *Emulator) SetInitialCWD(dir string)

SetInitialCWD sets the directory in which the PTY process starts.

func (*Emulator) SetOnCWDChange

func (e *Emulator) SetOnCWDChange(fn func(WorkingDirectory))

SetOnCWDChange registers a callback for validated OSC 7 directory changes.

func (*Emulator) SetOnCommandHistoryChanged

func (e *Emulator) SetOnCommandHistoryChanged(fn func([]string))

SetOnCommandHistoryChanged registers a callback for heuristic command captures.

func (*Emulator) SetOnError

func (e *Emulator) SetOnError(fn func(error))

SetOnError registers a callback for PTY, clipboard, and terminal errors.

func (*Emulator) SetOnExit

func (e *Emulator) SetOnExit(fn func(PtyExitMsg))

SetOnExit registers a callback for a child exit accepted by Update. It runs exactly once when ProcessExited is true; intentional Stop and Close suppress it. Hosts must keep the Listen command chain alive and route messages to Update.

func (*Emulator) SetOnTitleChange

func (e *Emulator) SetOnTitleChange(fn func(string))

SetOnTitleChange registers a callback for validated OSC 0/2 terminal titles.

func (*Emulator) SetScrollbackLimit

func (e *Emulator) SetScrollbackLimit(limit int)

SetScrollbackLimit sets the maximum number of scrollback lines. Non-positive values disable the line-count limit; the Screen cell-count cap remains active. Call before Start or update the existing screen immediately after Start.

func (*Emulator) SetStartEnv

func (e *Emulator) SetStartEnv(env []string)

SetStartEnv records extra environment variables to use when the PTY is spawned without explicit env vars (Start, StartWithEnv(nil), StartSync(nil)). Must be called before the process starts; later calls have no effect on an already running PTY.

func (*Emulator) Start

func (e *Emulator) Start() tea.Cmd

Start begins spawning the PTY process. Returns PtyReadyMsg when done.

func (*Emulator) StartEnv

func (e *Emulator) StartEnv() []string

StartEnv returns the env vars recorded via SetStartEnv (nil when unset).

func (*Emulator) StartSync

func (e *Emulator) StartSync(extraEnv []string) error

StartSync spawns the PTY process synchronously with extra environment variables. Unlike StartWithEnv, it does not return a tea.Cmd — the PTY is ready immediately. It returns an error if spawning or initial resizing fails; a resize failure leaves the spawned PTY attached with its last successfully applied size.

func (*Emulator) StartWithEnv

func (e *Emulator) StartWithEnv(extraEnv []string) tea.Cmd

StartWithEnv begins spawning the PTY process with extra environment variables. A non-fatal initial resize failure is reported in PtyReadyMsg.ResizeErr.

func (*Emulator) Stop

func (e *Emulator) Stop() error

Stop terminates the session, removes clipboard files, and shows the idle view.

func (*Emulator) Title

func (e *Emulator) Title() string

Title returns the last validated terminal title reported through OSC 0/2.

func (*Emulator) Update

func (e *Emulator) Update(msg tea.Msg) tea.Cmd

Update handles messages.

func (*Emulator) View

func (e *Emulator) View(width, height int) string

View renders the terminal screen at the given panel size. The screen size is kept in sync by ResizeMsg from the warp layout engine; during a drag the panel is filled by warp's padContent and the real resize happens on release.

type Parser

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

Parser parses ANSI escape sequences and updates a Screen. It is not safe for concurrent use; callbacks run synchronously during Feed and must not re-enter the parser.

func NewParser

func NewParser(screen *Screen) *Parser

NewParser creates a new ANSI parser for the given screen.

func (*Parser) Feed

func (p *Parser) Feed(data []byte)

Feed feeds data into the parser.

func (*Parser) Reset

func (p *Parser) Reset()

Reset restores power-on screen and parser state at the current dimensions.

func (*Parser) SetCWDCallback

func (p *Parser) SetCWDCallback(fn func(WorkingDirectory))

SetCWDCallback sets a callback invoked synchronously by Feed for OSC 7 changes. The callback must return promptly and must not re-enter the parser.

func (*Parser) SetResponseCallback

func (p *Parser) SetResponseCallback(fn func([]byte))

SetResponseCallback receives terminal-generated replies synchronously during Feed, such as DSR/DA. The callback must not block or re-enter the parser; Emulator queues replies and writes them after releasing its state mutex.

func (*Parser) SetTitleCallback

func (p *Parser) SetTitleCallback(fn func(string))

SetTitleCallback receives OSC 0/2 titles synchronously during Feed.

type Pty

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

Pty wraps a pseudoterminal. Methods are safe for concurrent use; consume output through Listen and call it at most once per active output chain.

func Spawn

func Spawn(command string, args []string, env ...string) (*Pty, error)

Spawn starts a new PTY with the given command, arguments and optional environment variables.

func SpawnInDir

func SpawnInDir(command string, args []string, dir string, env ...string) (*Pty, error)

SpawnInDir starts a new PTY in the given working directory.

func (*Pty) Close

func (p *Pty) Close() error

Close closes the PTY and kills the process.

func (*Pty) Listen

func (p *Pty) Listen(sessionID string) tea.Cmd

Listen returns a bubbletea command that waits for one ordered PTY read. readLoop already limits reads to 4 KiB; keeping that boundary prevents a 64 KiB Parser.Feed call from blocking the UI update loop. Listen returns a command that emits one PTY output or exit message. Call it serially and keep its returned command chain alive until the PTY exits.

func (*Pty) Resize

func (p *Pty) Resize(rows, cols int) error

func (*Pty) State

func (p *Pty) State() PtyState

Resize resizes the PTY. TIOCSWINSZ sends SIGWINCH to the foreground process group. State returns a snapshot without exposing the process or I/O handles.

func (*Pty) Write

func (p *Pty) Write(data []byte) error

Write sends data to the PTY through its ordered writer queue.

type PtyErrorMsg

type PtyErrorMsg struct {
	Err error
}

PtyErrorMsg reports an error from a standalone PTY helper such as SendBytes.

type PtyExitMsg

type PtyExitMsg struct {
	SessionID     string
	Generation    uint64
	ProcessExited bool
	ExitCode      int
	Signal        os.Signal
	Err           error
}

PtyExitMsg is sent when the PTY process exits.

type PtyOutputMsg

type PtyOutputMsg struct {
	SessionID  string
	Generation uint64
	Data       []byte
}

PtyOutputMsg is sent when new data arrives from the PTY.

type PtyReadyMsg

type PtyReadyMsg struct {
	SessionID      string
	Generation     uint64
	AlreadyRunning bool
	ResizeErr      error
}

PtyReadyMsg is sent when the PTY is ready for listening. ResizeErr is a non-fatal error applying a requested PTY size after the process started.

type PtyState

type PtyState struct {
	Running bool
	PID     int
	Rows    int
	Cols    int
}

PtyState describes the observable lifecycle and size of a PTY.

type PtyWarningMsg

type PtyWarningMsg struct {
	SessionID  string
	Generation uint64
	Err        error
}

PtyWarningMsg reports a nonfatal PTY diagnostic such as trace I/O failure.

type RenderTickMsg

type RenderTickMsg struct{ SessionID string }

RenderTickMsg is kept for compatibility with hosts that may still route queued tick messages from an older emulator instance.

type ResizeMsg

type ResizeMsg struct {
	Width  int
	Height int
}

ResizeMsg is sent by a host when the emulator's allocated rectangle changes. It carries the content size in cells (without borders or padding).

type Screen

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

Screen is a 2D grid of cells. It is not safe for concurrent use; callers that share a Screen must serialize access to its methods.

func NewScreen

func NewScreen(rows, cols int) *Screen

NewScreen creates a screen with the requested dimensions. Non-positive dimensions are normalized to one cell; dimensions beyond the terminal memory budget fall back to the conventional 24x80 size. Scrollback is capped to defaultScrollbackLimit lines by default.

func (*Screen) CellAt

func (s *Screen) CellAt(row, col int) (Cell, bool)

CellAt returns a copy of the cell at the requested position.

func (*Screen) CellsSnapshot

func (s *Screen) CellsSnapshot() [][]Cell

CellsSnapshot returns a deep copy of the visible cell grid.

func (*Screen) Clear

func (s *Screen) Clear()

func (*Screen) ClearLine

func (s *Screen) ClearLine()

ClearLine clears the current line from cursor to end.

func (*Screen) ClearLineAll

func (s *Screen) ClearLineAll()

ClearLineAll clears the entire current line.

func (*Screen) ClearLineLeft

func (s *Screen) ClearLineLeft()

ClearLineLeft clears from start of line to cursor.

func (*Screen) ClearScrollback

func (s *Screen) ClearScrollback()

func (*Screen) ClearSelection

func (s *Screen) ClearSelection()

ClearSelection clears any active selection.

func (*Screen) ClearTabStop

func (s *Screen) ClearTabStop(mode int)

ClearTabStop clears the current stop (mode 0) or all stops (mode 3).

func (*Screen) ClearToCursor

func (s *Screen) ClearToCursor()

func (*Screen) ClearWrapPending

func (s *Screen) ClearWrapPending()

ClearWrapPending resets the wrap-pending flag.

func (*Screen) Cols

func (s *Screen) Cols() int

Cols returns the number of columns in the screen.

func (*Screen) CursorBackward

func (s *Screen) CursorBackward(n int)

CursorBackward moves the cursor left n columns.

func (*Screen) CursorBlinkVisible

func (s *Screen) CursorBlinkVisible() bool

CursorBlinkVisible reports the host-controlled cursor blink phase.

func (*Screen) CursorDown

func (s *Screen) CursorDown(n int)

CursorDown moves the cursor down n rows.

func (*Screen) CursorForward

func (s *Screen) CursorForward(n int)

CursorForward moves the cursor right n columns.

func (*Screen) CursorNextLine

func (s *Screen) CursorNextLine(n int)

CursorNextLine moves the cursor down n rows and to column 0.

func (*Screen) CursorPos

func (s *Screen) CursorPos() (row, col int)

CursorPos returns the current cursor position.

func (*Screen) CursorPrevLine

func (s *Screen) CursorPrevLine(n int)

CursorPrevLine moves the cursor up n rows and to column 0.

func (*Screen) CursorState

func (s *Screen) CursorState() Cursor

CursorState returns a copy of the cursor position and rendition.

func (*Screen) CursorUp

func (s *Screen) CursorUp(n int)

CursorUp moves the cursor up n rows.

func (*Screen) CursorVisible

func (s *Screen) CursorVisible() bool

CursorVisible reports whether the terminal cursor is enabled.

func (*Screen) DeleteChars

func (s *Screen) DeleteChars(n int)

DeleteChars deletes n cells at the cursor and shifts the remainder left.

func (*Screen) DeleteLines

func (s *Screen) DeleteLines(n int)

DeleteLines deletes n lines at the cursor inside the active region.

func (*Screen) EnterAltScreen

func (s *Screen) EnterAltScreen()

EnterAltScreen saves the current screen and clears it.

func (*Screen) EraseChars

func (s *Screen) EraseChars(n int)

EraseChars clears n cells starting at the cursor without shifting text.

func (*Screen) ExitAltScreen

func (s *Screen) ExitAltScreen()

ExitAltScreen restores the saved screen.

func (*Screen) ExtendSelection

func (s *Screen) ExtendSelection(row, col int)

ExtendSelection updates the selection end to the given cell.

func (*Screen) Index

func (s *Screen) Index()

Index moves the cursor down, scrolling the active region at its bottom.

func (*Screen) InsertChars

func (s *Screen) InsertChars(n int)

InsertChars inserts n blank cells at the cursor.

func (*Screen) InsertLines

func (s *Screen) InsertLines(n int)

InsertLines inserts n blank lines at the cursor inside the active region.

func (*Screen) LineText

func (s *Screen) LineText(row int) string

LineText returns the plain text of the given screen row, ignoring trailing empty cells. It is used to capture the current command line before sending Enter to the PTY.

func (*Screen) NextLine

func (s *Screen) NextLine()

NextLine moves to column zero on the next line.

func (*Screen) Put

func (s *Screen) Put(r rune)

Put writes a rune at the cursor position and advances the cursor by its terminal cell width. Wide runes occupy a base cell plus a continuation cell; combining runes extend the previous grapheme without moving the cursor.

func (*Screen) PutBytes

func (s *Screen) PutBytes(data []byte) int

PutBytes bulk-writes printable ASCII bytes to the screen with a single markDirty and without allocating a temporary slice. It mirrors Put's per-byte semantics (wrap at end of row, cursor advance, wrapPending) but does it in one tight pass instead of N function calls.

The caller must guarantee data is all printable ASCII (0x20..0x7e). Returns the number of bytes consumed. Callers that discover a non-printable byte must fall back to Put for that byte.

func (*Screen) Render

func (s *Screen) Render() string

Render returns the screen as a string. If the view is scrolled back, lines are taken from the scrollback buffer; otherwise the live screen is rendered.

func (*Screen) RepeatPrevious

func (s *Screen) RepeatPrevious(n int)

RepeatPrevious repeats the preceding grapheme cluster n times (REP).

func (*Screen) Reset

func (s *Screen) Reset()

Reset restores power-on screen state at the current dimensions.

func (*Screen) ResetView

func (s *Screen) ResetView()

ResetView resets the view offset so the live screen is shown.

func (*Screen) Resize

func (s *Screen) Resize(rows, cols int)

Resize resizes the screen when dimensions are valid. Invalid dimensions leave the screen unchanged; use ResizeChecked to retrieve the validation error.

func (*Screen) ResizeChecked

func (s *Screen) ResizeChecked(rows, cols int) error

ResizeChecked resizes the screen or returns an error before changing it.

func (*Screen) RestoreCursor

func (s *Screen) RestoreCursor()

RestoreCursor restores the saved cursor position.

func (*Screen) ReverseIndex

func (s *Screen) ReverseIndex()

ReverseIndex moves the cursor up, scrolling the active region down at its top.

func (*Screen) Rows

func (s *Screen) Rows() int

Rows returns the number of rows in the screen.

func (*Screen) SaveCursor

func (s *Screen) SaveCursor()

SaveCursor saves the current cursor position.

func (*Screen) ScrollBottom

func (s *Screen) ScrollBottom() int

ScrollBottom returns the bottom of the scroll region (0-indexed).

func (*Screen) ScrollRegionDown

func (s *Screen) ScrollRegionDown(n int)

ScrollRegionDown scrolls the active region down by n lines.

func (*Screen) ScrollRegionUp

func (s *Screen) ScrollRegionUp(n int)

ScrollRegionUp scrolls the active region up by n lines.

func (*Screen) ScrollTop

func (s *Screen) ScrollTop() int

ScrollTop returns the top of the scroll region (0-indexed).

func (*Screen) ScrollUp

func (s *Screen) ScrollUp()

ScrollUp scrolls the active region up by one line.

func (*Screen) ScrollViewDown

func (s *Screen) ScrollViewDown(n int)

ScrollViewDown moves the view down towards the live screen by n lines.

func (*Screen) ScrollViewUp

func (s *Screen) ScrollViewUp(n int)

ScrollViewUp moves the view up into the scrollback by n lines.

func (*Screen) SelectionText

func (s *Screen) SelectionText() []string

SelectionText returns the selected text. It returns nil when the selection exceeds clipboard resource limits; trailing whitespace is trimmed.

func (*Screen) SetAutoWrap

func (s *Screen) SetAutoWrap(active bool)

func (*Screen) SetCursor

func (s *Screen) SetCursor(row, col int)

SetCursor sets the cursor position (1-indexed in ANSI, 0-indexed here).

func (*Screen) SetCursorAddress

func (s *Screen) SetCursorAddress(row, col int)

SetCursorAddress applies CUP/HVP/VPA coordinates. In DECOM origin mode the row is relative to the active scrolling region.

func (*Screen) SetCursorBlinkVisible

func (s *Screen) SetCursorBlinkVisible(visible bool)

SetCursorBlinkVisible updates the host-controlled cursor blink phase.

func (*Screen) SetInsertMode

func (s *Screen) SetInsertMode(active bool)

SetInsertMode controls whether printable writes shift existing cells.

func (*Screen) SetOriginMode

func (s *Screen) SetOriginMode(active bool)

func (*Screen) SetScrollRegion

func (s *Screen) SetScrollRegion(top, bottom int)

SetScrollRegion sets the scrolling region (DECSTBM). top and bottom are 1-indexed (as sent by ANSI).

func (*Screen) SetScrollbackLimit

func (s *Screen) SetScrollbackLimit(limit int)

SetScrollbackLimit sets the maximum number of retained lines. A value of zero or less disables this line-count limit; the cell-count safety cap still applies.

func (*Screen) SetSync

func (s *Screen) SetSync(active bool)

SetSync enables or disables synchronized output (ESC[?2026h/l). While synchronized output is active, Render() returns the last committed frame so intermediate redraw states are not visible.

func (*Screen) SetTabStop

func (s *Screen) SetTabStop()

SetTabStop adds a tab stop at the current cursor column.

func (*Screen) SoftReset

func (s *Screen) SoftReset()

SoftReset restores terminal modes and cursor rendition without clearing text.

func (*Screen) StartSelection

func (s *Screen) StartSelection(row, col int)

StartSelection begins a selection at the given cell.

func (*Screen) TabBackward

func (s *Screen) TabBackward(count int)

TabBackward moves to the previous configured tab stop, or the first column.

func (*Screen) TabForward

func (s *Screen) TabForward(count int)

TabForward moves to the next configured tab stop, or the last column.

func (*Screen) ViewOffset

func (s *Screen) ViewOffset() int

ViewOffset returns how many lines the view is scrolled back.

type StyleBits

type StyleBits uint8

StyleBits holds text style attributes.

const (
	StyleBold StyleBits = 1 << iota
	StyleDim
	StyleItalic
	StyleUnderline
	StyleBlink
	StyleReverse
	StyleHidden
	StyleStrikethrough
)

type WorkingDirectory

type WorkingDirectory struct {
	Host  string
	Path  string
	Local bool
}

WorkingDirectory is a validated OSC 7 location. Host is preserved for remote file URLs; Local reports whether Path belongs to this machine.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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