vt 实验性
实验性
本包属于实验层:任何 0.x 版本都可能有不兼容变化(docs/release.md「API 稳定性」)。
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 稳定性").
常量
const (
ColorKindDefault = 0
ColorIndexed = 1
ColorRGB = 2
)Color kinds, as returned by Color.Kind.
const DefaultScrollback = 10000DefaultScrollback is the scrollback length used when Options.Scrollback is 0.
变量
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
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
func EncodePaste(s string, m Modes) []byteEncodePaste 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
func EncodeText(s string) []byteEncodeText returns the bytes committed text sends to the program: s as UTF-8, unchanged. Alt is handled by EncodeKey.
func FillBlank
func FillBlank(cells []Cell)FillBlank sets every cell of cells to BlankCell.
func Width
func Width(r rune) intWidth 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
type Attr uint16Attr is a set of character attributes.
const (
AttrBold Attr = 1 << iota
AttrFaint
AttrItalic
AttrUnderline
AttrBlink
AttrInverse
AttrInvisible
AttrStrike
)Character attributes.
Cell
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
type Color uint32Color 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.
const ColorDefault Color = 0ColorDefault is the terminal's default foreground or background.
func IndexedColor
func IndexedColor(n uint8) ColorIndexedColor returns palette color n (0–15 the ANSI colors, 16–255 the xterm 256-color cube and grays).
func RGBColor
func RGBColor(r, g, b uint8) ColorRGBColor returns a direct 24-bit color.
func (Color) Index
func (c Color) Index() uint8Index returns an indexed color's palette index.
func (Color) Kind
func (c Color) Kind() intKind returns the color's kind.
func (Color) RGB
func (c Color) RGB() (r, g, b uint8)RGB returns an RGB color's components.
CursorStyle
type CursorStyle uint8CursorStyle is the cursor appearance requested by DECSCUSR.
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
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
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
func (l *Line) Combining(x int) []runeCombining 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
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
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
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
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
func (p *Params) Get(i, def int) intGet returns the main value of parameter i, or def if it is missing or 0.
func (*Params) Len
func (p *Params) Len() intLen returns the number of parameters.
func (*Params) Sub
func (p *Params) Sub(i int) []intSub 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
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
func NewParser(h Handler) *ParserNewParser returns a Parser in the ground state that reports to h.
func (*Parser) Write
func (p *Parser) Write(b []byte)Write parses b. Input may be split across calls at any byte.
Screen
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
func NewScreen(cols, rows, scrollback int) *ScreenNewScreen 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
func (s *Screen) BufferLine(i int) *LineBufferLine 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
func (s *Screen) ClearScrollback()ClearScrollback drops every scrollback line and returns the viewport to the bottom.
func (*Screen) Evicted
func (s *Screen) Evicted() uint64Evicted 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
func (s *Screen) Line(y int) *LineLine 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
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
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
func (s *Screen) ScrollbackLen() intScrollbackLen returns the number of lines in the scrollback.
func (*Screen) Search
func (s *Screen) Search(query string, caseSensitive bool) []MatchSearch 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
func (s *Screen) SetViewOffset(n int)SetViewOffset scrolls the viewport n lines up from the bottom, clamped to [0, ScrollbackLen].
func (*Screen) Size
func (s *Screen) Size() (cols, rows int)Size returns the screen's size in cells.
func (*Screen) Styles
func (s *Screen) Styles() *StyleTableStyles returns the table that cells' Style fields index.
func (*Screen) ViewLine
func (s *Screen) ViewLine(y int) *LineViewLine 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
func (s *Screen) ViewOffset() intViewOffset returns how many lines the viewport is scrolled up from the bottom; 0 means it shows the active area.
Snapshot
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
func (s *Snapshot) Evicted() uint64func (*Snapshot) Release
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
func (s *Snapshot) ScrollbackLen() intfunc (*Snapshot) Size
func (s *Snapshot) Size() (cols, rows int)Size returns the copied viewport dimensions.
func (*Snapshot) Styles
func (s *Snapshot) Styles() *StyleTablefunc (*Snapshot) ViewLine
func (s *Snapshot) ViewLine(y int) *Linefunc (*Snapshot) ViewOffset
func (s *Snapshot) ViewOffset() intSnapshotCombining
type SnapshotCombining struct {
Column int
Runes []rune
}SnapshotCombining stores combining marks for one cell.
SnapshotRow
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
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
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
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
func (t *StyleTable) Get(i uint16) StyleGet returns the style at index i. An index the table does not hold returns the default style.
func (*StyleTable) Intern
func (t *StyleTable) Intern(st Style) uint16Intern 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
func (t *StyleTable) Len() intLen returns the number of styles in the table, including the default.
Terminal
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
func New(o Options) *TerminalNew returns a terminal with a blank screen and the cursor at the top left.
func (*Terminal) Cursor
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
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
func (t *Terminal) Modes() ModesModes returns the current modes.
func (*Terminal) Resize
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
func (t *Terminal) Screen() *ScreenScreen returns the terminal's screen. The pointer stays valid for the terminal's lifetime.
func (*Terminal) Snapshot
func (t *Terminal) Snapshot() SnapshotSnapshot 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
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
func (t *Terminal) TakeScroll() intTakeScroll 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
func (t *Terminal) Title() stringTitle returns the window title last set with OSC 0 or OSC 2.
func (*Terminal) Write
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.