phosphor

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: MIT Imports: 10 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

phosphor

A headless VT/xterm terminal emulator for Go. Write a program's output to it, read back what a terminal would show: text, colors, attributes, hyperlinks, cursor, modes, title and scrollback. It answers the queries programs send, tells a renderer which rows changed, reflows on resize, and serializes its whole state as bytes that repaint it on another terminal.

t := phosphor.New(80, 24)
t.Write(output)       // io.Writer
fmt.Println(t.Lines())

It is the emulator inside ptyd, a daemon that keeps thousands of terminals alive, attaches clients to them and checkpoints them to disk, which is why it is small and fast when idle and why its serialization is exact.

Why

  • Small. About 2.5 KB for an idle 80x24 terminal at a shell prompt: a cell is 16 bytes, rows are allocated once drawn on, the alternate screen only while shown, and scrollback is kept serialized under a byte budget (an 80x24 terminal with 2,000 lines of log scrollback holds about 340 KB).
  • Correct. Five external conformance suites run as ordinary Go tests, with no unexplained failures (table below). Every departure from a suite is listed with its reason, and a listed case that starts passing fails the build.
  • Fast. 260-410 MiB/s per core on real program output (vim, less, an agent TUI, logs) and about 1 GiB/s on progress bars, 10-75x the throughput of charmbracelet/x/vt and hinshun/vt10x on the same streams, and redrawing a frame allocates nothing.
  • Round-trips. Repaint output replayed on a fresh terminal gives the same screen, scrollback, cursor and modes, byte for byte under fuzzing, so a client can attach mid-session and a checkpoint can be restored, subject to the limits under Serialization below.

The honest caveats: it does not encode input (keys, mouse, paste are the caller's job; Modes says what the program asked for), it has no graphics (sixel, kitty), no grapheme clustering (widths are per code point, as in xterm), and damage is per row with no scroll hints. If you need a full terminal UI stack, charmbracelet/x/vt integrates with the Charm ecosystem and does more around rendering and input; phosphor is the screen model.

The demo above is examples/mirror, about 150 lines: it runs a program in a PTY, writes its output to phosphor, and draws the screen back from Terminal.Cell alone, redrawing only the rows RowDirty reports. Try it with cd examples && go run ./mirror vim.

Install

go get github.com/2018kguo/phosphor

Go 1.24 or later. The only dependency is go-runewidth.

Use

t := phosphor.New(80, 24,
	phosphor.WithScrollback(5000),     // lines (default 2000)
	phosphor.WithScrollbackBytes(1<<20), // memory budget (default 256 KiB)
	phosphor.WithReply(ptmx),          // answer queries to the program
)

t.Write(buf[:n])                      // as you read the PTY; sequences may be split

for y := range rows {
	for x := range cols {
		c := t.Cell(x, y)             // Rune, Combining, Width, Style, Link
		_ = c.Style.Fg.Kind()         // ColorDefault, ColorIndexed, ColorRGB
		_ = c.Style.Attrs&phosphor.AttrBold != 0
	}
}
t.Lines(); t.Line(y); t.Wrapped(y)    // text, soft wraps
t.ScrollbackLines(); t.ScrollbackLine(i); t.ScrollbackCells(i)
cur := t.Cursor()                     // X, Y, Visible, Shape, Blink, PendingWrap
m := t.Modes()                        // AltScreen, BracketedPaste, Mouse, KittyKeyboard...
t.Title()

t.Resize(120, 40)                     // reflows; also resize the PTY
snapshot := t.Repaint(true)           // replay on a fresh 120x40 terminal to restore

The examples show basic use, a headless runner answering queries, a renderer driven by damage, attaching through Repaint, and Restart.

Queries

Programs ask their terminal things and some wait for the answer: shells and editors send DA1 and the kitty keyboard query at startup, prompts ask for the cursor position, editors ask for the background color. With WithReply(w) the terminal writes the answers to w, usually the PTY master, during Write. Without it queries are ignored, which is right when a real terminal downstream answers them.

Answered: DA1 (CSI ? 62 ; 22 c, a VT220 with ANSI color), DA2, DA3, DSR 5 and 6 (CPR), DECXCPR, DSR ?15, ?26 and ?996 (dark or light, from the background), DECRQM for ANSI and DEC modes, DECRQSS (SGR, DECSTBM, DECSLRM, DECSCUSR, DECSCA, DECSCL), XTVERSION (phosphor), XTGETTCAP (Co, colors), the kitty keyboard flags (CSI ? u), XTWINOPS 18 (text area size), and OSC 4, 10, 11 and 12 color queries from the palette (WithPalette, Palette). Programs can also set and reset those colors (OSC 4, 10, 11, 12, 104, 110-112).

Rendering
for y := range rows {
	if t.RowDirty(y) {
		drawRow(y)
	}
}
t.ClearDirty()

A row is dirty when its cells may have changed since the last ClearDirty: output, scrolling, erasing, switching screens, resizing, or a palette or reverse-video change. Before the first ClearDirty every row is dirty, and until then tracking costs nothing. The cursor is not part of it; compare Cursor() with what you drew. Modes().SyncUpdate is set while a program draws a frame it wants shown at once (mode 2026). Palette().Resolve(color, background) turns a cell color into RGB.

Applications hosting many sessions can call Compact() after output settles. It frees completely zeroed rows, unused Unicode and hyperlink storage, and temporary buffers. Clusters needed by REP and links held by saved cursors remain live; unchanged live tables stay in place. It does so without changing the screen, scrollback, input modes or unfinished parser state. Later output can allocate rows again. It is an explicit idle-time tradeoff; ordinary writes do not run it.

Serialization

Repaint(withScrollback) returns bytes that, written to a terminal of the same size in its initial state (another phosphor.Terminal, or a real one), reproduce this one: scrollback, both screens with their soft wraps, tab stops, saved cursors and modes, margins, the cursor with its pending wrap, pen, character sets and shape, input modes, and the title. It is wrapped in a synchronized update and hides the cursor while painting. An unfinished escape sequence or UTF-8 character is restored after the painting, so later output continues it correctly. Controls which already took effect inside a sequence are not repeated, and a synchronized update in progress stays in progress. The continuation is reconstructed from the parser's bounded state; normal output needs no additional tracking buffer. Colors the program set with OSC 4/10/11/12 are left out, since replaying them would change the receiving terminal's own colors. AppendRepaint reuses a buffer.

The preceding character used by REP (CSI b) is not serialized. Resuming a pending REP after a repaint can therefore differ from uninterrupted output; preserving unfinished parser input does not remove that limit. With origin mode enabled, repaint clamps the live cursor to the scrolling region. A restored cursor or scroll-and-clear (CSI 22 J) can leave it outside that region, so the next printed character can move after repaint.

Restart() is for running a new program in the same terminal: it resets everything as RIS does but keeps the scrollback and the old screen in view above the cursor, as a terminal that relaunches its command does.

Concurrency

A Terminal is not safe for concurrent use. If one goroutine writes output while another reads the screen, hold a lock around both. The reply writer and bell callback run inside Write and must not call back into the Terminal.

What it models

  • Printing: UTF-8 (invalid input becomes U+FFFD; C1 controls sent as UTF-8 act as their ESC forms), wcwidth widths (East Asian ambiguous = 1), wide characters and the blank they leave at a wrap, combining marks, ZWJ and variation selectors kept with the previous character, DEC special graphics in G0-G3 with SI/SO, LS2/LS3, SS2/SS3, REP, insert mode, autowrap with xterm's pending-wrap rules, reverse wraparound (45, 1045).
  • Cursor: CUU/CUD/CUF/CUB, CNL/CPL, CHA/HPA/HPR, VPA/VPR, CUP/HVP, origin mode, DECSC/DECRC, SCOSC/SCORC, 1048, IND/RI/NEL, HT/CHT/CBT with HTS/TBC, DECSCUSR.
  • Editing: ICH/DCH/ECH, IL/DL, SU/SD, ED/EL with the current background (BCE), ED 3, scroll-and-clear (ED 22), DECALN, character protection (DECSCA, SPA/EPA) with DECSED/DECSEL.
  • Regions: DECSTBM, and DECLRMM/DECSLRM left and right margins with every operation they constrain.
  • Screens: alternate screen modes 47, 1047, 1049; scrollback fed from the top of the main screen, stored as logical lines.
  • Modes: DECAWM, IRM, LNM, DECOM, DECTCEM, DECCKM, DECKPAM, DECSCNM, mouse tracking and encodings, focus events, bracketed paste, synchronized update, kitty keyboard flags, XTSAVE/XTRESTORE.
  • SGR: bold, faint, italic, underline styles (single, double, curly, dotted, dashed), blink, inverse, hidden, strikethrough, overline, 16/256/RGB colors in the ; and : forms.
  • OSC: title (0, 2), hyperlinks (8), colors (4, 10, 11, 12, 104, 110-112).
  • Resize: the main screen reflows (narrowing and widening back is exact) and lines come back from the scrollback when it grows.
  • RIS, DECSTR.

What it does not

  • Input encoding (keys, mouse reports, paste): the caller writes those to the PTY, using Modes.
  • Double-width and double-height lines, rectangular area operations (DECCRA, DECERA, DECFRA, DECIC...), 132-column mode (DECCOLM), national character sets, SGR fonts and super/subscript, underline color (SGR 58 is parsed and dropped), mode 12 (cursor blink; DECSCUSR's blink is kept).
  • Grapheme clustering (mode 2027): a ZWJ emoji sequence takes the width of its parts.
  • Sixel and kitty graphics, OSC 52 (clipboard), OSC 7 and 133 (shell integration), icon names, the title stack.
  • 8-bit C1 controls outside UTF-8, and S8C1T replies.
  • The alternate screen is cut or padded on resize, not reflowed (full-screen programs redraw on SIGWINCH).

Conformance

Five external suites run as ordinary Go tests (VT_CONF_REPORT=1 go test -run 'Conformance|Libvterm|Alacritty' -v prints the table).

Suite How Pass Fail Deliberate difference Out of scope
libvterm t/*.test scripts run unchanged by an interpreter, replies included 730 0 28 195
ghostty Terminal.zig, stream_terminal.zig translated cases 459 0 6 84
wezterm term/src/test translated cases 128 0 6 4
esctest2 (xterm) independently written cases (the GPL source is not used) 410 0 12 215
alacritty ref tests recordings and reference grids, per line 1507 / 1557 lines, 37 / 45 tests 0 8 tests

"Deliberate difference" cases are listed with a reason in conformance_known_test.go: places where that emulator departs from xterm (wezterm lets the cursor column equal the width, alacritty ignores SGR 21 and keeps a pending wrap across EL, libvterm brightens bold colors in the pen and answers DA1 as a VT100), places where the upstream harness fakes state, and the few gaps in the list above. "Out of scope" counts cases for features listed as not modeled, mostly input encoding, graphics-adjacent and window operations, palette rendering, rectangular operations and grapheme clustering. Query replies are checked by the libvterm scripts and by TestReplies.

Besides the suites:

  • Fuzzers: FuzzTokens (an alphabet of the sequences programs use, plus resizes, with invariants after every step and an exact Repaint round trip), FuzzRepaintContinuation (prefix, repaint and continued output), FuzzStream (raw bytes and resizes), FuzzChunking (how output is split into writes does not matter), FuzzWrite, FuzzDamage (every row whose cells changed is dirty), FuzzReplies (answering queries never changes the state), and, in the oracle module, FuzzOracle, a differential fuzzer against charmbracelet/x/vt on the subset where it agrees with xterm. CI runs each for 30 seconds. Before the extraction the targets had about 2.3 hours of fuzzing; since, each has run 4-5 minutes on 8 workers (which found one Repaint bug, now a regression input).
  • Recordings of nvim, vim, less, nano and man, cut at 40 points: the invariants, the Repaint round trip and resizes at each.
  • Every byte boundary in those recordings: repaint and continue the next 32 bytes before a later redraw can hide parser corruption. Focused cases also check styles, modes, replies, bells, oversized sequences and every parser state.
  • TestRedrawDoesNotAllocate pins zero allocations per redraw frame, TestDamageDoesNotAllocate the same with damage tracking on, and TestCellDoesNotAllocate reading every cell.

Performance

The October 2026 follow-up comparison measures idle metadata reclamation, parsing, replay and compatibility against libghostty-vt. The first round also compares with phosphor v0.1.0. Cross-engine memory figures include native RSS. The table below records the original v0.1.0 comparison with other Go emulators.

Apple M5 Pro, Go 1.26, one core. oracle/compare_test.go feeds the same streams, in 8 KiB writes as a PTY reader would, to each library at 120x40 (cd oracle && go test -bench Compare -benchmem); n=6, all spreads under 5%.

Stream (~1 MiB unless noted) phosphor charmbracelet/x/vt v0.1.0 hinshun/vt10x
vim session (6 KiB) 350 MiB/s, 0 allocs 23 MiB/s 30 MiB/s
less session (5 KiB) 266 MiB/s, 0 allocs 2 MiB/s 27 MiB/s
agent TUI (synchronized redraws, truecolor) 408 MiB/s 36 MiB/s 43 MiB/s
scrolling logs 404 MiB/s 5 MiB/s 39 MiB/s
progress bars 1.1 GiB/s 27 MiB/s 42 MiB/s
heap per idle 80x24 terminal at a prompt 3.0 KiB 4.5 MiB 66 KiB

Caveats: each library was used as its README suggests, with defaults. charmbracelet/x/vt's idle size is mostly what it allocates up front, and it does more per write (it keeps a renderable cell model for the Charm stack and runs callbacks); vt10x has no scrollback. The streams come from internal/benchdata and testdata, written for ptyd's workloads.

Other costs (go test -bench . -benchmem): Repaint of a 100x30 screen 4.4 us, of a 120x40 screen 9.3 us, with a full scrollback 17 us (one allocation); replaying a full checkpoint 0.46 ms; Lines 12 us. An 80x24 terminal with 2,000 lines of log scrollback holds about 350 KB. Damage tracking and query replies cost nothing until used.

Prior art and credits

The API takes from several emulators: the reply writer from xterm.js's onData and alacritty's PtyWrite event (as an io.Writer, so it wires straight to a PTY), row dirty flags that the renderer clears from ghostty and alacritty, Wrapped from xterm.js's isWrapped, cell values that do not allocate from xterm.js's reusable IBufferCell, the color kinds from libvterm and termwiz, and Repaint from tmux and xterm.js's serialize addon.

The conformance suites come from other projects, used under their licenses; testdata/conformance/NOTICE.md has the sources and revisions:

  • libvterm, MIT, Copyright (c) 2008 Paul Evans: test scripts vendored unchanged.
  • ghostty, MIT, Copyright (c) 2024 Mitchell Hashimoto, Ghostty contributors: unit tests translated.
  • wezterm, MIT, Copyright (c) 2018-Present Wez Furlong: unit tests translated.
  • alacritty, Apache-2.0 or MIT, The Alacritty Project contributors: reference recordings and grids.
  • esctest2, GPL-2.0: not vendored and nothing copied; the cases are written independently from the xterm behavior it checks.

License

MIT. See LICENSE.

Documentation

Overview

Package phosphor is a headless VT/xterm terminal emulator: a screen model you feed a program's output and read back what a terminal would show.

It keeps the main and alternate screens, a bounded scrollback, the cursor, colors and attributes, hyperlinks, the scroll region and margins, tab stops, character sets, the title, and the modes a program switched on, following xterm closely (see the README for the conformance suites it passes). Resize reflows the main screen. Repaint serializes the whole state as bytes that reproduce it on a fresh terminal, for attaching clients and for checkpoints.

It is built to be cheap when there are many terminals: a cell is 16 bytes, rows are allocated only once drawn on, the alternate screen only while in use, scrollback is stored serialized under a byte budget, an idle 80x24 terminal holds about 3 KB, and output that redraws a screen does not allocate.

Use

t := phosphor.New(80, 24)
t.Write(output)          // io.Writer; sequences may be split across writes
t.Lines()                // the screen as text
t.Cell(x, y)             // one cell: Rune, Width, Style, Link
t.Cursor(); t.Modes(); t.Title()
t.Resize(100, 30)
t.Repaint(true)          // bytes that recreate the state, scrollback included

Queries

Programs ask their terminal things (device attributes, the cursor position, mode and color settings) and some wait for the answer. Pass WithReply with the pseudo-terminal's input side and the Terminal answers; without it queries are ignored, which is right when a real terminal attached downstream answers them instead.

Rendering

RowDirty reports which rows changed since the last ClearDirty, so a renderer redraws only those. Tracking starts with the first ClearDirty and costs nothing before.

Concurrency

A Terminal is not safe for concurrent use. Callers that write output in one goroutine and read the screen in another must hold a lock around both.

Not modeled

Double-width and double-height lines, rectangular area operations (DECCRA, DECFRA...), 132-column mode, sixel and kitty graphics, grapheme clustering (mode 2027: widths are per code point, as in xterm), the underline color (SGR 58), OSC 52 clipboard, OSC 7 and 133 (shell integration), and 8-bit C1 controls outside UTF-8. The alternate screen is cut or padded on resize rather than reflowed.

Example
package main

import (
	"fmt"

	"github.com/2018kguo/phosphor"
)

func main() {
	t := phosphor.New(20, 3)
	fmt.Fprint(t, "hello, \x1b[1;31mworld\x1b[m\r\n")
	fmt.Fprint(t, "a line long enough to wrap")

	for _, line := range t.Lines() {
		fmt.Printf("%q\n", line)
	}
	c := t.Cell(7, 0)
	fmt.Println(c.Text(), c.Style.Fg == phosphor.IndexedColor(1), c.Style.Attrs&phosphor.AttrBold != 0)
	cur := t.Cursor()
	fmt.Println("cursor", cur.X, cur.Y, "row 2 wrapped:", t.Wrapped(2))
}
Output:
"hello, world"
"a line long enough t"
"o wrap"
w true true
cursor 6 2 row 2 wrapped: true
Example (Headless)

A headless runner answers the queries a program sends, or the program may wait forever for the reply. Pass the pseudo-terminal's input side to WithReply; here the program's output is simulated and the replies collected.

package main

import (
	"bytes"
	"fmt"
	"io"

	"github.com/2018kguo/phosphor"
)

func main() {
	var toProgram bytes.Buffer // in a real runner: the pty master, e.g. from github.com/creack/pty
	t := phosphor.New(80, 24, phosphor.WithReply(&toProgram))

	// A program checking what it runs in: primary device attributes, the
	// cursor position, the background color, and kitty keyboard support.
	io.WriteString(t, "\x1b[5;10H\x1b[c\x1b[6n\x1b]11;?\x07\x1b[?u")

	fmt.Printf("%q\n", toProgram.String())
}
Output:
"\x1b[?62;22c\x1b[5;10R\x1b]11;rgb:0000/0000/0000\a\x1b[?0u"
Example (Renderer)

A renderer redraws only the rows that changed since its last frame.

package main

import (
	"fmt"
	"io"
	"strings"

	"github.com/2018kguo/phosphor"
)

func main() {
	t := phosphor.New(12, 4)
	pal := t.Palette()
	draw := func() {
		var drawn []string
		_, rows := t.Size()
		for y := range rows {
			if !t.RowDirty(y) {
				continue
			}
			var line strings.Builder
			cols, _ := t.Size()
			for x := range cols {
				c := t.Cell(x, y)
				if c.Width == 0 {
					continue // the right half of a wide character
				}
				_ = pal.Resolve(c.Style.Fg, false) // the color to draw it in
				if c.Rune == 0 {                   // never written, or erased
					line.WriteByte('.')
				} else {
					line.WriteString(c.Text())
				}
			}
			drawn = append(drawn, fmt.Sprintf("%d:%s", y, line.String()))
		}
		t.ClearDirty()
		fmt.Println(strings.Join(drawn, " "))
	}

	io.WriteString(t, "$ ls\r\n")
	draw() // the first frame draws everything
	io.WriteString(t, "a.txt b.go\r\n$ ")
	draw()
	io.WriteString(t, "\x1b[1;3H\x1b[K")
	draw()
}
Output:
0:$ ls........ 1:............ 2:............ 3:............
1:a.txt b.go.. 2:$ ..........
0:$ ..........

Index

Examples

Constants

View Source
const (
	DefaultScrollbackLines = 2000
	DefaultScrollbackBytes = 256 << 10
)

The scrollback budget a Terminal has unless WithScrollback or WithScrollbackBytes set another.

Variables

This section is empty.

Functions

This section is empty.

Types

type Attr

type Attr uint16

Attr is a set of text attributes, combined with |.

const (
	AttrBold          Attr = 1 << iota // SGR 1
	AttrFaint                          // SGR 2
	AttrItalic                         // SGR 3
	AttrBlink                          // SGR 5 or 6
	AttrInverse                        // SGR 7: swap foreground and background
	AttrHidden                         // SGR 8
	AttrStrikethrough                  // SGR 9
	AttrOverline                       // SGR 53
	// AttrProtected marks a character that selective erase (DECSED,
	// DECSEL, and after SPA also ED, EL and ECH) leaves alone. DECSCA and
	// SPA set it.
	AttrProtected
)

The text attributes. All but AttrProtected are set with SGR.

type Cell

type Cell struct {
	// Rune is the character, or 0 for an empty cell and for the right half
	// of a wide character.
	Rune rune
	// Combining holds the combining marks, joiners and variation
	// selectors that follow Rune in the cell, usually "".
	Combining string
	// Width is 1, 2 for a wide character (which also covers the cell to its
	// right), or 0 for the right half of a wide character.
	Width int
	// Style is how the cell is drawn (the right half of a wide character
	// has its left half's style).
	Style Style
	// Link is the hyperlink the cell belongs to, if any.
	Link Hyperlink
}

Cell is the content and style of one screen position, as Terminal.Cell returns it. Reading a cell does not allocate.

func (Cell) AppendText

func (c Cell) AppendText(b []byte) []byte

AppendText appends the cell's characters (as Text returns them) to b.

func (Cell) Text

func (c Cell) Text() string

Text returns the cell's characters: Rune followed by Combining, or "" for an empty cell or the right half of a wide character. It allocates only for non-ASCII characters; AppendText never does.

type Color

type Color uint32

Color is a foreground or background color: the terminal's default, one of the 256 palette entries, or a 24-bit RGB color. The zero value is DefaultColor. Colors are comparable; Palette.Resolve turns one into RGB.

const DefaultColor Color = 0

DefaultColor is the terminal's default foreground or background.

func IndexedColor

func IndexedColor(n uint8) Color

IndexedColor returns palette entry n: 0-7 are the ANSI colors, 8-15 their bright versions, 16-231 a 6x6x6 color cube and 232-255 a gray ramp.

func RGBColor

func RGBColor(r, g, b uint8) Color

RGBColor returns the 24-bit color r, g, b.

func (Color) Index

func (c Color) Index() uint8

Index returns the palette entry of an indexed color (0 for other kinds).

func (Color) Kind

func (c Color) Kind() ColorKind

Kind reports whether c is the default color, a palette entry or RGB.

func (Color) RGB

func (c Color) RGB() RGB

RGB returns the components of an RGB color (zero for other kinds; see Palette.Resolve for those).

type ColorKind

type ColorKind uint8

ColorKind says how a Color is specified.

const (
	ColorDefault ColorKind = iota // the default foreground or background
	ColorIndexed                  // a palette entry (SGR 30-37, 90-97, 38;5;n...)
	ColorRGB                      // a 24-bit color (SGR 38;2;r;g;b...)
)

The kinds of Color.

type Cursor

type Cursor struct {
	// X and Y are the 0-based column and row on the visible screen.
	X, Y int
	// Visible is false when the program hid the cursor (DECTCEM).
	Visible bool
	// Shape and Blink are what the program asked for with DECSCUSR.
	Shape CursorShape
	Blink bool
	// PendingWrap is set when a character was just printed in the last
	// column: the cursor stays there, and the next character goes to the
	// next line.
	PendingWrap bool
}

Cursor is the cursor's state.

type CursorShape

type CursorShape uint8

CursorShape is the cursor shape a program asked for with DECSCUSR.

const (
	CursorDefault   CursorShape = iota // the program did not ask (or asked for the default)
	CursorBlock                        // a block
	CursorUnderline                    // an underline
	CursorBar                          // a vertical bar
)

The cursor shapes.

type Hyperlink struct {
	// ID is the link's id parameter, which ties together the cells of one
	// link that are not adjacent ("" if the program gave none).
	ID string
	// URI is the link target.
	URI string
}

Hyperlink is an OSC 8 hyperlink. The zero value is no link.

type Modes

type Modes struct {
	AltScreen             bool          // the alternate screen is shown (47, 1047, 1049)
	ApplicationCursorKeys bool          // DECCKM: cursor keys send ESC O A...
	ApplicationKeypad     bool          // DECKPAM: the keypad sends application sequences
	BracketedPaste        bool          // 2004: pasted text is wrapped in ESC [200~ ... ESC [201~
	FocusEvents           bool          // 1004: report focus in and out
	Mouse                 MouseMode     // the mouse events to report (9, 1000, 1002, 1003)
	MouseEncoding         MouseEncoding // how to encode them (1005, 1006, 1015)
	// KittyKeyboard holds the kitty keyboard protocol flags in effect
	// (CSI > u), 0 when the protocol is off.
	KittyKeyboard uint16
	Autowrap      bool // DECAWM
	Insert        bool // IRM
	Newline       bool // LNM: line feed also returns the carriage
	Origin        bool // DECOM: cursor positions are relative to the margins
	ReverseVideo  bool // DECSCNM: the whole screen is drawn inverted
	// SyncUpdate is set while the program is drawing a frame it wants
	// shown at once (2026): a renderer may wait for it to clear.
	SyncUpdate bool
}

Modes are the terminal modes a program sets, mostly to say how input should be encoded for it and how the screen should be drawn.

type MouseEncoding

type MouseEncoding uint16

MouseEncoding is how mouse reports are encoded. Its values are the DEC private mode numbers.

const (
	MouseEncodingDefault MouseEncoding = 0    // CSI M with bytes
	MouseEncodingUTF8    MouseEncoding = 1005 // CSI M with UTF-8
	MouseEncodingSGR     MouseEncoding = 1006 // CSI < ... M/m
	MouseEncodingURXVT   MouseEncoding = 1015 // CSI ... M
)

The mouse report encodings.

type MouseMode

type MouseMode uint16

MouseMode is the mouse tracking a program turned on. Its values are the DEC private mode numbers.

const (
	MouseNone        MouseMode = 0    // no tracking
	MouseX10         MouseMode = 9    // presses only
	MouseNormal      MouseMode = 1000 // presses and releases
	MouseButtonEvent MouseMode = 1002 // ... and motion with a button down
	MouseAnyEvent    MouseMode = 1003 // ... and all motion
)

The mouse tracking modes.

type Option

type Option func(*config)

An Option configures a Terminal in New.

func WithBell

func WithBell(fn func()) Option

WithBell calls fn when the program rings the bell (BEL), during Write.

func WithPalette

func WithPalette(p Palette) Option

WithPalette sets the colors the terminal starts with: those it reports to programs that ask (see WithReply), and that Terminal.Palette returns. The default is DefaultPalette.

func WithReply

func WithReply(w io.Writer) Option

WithReply makes the terminal answer the queries programs send, by writing the replies to w: usually the pseudo-terminal's input side, so they reach the program. Without it queries are ignored, as when a real terminal is attached to answer them instead.

Answered: primary, secondary and tertiary device attributes (DA1, DA2, DA3), device status and cursor position reports (DSR 5 and 6, DECXCPR, and DSR ?15, ?26 and ?996), mode reports (DECRQM, ANSI and DEC), DECRQSS for SGR, DECSTBM, DECSLRM, DECSCUSR, DECSCA and DECSCL, XTVERSION, XTGETTCAP for TN, Co and colors, the kitty keyboard flags (CSI ? u), the text area size (XTWINOPS 18), and color queries (OSC 4, 10, 11, 12, answered from the palette). Errors from w are ignored. w is called during Write, with a slice it must not keep.

func WithScrollback

func WithScrollback(lines int) Option

WithScrollback keeps up to lines lines of scrollback (a line that soft wrapped on screen counts once). Zero or less disables the scrollback. The default is DefaultScrollbackLines.

func WithScrollbackBytes

func WithScrollbackBytes(n int) Option

WithScrollbackBytes bounds the memory the scrollback holds to about n bytes (lines are stored serialized, styles included), dropping the oldest lines first; the newest line is always kept. Zero or less means no byte limit. The default is DefaultScrollbackBytes.

type Palette

type Palette struct {
	Foreground RGB // the default foreground (OSC 10)
	Background RGB // the default background (OSC 11)
	Cursor     RGB // the cursor (OSC 12)
	// Colors are the 256 indexed colors (OSC 4).
	Colors [256]RGB
}

Palette is the set of colors a terminal reports to programs that ask (OSC 4, 10, 11 and 12), and that a renderer uses to draw indexed and default colors.

func DefaultPalette

func DefaultPalette() Palette

DefaultPalette returns the palette a Terminal starts with unless WithPalette sets another: xterm's 256 colors, with light gray text on black.

func (*Palette) Resolve

func (p *Palette) Resolve(c Color, background bool) RGB

Resolve returns the RGB value of c in this palette. A DefaultColor is the default background when background is set, else the default foreground.

type RGB

type RGB struct{ R, G, B uint8 }

RGB is a 24-bit color.

type Style

type Style struct {
	Fg, Bg    Color     // foreground and background
	Attrs     Attr      // bold, italic...
	Underline Underline // the underline style, if underlined
}

Style is how a cell is drawn. The zero value is the default style. Styles are comparable. Inverse is not applied: Fg and Bg are as the program set them, and AttrInverse (and Modes.ReverseVideo) say to swap them.

type Terminal

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

Terminal is a VT/xterm screen model: write a program's output to it and read back what a terminal would show. Create one with New.

A Terminal is not safe for concurrent use: callers that write from one goroutine and read from another must hold a lock around both. Writers and callbacks given as options run synchronously inside Write and must not call back into the Terminal.

func New

func New(cols, rows int, opts ...Option) *Terminal

New returns a blank terminal of cols x rows (each at least 1), configured by opts.

func (*Terminal) AppendRepaint

func (t *Terminal) AppendRepaint(b []byte, withScrollback bool) []byte

AppendRepaint appends Repaint's output to b and returns the extended buffer, for callers that reuse one.

func (*Terminal) Cell

func (t *Terminal) Cell(x, y int) Cell

Cell returns the cell at column x, row y of the visible screen (the alternate screen while it is shown). It returns a zero Cell for a position outside the screen.

func (*Terminal) ClearDirty

func (t *Terminal) ClearDirty()

ClearDirty marks every row clean, typically after a renderer has drawn the dirty ones. Damage tracking starts with the first call; until then it costs nothing.

func (*Terminal) ClearScrollback

func (t *Terminal) ClearScrollback()

ClearScrollback drops the scrollback, as ED 3 (CSI 3 J) does.

func (*Terminal) Compact added in v0.2.0

func (t *Terminal) Compact()

Compact releases unused storage after a terminal becomes idle. It drops rows containing only zero cells, unused wrap flags, dead Unicode and hyperlink entries, invalid saved cursor storage and temporary buffers. It keeps screen contents, scrollback, cursors, modes, damage and unfinished parser input unchanged. Later output may allocate those buffers again.

Like Write and Resize, Compact requires exclusive access to the Terminal. The caller decides when to run it; output never compacts itself.

func (*Terminal) Cursor

func (t *Terminal) Cursor() Cursor

Cursor returns the cursor's position, visibility and shape.

func (*Terminal) Dirty

func (t *Terminal) Dirty() bool

Dirty reports whether any row is dirty (see RowDirty).

func (*Terminal) Line

func (t *Terminal) Line(y int) string

Line returns row y of the visible screen as text, without trailing blanks ("" for a row out of range).

func (*Terminal) Lines

func (t *Terminal) Lines() []string

Lines returns the visible screen as text, one string per row, without trailing blanks.

func (*Terminal) Modes

func (t *Terminal) Modes() Modes

Modes returns the modes the program has set.

func (*Terminal) Palette

func (t *Terminal) Palette() Palette

Palette returns the colors in effect: the palette the terminal started with (DefaultPalette, or WithPalette's), with the changes the program made since (OSC 4, 10, 11 and 12).

func (*Terminal) Repaint

func (t *Terminal) Repaint(withScrollback bool) []byte

Repaint returns a byte sequence that, written to a terminal of the same size in its initial state, reproduces this one: the scrollback (when withScrollback is set) followed by the main screen with its soft wraps, then the alternate screen if active (or kept by mode 47), tab stops, modes saved with XTSAVE, the saved cursor, the scroll region and margins, the cursor with its pending wrap, pen, character sets and shape, the modes the program set (wraparound, insert, keypad and cursor keys, mouse tracking and encoding, focus events, bracketed paste, kitty keyboard flags...) and the title. Feeding it to a new Terminal of the same size gives the same screen, cursor, modes and scrollback; it is also meant for real terminals, so a client can attach to a running program, and a checkpoint can be restored by replaying it.

Unfinished escape sequences and UTF-8 characters are restored after the repaint, so the next output continues them instead of printing their remaining bytes. A synchronized update in progress stays in progress. Colors set by the program (OSC 4, 10, 11, 12) are not included, since replaying those would change the receiving terminal's own colors.

The output is wrapped in a synchronized update (mode 2026) and hides the cursor while painting.

Example
package main

import (
	"fmt"
	"io"

	"github.com/2018kguo/phosphor"
)

func main() {
	src := phosphor.New(30, 3)
	io.WriteString(src, "\x1b]2;build\x07\x1b[32mok\x1b[m 12 tests\r\n\x1b[?2004h")

	// A client attaching later (or a restore from a checkpoint) replays
	// Repaint on a fresh terminal of the same size.
	dst := phosphor.New(30, 3)
	dst.Write(src.Repaint(true))
	fmt.Printf("%q %q %v %v\n", dst.Line(0), dst.Title(), dst.Modes().BracketedPaste, dst.Cell(0, 0).Style == src.Cell(0, 0).Style)
}
Output:
"ok 12 tests" "build" true true

func (*Terminal) Resize

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

Resize changes the screen size to cols x rows (each at least 1). On the main screen, lines that soft wrapped are rewrapped to the new width (reflow); when the content needs more rows than the screen has, blank rows below the cursor go first, then rows from the top go to the scrollback, and when it needs fewer, lines come back from the scrollback. The alternate screen is not reflowed: its rows are cut or padded (full-screen programs redraw when told of the new size). The cursor and saved cursors follow the characters they were on. The scroll region and margins are reset, and every row is marked dirty.

Resize does not tell the program: the caller resizes the pseudo-terminal too (which sends it SIGWINCH).

func (*Terminal) Restart

func (t *Terminal) Restart()

Restart prepares the terminal for a new program after the previous one ended, as a terminal that relaunches its command keeps the old output in view: it resets everything as RIS (ESC c) does, keeps the scrollback, and leaves what the screen showed above the cursor, as if it had been printed. That is the main screen down to its last non-blank row, then, if a full-screen program was showing the alternate screen, that too. Whatever does not fit above the last row scrolls into the scrollback, and the cursor starts the row below the kept content.

Options given to New (reply writer, bell, palette) are kept; colors set by the program (OSC 4, 10, 11, 12) are reset.

Example
package main

import (
	"fmt"
	"io"

	"github.com/2018kguo/phosphor"
)

func main() {
	t := phosphor.New(20, 4)
	io.WriteString(t, "$ make\r\nerror: oops\r\n\x1b[?1049h\x1b[2J\x1b[Hfull-screen app")

	// The program exited and is started again: keep its last screen above.
	t.Restart()
	io.WriteString(t, "$ ")
	for _, line := range t.Lines() {
		fmt.Printf("%q\n", line)
	}
}
Output:
"$ make"
"error: oops"
"full-screen app"
"$"

func (*Terminal) RowDirty

func (t *Terminal) RowDirty(y int) bool

RowDirty reports whether the cells of row y of the visible screen may have changed since the last ClearDirty: characters, styles or links, by output, scrolling, erasing, switching screens, Resize or a change of palette or reverse video. Before the first ClearDirty every row is dirty.

The cursor is not part of it: a renderer compares Cursor with what it drew. Rows out of range are never dirty.

func (*Terminal) ScrollbackCells

func (t *Terminal) ScrollbackCells(i int) [][]Cell

ScrollbackCells returns scrollback line i (see ScrollbackLine) with its styles and links, laid out as the rows it takes at the current width: one row, or more for a line that soft wraps. Unlike the other accessors it allocates, about as much as replaying the line costs.

func (*Terminal) ScrollbackLen

func (t *Terminal) ScrollbackLen() int

ScrollbackLen returns the number of lines in the scrollback. A line that soft wrapped on screen is one line.

func (*Terminal) ScrollbackLine

func (t *Terminal) ScrollbackLine(i int) string

ScrollbackLine returns scrollback line i as text, without trailing blanks: 0 is the oldest line, ScrollbackLen()-1 the newest ("" for a line out of range).

func (*Terminal) ScrollbackLines

func (t *Terminal) ScrollbackLines() []string

ScrollbackLines returns the scrollback as text, oldest line first.

func (*Terminal) Size

func (t *Terminal) Size() (cols, rows int)

Size returns the screen size.

func (*Terminal) Title

func (t *Terminal) Title() string

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

func (*Terminal) Wrapped

func (t *Terminal) Wrapped(y int) bool

Wrapped reports whether row y of the visible screen continues the row above it, because the text there reached the last column and wrapped (row 0 of the main screen can continue the last scrollback line). Text selection and copying join such rows without a line break.

func (*Terminal) Write

func (t *Terminal) Write(p []byte) (int, error)

Write feeds the terminal a program's output, implementing io.Writer. Escape sequences and UTF-8 characters may be split across calls. It consumes all of p and never fails; it does not keep p. Replies to queries (see WithReply) and the bell callback run before it returns.

type Underline

type Underline uint8

Underline is an underline style (SGR 4, 4:n, 21).

const (
	UnderlineNone   Underline = iota // SGR 24
	UnderlineSingle                  // SGR 4 or 4:1
	UnderlineDouble                  // SGR 21 or 4:2
	UnderlineCurly                   // SGR 4:3
	UnderlineDotted                  // SGR 4:4
	UnderlineDashed                  // SGR 4:5
)

The underline styles.

Directories

Path Synopsis
internal
benchdata
Package benchdata generates deterministic terminal output streams for benchmarks and the load test: what an agent TUI, a log tail and a progress bar print.
Package benchdata generates deterministic terminal output streams for benchmarks and the load test: what an agent TUI, a log tail and a progress bar print.

Jump to

Keyboard shortcuts

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