Skip to content

vt 实验性 ​

实验性

本包属于实验层:任何 0.x 版本都可能有不兼容变化(docs/release.md「API 稳定性」)。

go
import "github.com/tangoui/tango/ui/terminal/vt"

本页由 site/tools/apigen 从源码注释生成(按 darwin 构建标签选文件),请勿手改。

Package vt is the terminal emulator core of ui/terminal: it turns the bytes a program writes into screen state, and the keys and text the user types into the bytes the program reads. Of the ui packages it only uses ui/input, for key events, and it can be tested on its own.

Terminal is the emulator: it feeds output through a Parser and applies the result to a Screen, tracking the cursor, the modes, the title and which rows changed since the view last drew them.

Parser implements the DEC ANSI parser state machine described by Paul Williams (vt100.net/emu/dec_ansi_parser), extended with UTF-8 decoding, ':' sub-parameters and BEL-terminated OSC strings. Runs of printable ASCII bypass the state machine and reach Handler.PrintASCII in one call.

Screen holds the cell grid: the active rows plus a bounded scrollback, kept in one ring buffer of Line values so scrolling never copies cells. Each Cell stores a code point, a width and a 16-bit index into the screen's StyleTable. Width gives a character's cell width using xterm.js's rules and tables generated from the Unicode data files.

EncodeKey, EncodeText and EncodePaste encode keyboard input the way xterm.js does (legacy xterm sequences, bracketed paste).

Experimental: this package's API may change in any 0.x release (see docs/release.md, "API 稳定性").

常量 ​

go
const (
	ColorKindDefault = 0
	ColorIndexed     = 1
	ColorRGB         = 2
)

Color kinds, as returned by Color.Kind.

go
const DefaultScrollback = 10000

DefaultScrollback is the scrollback length used when Options.Scrollback is 0.

变量 ​

go
var BlankCell = Cell{Width: 1}

BlankCell is an empty cell in the default style. Note that the zero Cell is not blank; see Cell.

函数 ​

func EncodeKey ​

go
func EncodeKey(ev input.KeyEvent, m Modes) (b []byte, ok bool)

EncodeKey returns the bytes a key press sends to the program; ok=false means the terminal does not handle the key and the caller may treat it as an application shortcut or ignore it.

Only presses (Down, including Repeat) are encoded. Printable characters arrive as committed text (see EncodeText); EncodeKey handles letters, digits, punctuation and Space only when Ctrl or Alt is held.

The encoding is xterm's legacy one: Enter "\r", Backspace "\x7f" (Ctrl+Backspace "\x08"), Tab "\t", Shift+Tab "\x1b[Z", Esc "\x1b", cursor keys "\x1b[A".."\x1b[D" ("\x1bOA".."\x1bOD" when Modes.AppCursor is set), Home/End, Insert/Delete/PageUp/PageDown, F1–F12, Ctrl+letter 0x01–0x1A, Ctrl+[ \ ] ^ _ and Ctrl+Space. Keys with a modifier parameter send "\x1b[1;{m}A" or "\x1b[3;{m}~" when a modifier is held, with m = 1 + Shift 1 + Alt 2 + Ctrl 4 + Meta 8, and ignore AppCursor then. On other keys except Tab (as in xterm.js) Alt sends ESC followed by the key's encoding: Alt+x "\x1bx", Alt+Shift+x "\x1bX", and Alt+Shift with a digit or punctuation key ESC followed by the symbol it gives on the US layout (Alt+Shift+. "\x1b>", readline's M->). Meta (Command, Super) is not encoded: such a key returns ok=false. Whether Option on macOS counts as Alt is the caller's choice: it clears input.ModAlt to let Option compose characters instead.

Each call returns a new slice.

func EncodePaste ​

go
func EncodePaste(s string, m Modes) []byte

EncodePaste returns the bytes pasting s sends to the program. Any bracketed-paste markers ("\x1b[200~", "\x1b[201~") in s are removed, including ones that removing another marker would form, so pasted text cannot end bracketed paste early; "\r\n" and "\n" become "\r". When Modes.BracketedPaste is set the result is wrapped in the markers. Other control characters are kept.

func EncodeText ​

go
func EncodeText(s string) []byte

EncodeText returns the bytes committed text sends to the program: s as UTF-8, unchanged. Alt is handled by EncodeKey.

func FillBlank ​

go
func FillBlank(cells []Cell)

FillBlank sets every cell of cells to BlankCell.

func Width ​

go
func Width(r rune) int

Width reports how many cells r occupies: 0 for combining marks, format and other zero-width characters, 2 for East Asian wide and full-width characters and for emoji with emoji presentation, and 1 otherwise. The rules match xterm.js's unicode11 addon; the tables come from the Unicode version in width_table.go.

C0 and C1 controls report 0; the screen never stores them. Values outside the Unicode range report 1.

类型 ​

Attr ​

go
type Attr uint16

Attr is a set of character attributes.

go
const (
	AttrBold Attr = 1 << iota
	AttrFaint
	AttrItalic
	AttrUnderline
	AttrBlink
	AttrInverse
	AttrInvisible
	AttrStrike
)

Character attributes.

Cell ​

go
type Cell struct {
	Rune  rune   // 0 is a blank (drawn as a space)
	Style uint16 // index into the screen's StyleTable
	Width uint8  // 1 or 2; 0 for the right half of a wide character
}

Cell is one character cell.

The zero Cell is NOT a blank: Cell{} (Width 0) is the right half of a wide character. A blank cell is BlankCell, Cell{Width: 1}; pad and erase with it (or with Cell{Style: s, Width: 1} for a styled blank).

A wide character takes two cells: the left one holds the character with Width 2, the right one has Rune 0 and Width 0. For a grapheme with combining marks, Rune is the base character.

Color ​

go
type Color uint32

Color is a foreground or background color. The high 8 bits hold the kind (ColorKindDefault, ColorIndexed or ColorRGB); an indexed color keeps its palette index in the low 8 bits and an RGB color its 0xRRGGBB value in the low 24 bits. The zero Color is the default.

go
const ColorDefault Color = 0

ColorDefault is the terminal's default foreground or background.

func IndexedColor ​

go
func IndexedColor(n uint8) Color

IndexedColor returns palette color n (0–15 the ANSI colors, 16–255 the xterm 256-color cube and grays).

func RGBColor ​

go
func RGBColor(r, g, b uint8) Color

RGBColor returns a direct 24-bit color.

func (Color) Index ​

go
func (c Color) Index() uint8

Index returns an indexed color's palette index.

func (Color) Kind ​

go
func (c Color) Kind() int

Kind returns the color's kind.

func (Color) RGB ​

go
func (c Color) RGB() (r, g, b uint8)

RGB returns an RGB color's components.

CursorStyle ​

go
type CursorStyle uint8

CursorStyle is the cursor appearance requested by DECSCUSR.

go
const (
	CursorDefault         CursorStyle = iota // use the view's preference
	CursorBlinkBlock                         // blinking block
	CursorSteadyBlock                        // steady block
	CursorBlinkUnderline                     // blinking underline
	CursorSteadyUnderline                    // steady underline
	CursorBlinkBar                           // blinking vertical bar
	CursorSteadyBar                          // steady vertical bar
)

Handler ​

go
type Handler interface {
	// Print receives one printable code point that is not ASCII, or
	// U+FFFD for each byte of invalid UTF-8.
	Print(r rune)
	// PrintASCII receives a run of printable ASCII (0x20–0x7E). A run may
	// be split across several calls.
	PrintASCII(b []byte)
	// Execute receives a C0 control byte. 0x80–0x9F are never C1 controls
	// because input is UTF-8.
	Execute(b byte)
	// CSI receives a control sequence. private is '<', '=', '>', '?' or 0.
	CSI(p *Params, inter []byte, final byte, private byte)
	// ESC receives an escape sequence.
	ESC(inter []byte, final byte)
	// OSC receives an operating system command without its BEL or ST
	// terminator. Strings longer than 1 MB are dropped.
	OSC(data []byte)
	// DCS receives a device control string once its ST arrives. A private
	// marker ('<'–'?') is the first byte of inter. Payloads longer than
	// 1 MB are dropped.
	DCS(p *Params, inter []byte, final byte, data []byte)
}

Handler receives the actions decoded by a Parser. Slices passed to a method are only valid during the call.

Line ​

go
type Line struct {
	Cells   []Cell
	Wrapped bool // the line continues on the next row (soft wrap)
	Dirty   bool // changed since the flag was last cleared
	// contains filtered or unexported fields
}

Line is one row of cells.

func (*Line) Combining ​

go
func (l *Line) Combining(x int) []rune

Combining returns the combining marks drawn on the character in column x, in the order they arrived, or nil if there are none. The slice is valid until the line next changes.

Match ​

go
type Match struct {
	Line     int
	From, To int
}

Match is a search hit. Line is the absolute line position (0 the oldest scrollback line, ScrollbackLen the first active row); [From, To) are the cell columns it spans, widened to whole wide characters.

Modes ​

go
type Modes struct {
	AppCursor      bool // DECCKM (?1): cursor keys send application sequences
	BracketedPaste bool // ?2004: wrap pasted text in ESC [200~ … ESC [201~
	ShowCursor     bool // DECTCEM (?25): the cursor is visible
	AutoWrap       bool // DECAWM (?7): printing past the last column wraps
}

Modes are the terminal modes a view or input encoder needs to know.

Options ​

go
type Options struct {
	Cols, Rows int // size in cells; raised to at least 1
	// Scrollback is the number of lines kept after they scroll off the
	// top. 0 means the default, 10 000; a negative value keeps none.
	Scrollback int
	// Reply receives the bytes the terminal sends back to the program,
	// such as cursor position and device attribute reports. It is called
	// during Write and may be nil. b is only valid during the call.
	Reply func(b []byte)
}

Options configures a Terminal.

Params ​

go
type Params struct {
	// contains filtered or unexported fields
}

Params holds the parameters of a CSI or DCS sequence: up to 32 parameters separated by ';', each with up to 8 values separated by ':'. Extra parameters and values are ignored.

func (*Params) Get ​

go
func (p *Params) Get(i, def int) int

Get returns the main value of parameter i, or def if it is missing or 0.

func (*Params) Len ​

go
func (p *Params) Len() int

Len returns the number of parameters.

func (*Params) Sub ​

go
func (p *Params) Sub(i int) []int

Sub returns the main value of parameter i followed by its ':' sub-parameters, or nil if i is out of range. Missing values are 0.

Parser ​

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

Parser decodes a byte stream into Handler calls. It is not safe for concurrent use.

func NewParser ​

go
func NewParser(h Handler) *Parser

NewParser returns a Parser in the ground state that reports to h.

func (*Parser) Write ​

go
func (p *Parser) Write(b []byte)

Write parses b. Input may be split across calls at any byte.

Screen ​

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

Screen is a grid of rows lines plus up to scrollback lines that have scrolled off its top. Lines live in a ring buffer, so scrolling moves an index instead of copying, and a line evicted from a full scrollback is reused, cells and all, as the new bottom row.

The active area is rows 0 to rows-1, read with Screen.Line. The viewport is what a view shows: rows lines ending ViewOffset lines above the bottom of the active area, read with Screen.ViewLine.

A Screen is not safe for concurrent use.

func NewScreen ​

go
func NewScreen(cols, rows, scrollback int) *Screen

NewScreen returns a blank screen of cols×rows cells keeping up to scrollback lines of history. A screen with scrollback 0, such as the alternate screen, drops lines that scroll off the top. cols and rows are raised to at least 1 and scrollback to at least 0.

func (*Screen) BufferLine ​

go
func (s *Screen) BufferLine(i int) *Line

BufferLine returns row i counted from the oldest retained scrollback row, or nil outside the buffer. Like Line, its pointer lasts until the next scroll.

func (*Screen) ClearScrollback ​

go
func (s *Screen) ClearScrollback()

ClearScrollback drops every scrollback line and returns the viewport to the bottom.

func (*Screen) Evicted ​

go
func (s *Screen) Evicted() uint64

Evicted returns how many lines have been removed from the top of the screen's history (the oldest scrollback line, or row 0 of a screen without scrollback) since the screen was made: lines a full scrollback dropped, lines ClearScrollback dropped and lines a resize pushed out of the scrollback. It never decreases. Evicted plus a line's position (0 the oldest scrollback line, ScrollbackLen the first active row) is therefore a number that stays with the line while it is kept, which a view uses to keep a selection on its text.

func (*Screen) Line ​

go
func (s *Screen) Line(y int) *Line

Line returns active row y, 0 ≤ y < rows. It panics if y is out of range. The pointer is valid until the next scroll, which moves lines between rows.

func (*Screen) ScrollDown ​

go
func (s *Screen) ScrollDown(top, bottom int)

ScrollDown scrolls active rows top through bottom (inclusive) down one line and blanks row top. Nothing enters or leaves the scrollback. Out of range or empty regions are ignored.

func (*Screen) ScrollUp ​

go
func (s *Screen) ScrollUp(top, bottom int)

ScrollUp scrolls active rows top through bottom (inclusive) up one line and blanks row bottom. If top is 0 and the screen keeps scrollback, the line scrolled off goes into the scrollback (evicting the oldest line when it is full) and a viewport scrolled up keeps showing the same content; otherwise it is discarded. Rows outside the region do not move. Out-of-range or empty regions are ignored.

func (*Screen) ScrollbackLen ​

go
func (s *Screen) ScrollbackLen() int

ScrollbackLen returns the number of lines in the scrollback.

func (*Screen) Search ​

go
func (s *Screen) Search(query string, caseSensitive bool) []Match

Search returns every occurrence of query in the scrollback and the active area, oldest line first and left to right within a line. Matching is case-insensitive unless caseSensitive. An empty query returns nil. Soft-wrapped lines are searched individually; a query does not match across a wrap. The caller must hold the screen's lock.

func (*Screen) SetViewOffset ​

go
func (s *Screen) SetViewOffset(n int)

SetViewOffset scrolls the viewport n lines up from the bottom, clamped to [0, ScrollbackLen].

func (*Screen) Size ​

go
func (s *Screen) Size() (cols, rows int)

Size returns the screen's size in cells.

func (*Screen) Styles ​

go
func (s *Screen) Styles() *StyleTable

Styles returns the table that cells' Style fields index.

func (*Screen) ViewLine ​

go
func (s *Screen) ViewLine(y int) *Line

ViewLine returns row y of the viewport, 0 ≤ y < rows. It panics if y is out of range. As with Screen.Line, the pointer is valid until the next scroll.

func (*Screen) ViewOffset ​

go
func (s *Screen) ViewOffset() int

ViewOffset returns how many lines the viewport is scrolled up from the bottom; 0 means it shows the active area.

Snapshot ​

go
type Snapshot struct {
	Version          uint64
	Cols, Height     int
	ViewOffsetN      int
	EvictedN         uint64
	Scrollback       int
	CursorX, CursorY int
	CursorVisible    bool
	CursorStyle      CursorStyle
	Title            string
	StyleGeneration  uint64
	StylesData       []Style
	Rows             []SnapshotRow
	// contains filtered or unexported fields
}

Snapshot is an immutable copy of the terminal state needed by a view. Its slices are owned by the snapshot and remain valid until Release.

func (*Snapshot) Evicted ​

go
func (s *Snapshot) Evicted() uint64

func (*Snapshot) Release ​

go
func (s *Snapshot) Release()

Release is retained for callers that own a snapshot value. Snapshot data is immutable and the terminal keeps the latest version for reuse; old values are reclaimed normally when no caller references them.

func (*Snapshot) ScrollbackLen ​

go
func (s *Snapshot) ScrollbackLen() int

func (*Snapshot) Size ​

go
func (s *Snapshot) Size() (cols, rows int)

Size returns the copied viewport dimensions.

func (*Snapshot) Styles ​

go
func (s *Snapshot) Styles() *StyleTable

func (*Snapshot) ViewLine ​

go
func (s *Snapshot) ViewLine(y int) *Line

func (*Snapshot) ViewOffset ​

go
func (s *Snapshot) ViewOffset() int

SnapshotCombining ​

go
type SnapshotCombining struct {
	Column int
	Runes  []rune
}

SnapshotCombining stores combining marks for one cell.

SnapshotRow ​

go
type SnapshotRow struct {
	ID        uint64
	Version   uint64
	Cells     []Cell
	Wrapped   bool
	Combining []SnapshotCombining
	// contains filtered or unexported fields
}

SnapshotRow is a copied viewport row. ID remains stable while the same scrollback line is retained; Version changes when its content changes.

Style ​

go
type Style struct {
	Fg, Bg Color
	Attr   Attr
}

Style is how a cell is drawn. Cells refer to styles by their index in the screen's StyleTable; the zero Style (index 0) is the default.

StyleTable ​

go
type StyleTable struct {
	// contains filtered or unexported fields
}

StyleTable stores each distinct Style once and hands out 16-bit indexes for cells to refer to. Index 0 is always the default style. When the table is full, interning a new style first drops the entries no cell of the owning screen uses, renumbering the cells that remain.

Compacting scans every cell of the screen, so it is rate-limited: after a compaction that freed less than an eighth of the table, the next one waits until an eighth of the table's worth of styles have been refused (interned as 0) or an eighth of the stored lines have been evicted from the scrollback. Until then a new style on a full table is the default.

func (*StyleTable) Compact ​

go
func (t *StyleTable) Compact()

Compact removes the styles no cell of the screen uses and renumbers the remaining ones, updating the cells. The default style stays at index 0.

func (*StyleTable) Get ​

go
func (t *StyleTable) Get(i uint16) Style

Get returns the style at index i. An index the table does not hold returns the default style.

func (*StyleTable) Intern ​

go
func (t *StyleTable) Intern(st Style) uint16

Intern returns st's index, adding it if needed. Adding to a full table compacts it first, which renumbers the screen's cells; indexes obtained earlier and not stored in a cell are then invalid. If every entry is in use, Intern returns 0 (the default style).

func (*StyleTable) Len ​

go
func (t *StyleTable) Len() int

Len returns the number of styles in the table, including the default.

Terminal ​

go
type Terminal struct {
	// contains filtered or unexported fields
}

Terminal is a terminal emulator: it parses the bytes a program writes and keeps the resulting screen, cursor and modes.

A Terminal is not safe for concurrent use; the caller serializes Write with reads of its state.

func New ​

go
func New(o Options) *Terminal

New returns a terminal with a blank screen and the cursor at the top left.

func (*Terminal) Cursor ​

go
func (t *Terminal) Cursor() (x, y int, visible bool)

Cursor returns the cursor's active-area position and whether it is shown (DECTCEM). After the last column is written x stays on it until the next character wraps.

func (*Terminal) EchoCursor ​

go
func (t *Terminal) EchoCursor() (x, y int, ok bool)

EchoCursor returns a position suitable for considering local echo. It requires plain text parser state, the normal screen at its live end and a visible cursor without a pending wrap. Callers still need to confirm echo.

func (*Terminal) Modes ​

go
func (t *Terminal) Modes() Modes

Modes returns the current modes.

func (*Terminal) Resize ​

go
func (t *Terminal) Resize(cols, rows int)

Resize changes the terminal to cols×rows cells (each at least 1). Lines are truncated or padded, not reflowed. Losing rows keeps the cursor's line on screen by moving lines into the scrollback; gaining rows brings them back while the cursor is on the last row. The cursor and the saved cursor are clamped to the new size; as in xterm.js, a pending wrap counts as a cursor just past the last column, so gaining columns moves the cursor there and otherwise the wrap is cancelled.

func (*Terminal) Screen ​

go
func (t *Terminal) Screen() *Screen

Screen returns the terminal's screen. The pointer stays valid for the terminal's lifetime.

func (*Terminal) Snapshot ​

go
func (t *Terminal) Snapshot() Snapshot

Snapshot returns a read-only copy of the current terminal state. The caller serializes it with Terminal.Write, Resize and other state reads.

func (*Terminal) TakeDirty ​

go
func (t *Terminal) TakeDirty() (rows []int, all bool)

TakeDirty returns the viewport rows that changed since the last call, in ascending order, and clears the record. all is true, and rows nil, when the whole viewport must be redrawn: after a resize, ED 2, RIS, a change of the viewport offset or more scrolling than the viewport has rows. The slice is reused by the next call.

Rows are relative to the viewport after the scroll TakeScroll reports: a view shifts its old image up by TakeScroll() rows, then repaints rows.

func (*Terminal) TakeScroll ​

go
func (t *Terminal) TakeScroll() int

TakeScroll returns how many lines the viewport content moved up since the last call and clears the count. It is 0 while a full redraw is pending (see TakeDirty), so a view calls it before TakeDirty.

func (*Terminal) Title ​

go
func (t *Terminal) Title() string

Title returns the window title last set with OSC 0 or OSC 2.

func (*Terminal) Write ​

go
func (t *Terminal) Write(b []byte)

Write feeds program output to the terminal. Input may be split across calls at any byte, including inside a UTF-8 sequence.

以 MIT 许可发布