phosphor

package module
v0.4.3 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: MIT Imports: 14 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 small, headless terminal emulator for Go programs that keep lots of PTYs alive.

Feed it a program's output and read what a terminal would show: cells, colors, hyperlinks, cursor, modes and scrollback. Save an exact checkpoint, or send ANSI to a client attaching later. You supply the PTY, input encoding and renderer.

Phosphor is the screen model inside ptyd. It is built for sessions that spend much of their lives waiting at a prompt, with no client attached, but still need to resume an editor correctly.

Use it

Add it to a Go project:

go get github.com/2018kguo/phosphor
package main

import (
	"fmt"
	"io"

	"github.com/2018kguo/phosphor"
)

func main() {
	t := phosphor.New(80, 24)
	io.WriteString(t, "\x1b[32mok\x1b[0m 12 tests\r\n")

	fmt.Println(t.Line(0)) // ok 12 tests
	fmt.Println(t.Cell(0, 0).Style.Fg == phosphor.IndexedColor(2)) // true
}

Terminal is an io.Writer; escape sequences and UTF-8 may be split across writes. For a live program, use phosphor.WithReply(ptmx) to send terminal query replies back through the PTY master. Some shells and editors wait for those answers. The reference shows the wiring.

To try a renderer, clone the repo and run:

cd examples
go run ./mirror vim

The mirror example produces the demo above. Its characters and colors come from Cell; it redraws only changed rows.

When it is useful

  • Hosting many sessions. Keep a screen model for remote shells, coding agents or background jobs, including sessions nobody is currently viewing.
  • Inspecting terminal programs. Read the current screen, attributes, hyperlinks and shell prompt markers instead of trying to interpret logs as an editor's display.
  • Attaching and recovering. Give a new client the current picture with Repaint, and preserve exact emulator state on disk with Snapshot.
  • Building your own UI. Draw cells in a browser, native app or terminal renderer, using row damage to avoid redrawing everything.

The library is pure Go and embeds in your process. It answers terminal queries and models output; your application owns process management, keyboard and mouse encoding, clipboard integration and the way cells appear on screen.

Why Phosphor instead of libghostty

libghostty-vt already provides an embeddable terminal core. It supports headless use, snapshots and idle compression. Choosing it does not mean embedding the Ghostty GUI.

Phosphor grew out of ptyd's need to keep many sessions alive while nobody is watching them. A shell can wait at a prompt for hours. An editor can close while its alternate screen still needs to survive. The storage kept between bursts of output matters as much as parsing speed.

Recorded headless workloads show the storage and speed tradeoffs:

Workload or retained state Phosphor compared with libghostty-vt
Prompts after erase and compaction About 10–26× less incremental RSS, depending on emulator count and allocator amortization
Completed editors and pagers 19–51% less RSS, with inactive editor buffers retained
Exactly 100 styled history rows About 3.1× less RSS, with equal retained contents verified
Editor/pager recordings and progress 1.22–2.67× more bytes per CPU second under the recorded budgets
Scrolling logs Native is 19% faster with budgeted history; Phosphor is 2.2× faster with history disabled
Grapheme-heavy Unicode Native is about 13% faster with history and 3% faster without it at the measured write size

Inputs match, but equal byte budgets keep different amounts of history: Phosphor stores serialized logical lines; native prunes physical pages. The memory runs use 128 and 1,024 emulators in fresh processes and compact both engines. They exclude the child program and PTY. The report records policies, all samples and a history-disabled parsing control. These are workload measurements, not per-session guarantees.

Phosphor keeps that model in Go: no cgo, native library or separate build toolchain. Its production module has no external Go dependencies. Its API exposes cells directly, and the application decides when to compact storage and save a checkpoint. This makes it a useful fit for Go daemons that want to control the lifetime and cost of terminal state. Maintaining a separate emulator also means maintaining its compatibility; the test corpus and remaining differences are part of that cost.

Choose libghostty when you want Ghostty's terminal behavior and a native dependency fits your application. It also supplies input encoders and other APIs that Phosphor leaves to the host. Both cores can run without a renderer. The reasons to choose Phosphor are its Go integration and storage choices. Speed and fidelity still need to be checked against your programs.

What the measurements show

Idle memory stays small. An 80×24 prompt after erase and compaction used about 1.51 KB of Go heap, with a reply sink installed in the measured workload. Rows grow as they are used, history has configurable line and byte budgets, and Compact() releases unused storage after output settles.

That prompt number is not the cost of every session. A closed editor's alternate screen must stay available for later re-entry: the completed recordings retained 22–47 KB of heap after Compact. History and rich attributes add their own storage. Benchmarks explains what is retained and how heap differs from process RSS.

Continuation is part of correctness. Checkpoints keep both screens, saved cursors, modes, colors, scrollback and unfinished input. Tests continue writing and resizing after restore, so a correct first picture is only the start. The library also reads the earlier checkpoint format; reader requirements matter when upgrading.

Compatibility is checked against other terminals. Five external suites, real editor recordings, fuzzing and a pinned libghostty-vt comparison cover cells, Unicode, replies and future behavior. Remaining policy differences and ANSI replay limits are published, including the cases where terminals disagree. This is not a claim of universal VT compatibility.

Output parsing depends on the workload. The recorded comparison leads libghostty-vt on several editor/pager recordings and progress output. History policy changes the log result, and native leads on grapheme-heavy Unicode. Choose using your workload, rather than a claim that one engine wins every stream.

Tradeoffs

Phosphor models terminal text: UTF-8 and Unicode widths, colors and attributes, wide characters and graphemes, hyperlinks, alternate screens, margins, scrollback, common queries and input modes. Modes() tells your input encoder what the running program requested.

It provides no window, fonts, GPU renderer, input encoder, sixel/kitty images or clipboard provider. Some VT features, including rectangular operations and double-size lines, are outside its scope. See the supported behavior before choosing it for an application that depends on a particular escape sequence.

Snapshot is the persistence format. Repaint is portable terminal output and has a weaker contract: REP, a few cursor/margin combinations, very narrow graphemes and mixed-background alternate screens can differ on continued output. Program-set palette colors are omitted from replay. See the precise snapshot reader requirements and ANSI attach limits.

A Terminal needs exclusive access: use one goroutine or hold a lock around all reads and writes. Reply writers and bell callbacks run during Write and must not call back into that terminal.

Docs

  • Reference: PTY wiring, rendering, replies, history, checkpoints, replay and supported behavior.
  • Benchmarks: current memory and throughput results, compatibility coverage, caveats and raw evidence.
  • Development: run the demo, tests, benchmarks and optional native comparison.
  • Go API and examples: all exported types and methods.

License

MIT. See LICENSE. External test sources and their licenses are listed in NOTICE.md. X11 color names retain the notices in licenses/X11.txt.

Documentation

Overview

Code generated by go run ./internal/unicodegen; DO NOT EDIT. Unicode 18.0.0; width source Ghostty 6ba144158577d033ccb6ed4b574e4013957c9161. Inputs and checksums: internal/unicodegen/sources.json. Unicode data copyright Unicode, Inc.; see testdata/conformance/LICENSE.unicode.

Code generated by go run ./internal/colorgen; DO NOT EDIT. X11 rgb.txt from Ghostty 46e9dc9a927b2e7e7cba79e6902c176127dbdf2c; SHA256 f8e3a7bea17acc0b91e6285c5d32001db27d84c4461c655afdbce9dbeb4fb6f0. Source: https://raw.githubusercontent.com/ghostty-org/ghostty/46e9dc9a927b2e7e7cba79e6902c176127dbdf2c/src/terminal/res/rgb.txt Copyright The Open Group and Oracle; see licenses/X11.txt.

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 exports ANSI output for attaching clients; Snapshot preserves exact emulator state for checkpoints, including unfinished input and saved cursors.

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)          // ANSI output for an attached terminal
t.Snapshot()             // exact checkpoint, 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, 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

View Source
var (
	ErrSnapshotMalformed = errors.New("malformed terminal snapshot")
	ErrSnapshotVersion   = errors.New("unsupported terminal snapshot version")
	ErrSnapshotLimit     = errors.New("terminal snapshot exceeds limit")
)

Functions

func CodepointWidth added in v0.3.0

func CodepointWidth(r rune) int

CodepointWidth returns the terminal width of a single scalar: zero for combining or ignored scalars, two for wide scalars, otherwise one. Invalid scalars have width one. A complete grapheme can have a different width under mode 2027, so summing scalar widths measures mode-off layout.

Types

type AltScreenModes added in v0.4.0

type AltScreenModes uint8

AltScreenModes records independently enabled DEC alternate-screen modes. Their bits may differ from the screen currently shown; the last set or reset switches screens even when other mode bits remain enabled.

const (
	AltScreenMode47 AltScreenModes = 1 << iota
	AltScreenMode1047
	AltScreenMode1049
)

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)
	AltScreenModes        AltScreenModes     // independent 47/1047/1049 bits
	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, 1016)
	MouseTrackingModes    MouseTrackingModes // enabled tracking bits, queried and saved independently
	MouseEncodingModes    MouseEncodingModes // enabled encoding bits, queried and saved independently
	// 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
	// GraphemeClustering joins Unicode grapheme clusters into cells (2027).
	GraphemeClustering   bool
	Columns132           bool // DECCOLM (3): the program selected 132-column mode
	AllowColumnSwitching bool // mode40 permits DECCOLM to resize the terminal
	SmoothScrolling      bool // DEC mode4 requests smooth scrolling from the renderer
}

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
	MouseEncodingSGRPixels MouseEncoding = 1016 // CSI < ... M/m with pixel coordinates
)

The mouse report encodings.

type MouseEncodingModes added in v0.4.0

type MouseEncodingModes uint8

MouseEncodingModes records the independently enabled mouse report encodings. MouseEncoding in Modes reports the most recently selected encoding.

const (
	MouseEncodingModeUTF8 MouseEncodingModes = 1 << iota
	MouseEncodingModeSGR
	MouseEncodingModeURXVT
	MouseEncodingModeSGRPixels
)

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 MouseTrackingModes added in v0.4.0

type MouseTrackingModes uint8

MouseTrackingModes records the independently enabled mouse tracking modes. Mouse in Modes reports the most recently selected tracking behavior.

const (
	MouseTrackingX10 MouseTrackingModes = 1 << iota
	MouseTrackingNormal
	MouseTrackingButtonEvent
	MouseTrackingAnyEvent
)

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, 21, 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, 12 and 21), 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 PromptKind added in v0.4.0

type PromptKind uint8

PromptKind identifies a row annotated by the shell through OSC133.

const (
	PromptNone PromptKind = iota
	PromptPrimary
	PromptContinuation
)

type RGB

type RGB struct{ R, G, B uint8 }

RGB is a 24-bit color.

type SnapshotLimits added in v0.3.0

type SnapshotLimits struct {
	// MaxBytes bounds requested decoded storage, including cell rows, slice
	// tables and strings. Zero selects 64 MiB. Allocator overhead is excluded.
	MaxBytes int
	// MaxCells bounds columns * rows for each screen, including sparse blank
	// cells that may be allocated by later output. Zero selects 4 Mi cells.
	MaxCells int
}

SnapshotLimits bounds the storage a RestoreSnapshot call may install. Limits do not change the snapshot's scrollback policy or bound later output.

type Style

type Style struct {
	Fg, Bg         Color     // foreground and background
	UnderlineColor Color     // default follows the foreground
	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) AppendSnapshot added in v0.3.0

func (t *Terminal) AppendSnapshot(dst []byte) []byte

AppendSnapshot appends an exact checkpoint to dst, reusing its storage.

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 unused zero tails and rows, unused wrap flags, dead Unicode and cell attribute 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, 12 and 21).

func (*Terminal) Prompt added in v0.4.0

func (t *Terminal) Prompt(y int) PromptKind

Prompt returns the shell prompt annotation for visible row y. Out-of-range rows return PromptNone. It does not allocate.

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) RestoreSnapshot added in v0.3.0

func (t *Terminal) RestoreSnapshot(data []byte, limits SnapshotLimits) error

RestoreSnapshot replaces durable state and retains only the receiver's reply writer and bell callback. It also works on a zero Terminal. Constructor geometry, palette and scrollback choices are replaced by snapshot state.

No callbacks run, no input storage is retained, and an error leaves the receiver unchanged. Negative limits are invalid. The decoded-storage bound excludes fixed parser-validation scratch state and a buffer of at most maxOSC+4 bytes.

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 rare, 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 rare, 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) Snapshot added in v0.3.0

func (t *Terminal) Snapshot() []byte

Snapshot returns an exact checkpoint, including scrollback and unfinished input. Use Repaint to draw the terminal into another terminal. Snapshots do not contain reply writers or bell callbacks.

Like Write and Resize, snapshot methods require exclusive access.

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.
colorgen command
Command colorgen regenerates the X11 color names from the pinned source.
Command colorgen regenerates the X11 color names from the pinned source.
unicodegen command
Command unicodegen regenerates the terminal's fused Unicode properties.
Command unicodegen regenerates the terminal's fused Unicode properties.

Jump to

Keyboard shortcuts

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