package uv

Import Path
	github.com/charmbracelet/ultraviolet (on go.dev)

Dependency Relation
	imports 38 packages, and imported by one package

Involved Source Files border.go buffer.go cancelreader_other.go cell.go console.go console_unix.go cursor.go decoder.go Package uv (Ultraviolet) provides primitives for building terminal user interfaces in Go. It offers cell-based screen buffers, a diffing terminal renderer, cross-platform input decoding (keyboard, mouse, paste, focus, resize), and a windowing model with off-screen buffers. Ultraviolet powers Bubble Tea v2 and Lip Gloss v2. # Getting Started Create a terminal, get its screen, and run an event loop: t := uv.DefaultTerminal() scr := t.Screen() scr.EnterAltScreen() if err := t.Start(); err != nil { log.Fatal(err) } defer t.Stop() for ev := range t.Events() { switch ev := ev.(type) { case uv.WindowSizeEvent: scr.Resize(ev.Width, ev.Height) case uv.KeyPressEvent: if ev.MatchString("q") { return } } } # Rendering Drawing is a two-step process. [TerminalScreen.Render] diffs the screen and writes escape sequences to an internal buffer. [TerminalScreen.Flush] sends the buffer to the terminal—this is the only method that performs real I/O. scr.Render() scr.Flush() Use the screen package for high-level drawing helpers like [screen.Context.DrawString] and [screen.Clear]. # Packages - screen — drawing context and screen manipulation helpers - layout — constraint-based layout solver (Cassowary algorithm) environ.go event.go key.go key_table.go logger.go mouse.go poll.go poll_fallback.go poll_linux.go styled.go tabstop.go terminal.go terminal_bsdly.go terminal_reader.go terminal_reader_other.go terminal_renderer.go terminal_renderer_hardscroll.go terminal_renderer_hashmap.go terminal_screen.go terminal_tabdly.go terminal_unix.go tty.go tty_unix.go utils.go uv.go winch.go winch_unix.go window.go
Package-Level Type Names (total 105, in which 94 are exported)
/* sort exporteds by: | */
BackgroundColorEvent represents a background color event. This event is emitted when the terminal requests the terminal background color using [ansi.RequestBackgroundColor]. Color color.Color IsDark returns whether the color is dark. RGBA returns the alpha-premultiplied red, green, blue and alpha values for the color. Each value ranges within [0, 0xffff], but is represented by a uint32 so that multiplying by a blend factor up to 0xffff will not overflow. An alpha-premultiplied color component c has been scaled by alpha (a), so has valid values 0 <= c <= a. String returns the hex representation of the color. BackgroundColorEvent : github.com/charmbracelet/x/ansi.Color BackgroundColorEvent : expvar.Var BackgroundColorEvent : fmt.Stringer BackgroundColorEvent : image/color.Color
BlurEvent represents a terminal blur event. This occurs when the terminal loses focus.
Border represents a border with its properties. Bottom Side BottomLeft Side BottomRight Side Left Side Right Side Top Side TopLeft Side TopRight Side Draw draws the border around the given component. Link returns a new [Border] with the given link applied to all [Side]s. Style returns a new [Border] with the given style applied to all [Side]s. *Border : Drawable func ASCIIBorder() Border func BlockBorder() Border func DoubleBorder() Border func HiddenBorder() Border func InnerHalfBlockBorder() Border func MarkdownBorder() Border func NormalBorder() Border func OuterHalfBlockBorder() Border func RoundedBorder() Border func ThickBorder() Border func Border.Link(link Link) Border func Border.Style(style Style) Border
Buffer represents a cell buffer that contains the contents of a screen. Lines is a slice of lines that make up the cells of the buffer. Bounds returns the bounds of the buffer. The origin is always at (0, 0) and the maximum coordinates are determined by the width and height of the buffer. CellAt returns the cell at the given position. It returns nil if the position is out of bounds. Clear clears the buffer with space cells and rectangle. ClearArea clears the buffer with space cells within the specified rectangles. Only cells within the rectangle's bounds are affected. Clone clones the entire buffer into a new buffer. CloneArea clones the area of the buffer within the specified rectangle. If the area is out of bounds, it returns nil. DeleteCell deletes cells at the given position, with the given optional cell, within the specified rectangles. If no rectangles are specified, it deletes cells in the entire buffer. This follows terminal [ansi.DCH] behavior. DeleteCellArea deletes cells at the given position, with the given optional cell, within the rectangle bounds. Only cells within the rectangle's bounds are affected, following terminal [ansi.DCH] behavior. DeleteLine deletes n lines at the given line position, with the given optional cell, within the specified rectangles. If no rectangles are specified, it deletes lines in the entire buffer. DeleteLineArea deletes lines at the given line position, with the given optional cell, within the rectangle bounds. Only cells within the rectangle's bounds are affected. Lines are shifted up within the bounds and new blank lines are created at the bottom. This follows terminal [ansi.DL] behavior. Draw draws the buffer to the given screen at the specified area. It implements the [Drawable] interface. Fill fills the buffer with the given cell and rectangle. FillArea fills the buffer with the given cell and rectangle. Height implements Screen. InsertCell inserts new cells at the given position, with the given optional cell, within the specified rectangles. If no rectangles are specified, it inserts cells in the entire buffer. This follows terminal [ansi.ICH] behavior. InsertCellArea inserts new cells at the given position, with the given optional cell, within the rectangle bounds. Only cells within the rectangle's bounds are affected, following terminal [ansi.ICH] behavior. InsertLine inserts n lines at the given line position, with the given optional cell, within the specified rectangles. If no rectangles are specified, it inserts lines in the entire buffer. Only cells within the rectangle's horizontal bounds are affected. Lines are pushed out of the rectangle bounds and lost. This follows terminal [ansi.IL] behavior. It returns the pushed out lines. InsertLineArea inserts new lines at the given line position, with the given optional cell, within the rectangle bounds. Only cells within the rectangle's horizontal bounds are affected. Lines are pushed out of the rectangle bounds and lost. This follows terminal [ansi.IL] behavior. Line returns a pointer to the line at the given y position. If the line does not exist, it returns nil. Render renders the buffer to a styled string with all the required attributes and styles. Resize resizes the buffer to the given width and height. SetCell sets the cell at the given x, y position. String returns the string representation of the buffer. Width implements Screen. *Buffer : Drawable *Buffer : expvar.Var *Buffer : fmt.Stringer func NewBuffer(width int, height int) *Buffer func (*Buffer).Clone() *Buffer func (*Buffer).CloneArea(area Rectangle) *Buffer
CapabilityEvent represents a Termcap/Terminfo response event. Termcap responses are generated by the terminal in response to RequestTermcap (XTGETTCAP) requests. See: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Operating-System-Commands Content is the pasted text content. String returns the capability content. CapabilityEvent : expvar.Var CapabilityEvent : fmt.Stringer
Cell represents a single cell in the terminal screen. Content is the [Cell]'s content, which consists of a single grapheme cluster. Most of the time, this will be a single rune as well, but it can also be a combination of runes that form a grapheme cluster. Link is the hyperlink of the cell. The style of the cell. Nil style means no style. Zero value prints a reset sequence. Width is the mono-spaced width of the grapheme cluster. Clone returns a copy of the cell. Empty makes the cell an empty cell by setting its content to a single space and width to 1. Equal returns whether the cell is equal to the other cell. IsZero returns whether the cell is an empty cell. String returns the string content of the cell excluding any styles, links, and escape sequences. *Cell : expvar.Var *Cell : fmt.Stringer func NewCell(method WidthMethod, gr string) *Cell func (*Buffer).CellAt(x int, y int) *Cell func (*Cell).Clone() (n *Cell) func Line.At(x int) *Cell func Screen.CellAt(x, y int) *Cell func (*TerminalScreen).CellAt(x, y int) *Cell func charm.land/lipgloss/v2.(*Canvas).CellAt(x int, y int) *Cell func (*Buffer).DeleteCell(x, y, n int, c *Cell) func (*Buffer).DeleteCellArea(x, y, n int, c *Cell, area Rectangle) func (*Buffer).DeleteLine(y, n int, c *Cell) func (*Buffer).DeleteLineArea(y, n int, c *Cell, area Rectangle) func (*Buffer).Fill(c *Cell) func (*Buffer).FillArea(c *Cell, area Rectangle) func (*Buffer).InsertCell(x, y, n int, c *Cell) func (*Buffer).InsertCellArea(x, y, n int, c *Cell, area Rectangle) func (*Buffer).InsertLine(y, n int, c *Cell) func (*Buffer).InsertLineArea(y, n int, c *Cell, area Rectangle) func (*Buffer).SetCell(x, y int, c *Cell) func (*Cell).Equal(o *Cell) bool func Line.Set(x int, c *Cell) func (*RenderBuffer).DeleteCell(x, y, n int, c *Cell) func (*RenderBuffer).DeleteCellArea(x, y, n int, c *Cell, area Rectangle) func (*RenderBuffer).DeleteLine(y, n int, c *Cell) func (*RenderBuffer).DeleteLineArea(y, n int, c *Cell, area Rectangle) func (*RenderBuffer).Fill(c *Cell) func (*RenderBuffer).FillArea(c *Cell, area Rectangle) func (*RenderBuffer).InsertCell(x, y, n int, c *Cell) func (*RenderBuffer).InsertCellArea(x, y, n int, c *Cell, area Rectangle) func (*RenderBuffer).InsertLine(y, n int, c *Cell) func (*RenderBuffer).InsertLineArea(y, n int, c *Cell, area Rectangle) func (*RenderBuffer).SetCell(x, y int, c *Cell) func Screen.SetCell(x, y int, c *Cell) func (*TerminalScreen).SetCell(x, y int, cell *Cell) func charm.land/lipgloss/v2.(*Canvas).SetCell(x int, y int, cell *Cell) var EmptyCell
CellSizeEvent represents the cell size in pixels. Height int Width int Bounds returns the bounds corresponding to the size.
ClipboardEvent is a clipboard read message event. This message is emitted when a terminal receives an OSC52 clipboard read message event. Content string Selection ClipboardSelection Clipboard returns the clipboard selection. This can be either [SystemClipboard] 'c' or [PrimaryClipboard] 'p'. String returns the string representation of the clipboard message. ClipboardEvent : expvar.Var ClipboardEvent : fmt.Stringer
ClipboardSelection represents a clipboard selection. The most common clipboard selections are "system" and "primary" and selections.
Console represents a cross-platform console I/O interface. ( Console) Close() error Environ returns the console's environment variables. GetSize returns the current size of the console. GetWinsize returns the current size of the console in cells and pixels. Getenv retrieves the value of the environment variable named by the key. LookupEnv retrieves the value of the environment variable named by the key and a boolean indicating whether the variable is present. MakeRaw puts the console input side into raw mode. ( Console) Read(p []byte) (n int, err error) Reader returns the input reader of the console. Restore restores the console to its previous state. ( Console) Write([]byte) (int, error) Writer returns the output writer of the console. TTY WinCon Console : internal/bisect.Writer Console : io.Closer Console : io.ReadCloser Console : io.Reader Console : io.ReadWriteCloser Console : io.ReadWriter Console : io.WriteCloser Console : io.Writer func ControllingConsole() (Console, error) func DefaultConsole() Console func NewConsole(input, output File, environ []string) Console func NewTerminal(con Console, opts *Options) *Terminal
Cursor represents a cursor on the terminal screen. Blink is a boolean that determines whether the cursor should blink. Color is a [color.Color] that determines the cursor's color. Hidden is a boolean that determines whether the cursor is hidden. You can use this if you want to hide the cursor but still want to change its position. Position is a [Position] that determines the cursor's position on the screen relative to the top left corner of the frame. Position.X int Position.Y int Shape is a [CursorShape] that determines the cursor's shape. Add returns the vector p+q. Div returns the vector p/k. Eq reports whether p and q are equal. In reports whether p is in r. Mod returns the point q in r such that p.X-q.X is a multiple of r's width and p.Y-q.Y is a multiple of r's height. Mul returns the vector p*k. String returns a string representation of p like "(3,4)". Sub returns the vector p-q. Cursor : expvar.Var Cursor : fmt.Stringer func NewCursor(x, y int) *Cursor
CursorColorEvent represents a cursor color change event. This event is emitted when the program requests the terminal cursor color using [ansi.RequestCursorColor]. Color color.Color IsDark returns whether the color is dark. RGBA returns the alpha-premultiplied red, green, blue and alpha values for the color. Each value ranges within [0, 0xffff], but is represented by a uint32 so that multiplying by a blend factor up to 0xffff will not overflow. An alpha-premultiplied color component c has been scaled by alpha (a), so has valid values 0 <= c <= a. String returns the hex representation of the color. CursorColorEvent : github.com/charmbracelet/x/ansi.Color CursorColorEvent : expvar.Var CursorColorEvent : fmt.Stringer CursorColorEvent : image/color.Color
CursorPositionEvent represents a cursor position event. Where X is the zero-based column and Y is the zero-based row. X int Y int
CursorShape represents a terminal cursor shape. Encode returns the encoded value for the cursor shape. func (*TerminalScreen).CursorStyle() (shape CursorShape, blink bool) func EncodeCursorStyle(w io.Writer, shape CursorShape, blink bool) error func (*TerminalScreen).SetCursorStyle(shape CursorShape, blink bool) const CursorBar const CursorBlock const CursorUnderline
DarkColorSchemeEvent is sent when the operating system is using a dark color scheme. This is typically used to notify applications of the current or new system color scheme.
Drawable represents a drawable component on a [Screen]. Draw renders the component on the screen for the given area. *Border *Buffer DrawableFunc RenderBuffer ScreenBuffer *StyledString Window *charm.land/lipgloss/v2.Canvas *charm.land/lipgloss/v2.Compositor *charm.land/lipgloss/v2.Layer func (*TerminalScreen).Display(d Drawable) error func charm.land/lipgloss/v2.(*Canvas).Compose(drawer Drawable) *lipgloss.Canvas
DrawableFunc is a function that implements the [Drawable] interface. Draw implements the [Drawable] interface. DrawableFunc : Drawable
Environ is a slice of strings that represents the environment variables of the program. Getenv returns the value of the environment variable named by the key. If the variable is not present in the environment, the value returned will be the empty string. LookupEnv retrieves the value of the environment variable named by the key. If the variable is present in the environment the value (which may be empty) is returned and the boolean is true. Otherwise the returned value will be empty and the boolean will be false. func NewTerminalScreen(w io.Writer, env Environ) *TerminalScreen
Event represents an input event that can be received from an input source. func (*EventDecoder).Decode(buf []byte) (n int, Event Event) func (*Terminal).Events() <-chan Event func EventStreamer.StreamEvents(ctx context.Context, ch chan<- Event) error func (*Terminal).SendEvent(e Event) func (*TerminalReader).StreamEvents(ctx context.Context, eventc chan<- Event) error
EventDecoder decodes terminal input events from a byte buffer. Terminal input events are typically encoded as Unicode or ASCII characters, control codes, or ANSI escape sequences. Legacy is the legacy key encoding flags. These flags control the behavior of legacy terminal key encodings. See [LegacyKeyEncoding] for more details. UseTerminfo is a flag that controls whether to use the terminal type Terminfo database to map escape sequences to key events. This will override the default key sequences handled by the parser. Decode finds the first recognized event sequence and returns it along with its length. It will return zero and nil no sequence is recognized or when the buffer is empty. If a sequence is not supported, an [UnknownEvent] is returned. Example: ```go var decoder EventDecoder var events []Event buf := []byte("\x00" + // Ctrl+Space "\x1b[A" + // Up arrow "Hello") // Text input for len(buf) > 0 { n, ev := decoder.Decode(buf) if ev != nil { events = append(events, ev) } buf = buf[n:] } ```
EventStreamer is an interface that defines a method to stream events from an input source. It takes a context and a channel to send events to. The streamer should block until the context is done or an error occurs. The channel should never be closed by the streamer, as it is the responsibility of the consumer to close it when done. ( EventStreamer) StreamEvents(ctx context.Context, ch chan<- Event) error *TerminalReader
File is an interface that represents a file with a file descriptor. This is typically an [os.File] like [os.Stdin] and [os.Stdout]. ( File) Close() error Fd returns its file descriptor Name returns its file name. ( File) Read(p []byte) (n int, err error) ( File) Write([]byte) (int, error) github.com/muesli/cancelreader.File (interface) *os.File File : github.com/charmbracelet/x/term.File File : github.com/muesli/cancelreader.File File : internal/bisect.Writer File : io.Closer File : io.ReadCloser File : io.Reader File : io.ReadWriteCloser File : io.ReadWriter File : io.WriteCloser File : io.Writer func NewConsole(input, output File, environ []string) Console
FocusEvent represents a terminal focus event. This occurs when the terminal gains focus.
ForegroundColorEvent represents a foreground color event. This event is emitted when the terminal requests the terminal foreground color using [ansi.RequestForegroundColor]. Color color.Color IsDark returns whether the color is dark. RGBA returns the alpha-premultiplied red, green, blue and alpha values for the color. Each value ranges within [0, 0xffff], but is represented by a uint32 so that multiplying by a blend factor up to 0xffff will not overflow. An alpha-premultiplied color component c has been scaled by alpha (a), so has valid values 0 <= c <= a. String returns the hex representation of the color. ForegroundColorEvent : github.com/charmbracelet/x/ansi.Color ForegroundColorEvent : expvar.Var ForegroundColorEvent : fmt.Stringer ForegroundColorEvent : image/color.Color
Key represents a Key press or release event. It contains information about the Key pressed, like the runes, the type of Key, and the modifiers pressed. There are a couple general patterns you could use to check for key presses or releases: // Switch on the string representation of the key (shorter) switch ev := ev.(type) { case KeyPressEvent: switch ev.String() { case "enter": fmt.Println("you pressed enter!") case "a": fmt.Println("you pressed a!") } } // Switch on the key type (more foolproof) switch ev := ev.(type) { case KeyEvent: // catch both KeyPressEvent and KeyReleaseEvent switch key := ev.Key(); key.Code { case KeyEnter: fmt.Println("you pressed enter!") default: switch key.Text { case "a": fmt.Println("you pressed a!") } } } Note that [Key.Text] will be empty for special keys like [KeyEnter], [KeyTab], and for keys that don't represent printable characters like key combos with modifier keys. In other words, [Key.Text] is populated only for keys that represent printable characters shifted or unshifted (like 'a', 'A', '1', '!', etc.). BaseCode is the key pressed according to the standard PC-101 key layout. On international keyboards, this is the key that would be pressed if the keyboard was set to US PC-101 layout. For example, if the user presses 'q' on a French AZERTY keyboard, [Key.BaseCode] will be 'q'. This is only available with the Kitty Keyboard Protocol or the Windows Console API. Code represents the key pressed. This is usually a special key like [KeyTab], [KeyEnter], [KeyF1], or a printable character like 'a'. IsRepeat indicates whether the key is being held down and sending events repeatedly. This is only available with the Kitty Keyboard Protocol or the Windows Console API. Mod represents modifier keys, like [ModCtrl], [ModAlt], and so on. ShiftedCode is the actual, shifted key pressed by the user. For example, if the user presses shift+a, or caps lock is on, [Key.ShiftedCode] will be 'A' and [Key.Code] will be 'a'. In the case of non-latin keyboards, like Arabic, [Key.ShiftedCode] is the unshifted key on the keyboard. This is only available with the Kitty Keyboard Protocol or the Windows Console API. Text contains the actual characters received. This usually the same as [Key.Code]. When [Key.Text] is non-empty, it indicates that the key pressed represents printable character(s). Keystroke returns the keystroke representation of the [Key]. While less type safe than looking at the individual fields, it will usually be more convenient and readable to use this method when matching against keys. Note that modifier keys are always printed in the following order: - ctrl - alt - shift - meta - hyper - super For example, you'll always see "ctrl+shift+alt+a" and never "shift+ctrl+alt+a". MatchString returns true if the [Key] matches one of the given strings. A string can be a key name like "enter", "tab", "a", or a printable character like "1" or " ". It can also have combinations of modifiers like "ctrl+a", "shift+enter", "alt+tab", "ctrl+shift+enter", etc. String implements [fmt.Stringer] and is quite useful for matching key events. It will return the textual representation of the [Key] if there is one, otherwise, it will fallback to [Key.Keystroke]. For example, you'll always get "?" and instead of "shift+/" on a US ANSI keyboard. Key : expvar.Var Key : fmt.Stringer func KeyEvent.Key() Key func KeyPressEvent.Key() Key func KeyReleaseEvent.Key() Key
KeyboardEnhancements defines different keyboard enhancement features that can be requested from the terminal. DisambiguateEscapeCodes requests the terminal to report ambiguous keys such as Ctrl+i and Tab, and Ctrl+m and Enter, and others as distinct key code sequences. If supported, your program will receive distinct [KeyPressEvent]s for these keys. ReportAllKeysAsEscapeCodes requests the terminal to report all key events, including plain text keys, as escape codes. When this is enabled, text won't be sent as plain text but instead as escape codes that encode the key value and modifiers. ReportAlternateKeys requests the terminal to report alternate key values in addition to the main ones. Note that only key events represented as escape codes will affected by this enhancement. ReportAssociatedText requests the terminal to report the text associated with key events. Note that this is an enhancement to [KeyboardEnhancements.ReportAllKeysAsEscapeCodes] and only has an effect if that is enabled. ReportEventTypes requests the terminal to report key repeat and release events. If supported, your program will receive [KeyReleaseEvent]s and [KeyPressEvent] with the [Key.IsRepeat] field set indicating that this is a it's part of a key repeat sequence. Flags returns the keyboard enhancements as bits that can be used to set the appropriate terminal modes. func NewKeyboardEnhancements(flags int) *KeyboardEnhancements func (*TerminalScreen).KeyboardEnhancements() *KeyboardEnhancements func EncodeKeyboardEnhancements(w io.Writer, ke *KeyboardEnhancements) error func (*TerminalScreen).SetKeyboardEnhancements(enh *KeyboardEnhancements)
KeyboardEnhancementsEvent represents a keyboard enhancements report event. Flags are the Kitty Keyboard Enhancement flags. Bit values: 00000001: Disambiguate escape codes 00000010: Report event types 00000100: Report alternate keys 00001000: Report all keys as escape codes 00010000: Report associated text See: https://sw.kovidgoyal.net/kitty/keyboard-protocol/#keyboard-enhancements Contains reports whether m contains the given enhancements. SupportsKeyDisambiguation returns whether the terminal supports reporting disambiguous keys as escape codes. SupportsKeyReleases returns whether the terminal supports key release events. SupportsUniformKeyLayout returns whether the terminal supports reporting key events as though they were on a PC-101 layout.
KeyEvent represents a key event. This can be either a key press or a key release event. Key returns the underlying key event. ( KeyEvent) String() string KeyPressEvent KeyReleaseEvent KeyEvent : expvar.Var KeyEvent : fmt.Stringer
KeyMod represents modifier keys. Contains reports whether m contains the given modifiers. Example: m := ModAlt | ModCtrl m.Contains(ModCtrl) // true m.Contains(ModAlt | ModCtrl) // true m.Contains(ModAlt | ModCtrl | ModShift) // false func KeyMod.Contains(mods KeyMod) bool const ModAlt const ModCapsLock const ModCtrl const ModHyper const ModMeta const ModNumLock const ModScrollLock const ModShift const ModSuper
KeyPressEvent represents a key press event. BaseCode is the key pressed according to the standard PC-101 key layout. On international keyboards, this is the key that would be pressed if the keyboard was set to US PC-101 layout. For example, if the user presses 'q' on a French AZERTY keyboard, [Key.BaseCode] will be 'q'. This is only available with the Kitty Keyboard Protocol or the Windows Console API. Code represents the key pressed. This is usually a special key like [KeyTab], [KeyEnter], [KeyF1], or a printable character like 'a'. IsRepeat indicates whether the key is being held down and sending events repeatedly. This is only available with the Kitty Keyboard Protocol or the Windows Console API. Mod represents modifier keys, like [ModCtrl], [ModAlt], and so on. ShiftedCode is the actual, shifted key pressed by the user. For example, if the user presses shift+a, or caps lock is on, [Key.ShiftedCode] will be 'A' and [Key.Code] will be 'a'. In the case of non-latin keyboards, like Arabic, [Key.ShiftedCode] is the unshifted key on the keyboard. This is only available with the Kitty Keyboard Protocol or the Windows Console API. Text contains the actual characters received. This usually the same as [Key.Code]. When [Key.Text] is non-empty, it indicates that the key pressed represents printable character(s). Key returns the underlying key event. This is a syntactic sugar for casting the key event to a [Key]. Keystroke returns the keystroke representation of the [Key]. While less type safe than looking at the individual fields, it will usually be more convenient and readable to use this method when matching against keys. Note that modifier keys are always printed in the following order: - ctrl - alt - shift - meta - hyper - super For example, you'll always see "ctrl+shift+alt+a" and never "shift+ctrl+alt+a". MatchString returns true if the [Key] matches one of the given strings. A string can be a key name like "enter", "tab", "a", or a printable character like "1" or " ". It can also have combinations of modifiers like "ctrl+a", "shift+enter", "alt+tab", "ctrl+shift+enter", etc. String implements [fmt.Stringer] and is quite useful for matching key events. For details, on what this returns see [Key.String]. KeyPressEvent : KeyEvent KeyPressEvent : expvar.Var KeyPressEvent : fmt.Stringer
KeyReleaseEvent represents a key release event. BaseCode is the key pressed according to the standard PC-101 key layout. On international keyboards, this is the key that would be pressed if the keyboard was set to US PC-101 layout. For example, if the user presses 'q' on a French AZERTY keyboard, [Key.BaseCode] will be 'q'. This is only available with the Kitty Keyboard Protocol or the Windows Console API. Code represents the key pressed. This is usually a special key like [KeyTab], [KeyEnter], [KeyF1], or a printable character like 'a'. IsRepeat indicates whether the key is being held down and sending events repeatedly. This is only available with the Kitty Keyboard Protocol or the Windows Console API. Mod represents modifier keys, like [ModCtrl], [ModAlt], and so on. ShiftedCode is the actual, shifted key pressed by the user. For example, if the user presses shift+a, or caps lock is on, [Key.ShiftedCode] will be 'A' and [Key.Code] will be 'a'. In the case of non-latin keyboards, like Arabic, [Key.ShiftedCode] is the unshifted key on the keyboard. This is only available with the Kitty Keyboard Protocol or the Windows Console API. Text contains the actual characters received. This usually the same as [Key.Code]. When [Key.Text] is non-empty, it indicates that the key pressed represents printable character(s). Key returns the underlying key event. This is a convenience method and syntactic sugar to satisfy the [KeyEvent] interface, and cast the key event to [Key]. Keystroke returns the keystroke representation of the [Key]. While less type safe than looking at the individual fields, it will usually be more convenient and readable to use this method when matching against keys. Note that modifier keys are always printed in the following order: - ctrl - alt - shift - meta - hyper - super For example, you'll always see "ctrl+shift+alt+a" and never "shift+ctrl+alt+a". MatchString returns true if the [Key] matches one of the given strings. A string can be a key name like "enter", "tab", "a", or a printable character like "1" or " ". It can also have combinations of modifiers like "ctrl+a", "shift+enter", "alt+tab", "ctrl+shift+enter", etc. String implements [fmt.Stringer] and is quite useful for matching key events. For details, on what this returns see [Key.String]. KeyReleaseEvent : KeyEvent KeyReleaseEvent : expvar.Var KeyReleaseEvent : fmt.Stringer
KittyGraphicsEvent represents a Kitty Graphics response event. See https://sw.kovidgoyal.net/kitty/graphics-protocol/ Options kitty.Options Payload []byte
LegacyKeyEncoding is a set of flags that control the behavior of legacy terminal key encodings. Historically, ctrl+<key> input events produce control characters (0x00-0x1F) that collide with some special keys like Tab, Enter, and Escape. This controls the expected behavior of encoding these keys. This type has the following default values: - CtrlAt maps 0x00 [ansi.NUL] to ctrl+space instead of ctrl+@. - CtrlI maps 0x09 [ansi.HT] to the tab key instead of ctrl+i. - CtrlM maps 0x0D [ansi.CR] to the enter key instead of ctrl+m. - CtrlOpenBracket maps 0x1B [ansi.ESC] to the escape key instead of ctrl+[. - Backspace maps the backspace key to 0x08 [ansi.BS] instead of 0x7F [ansi.DEL]. - Find maps the legacy find key to the home key. - Select maps the legacy select key to the end key. - FKeys maps high function keys instead of treating them as Function+<modifiers>. Backspace returns a [LegacyKeyEncoding] with whether the backspace key is mapped to [ansi.BS] (0x08) instead of [ansi.DEL] (0x7F). CtrlAt returns a [LegacyKeyEncoding] with whether [ansi.NUL] (0x00) is mapped to ctrl+at instead of ctrl+space. CtrlI returns a [LegacyKeyEncoding] with whether [ansi.HT] (0x09) is mapped to ctrl+i instead of the tab key. CtrlM returns a [LegacyKeyEncoding] with whether [ansi.CR] (0x0D) is mapped to ctrl+m instead of the enter key. CtrlOpenBracket returns a [LegacyKeyEncoding] with whether [ansi.ESC] (0x1B) is mapped to ctrl+[ instead of the escape key. FKeys returns a [LegacyKeyEncoding] with whether high function keys are mapped to high function keys (beyond F20) instead of treating them as Function+<modifiers> keys. Find returns a [LegacyKeyEncoding] with whether the legacy find key is mapped to the home key. Select returns a [LegacyKeyEncoding] with whether the legacy select key is mapped to the end key. func LegacyKeyEncoding.Backspace(v bool) LegacyKeyEncoding func LegacyKeyEncoding.CtrlAt(v bool) LegacyKeyEncoding func LegacyKeyEncoding.CtrlI(v bool) LegacyKeyEncoding func LegacyKeyEncoding.CtrlM(v bool) LegacyKeyEncoding func LegacyKeyEncoding.CtrlOpenBracket(v bool) LegacyKeyEncoding func LegacyKeyEncoding.Find(v bool) LegacyKeyEncoding func LegacyKeyEncoding.FKeys(v bool) LegacyKeyEncoding func LegacyKeyEncoding.Select(v bool) LegacyKeyEncoding
LightColorSchemeEvent is sent when the operating system is using a light color scheme. This is typically used to notify applications of the current or new system color scheme.
Line represents cells in a line. At returns the cell at the given x position. If the cell does not exist, it returns nil. Render renders the line to a string with all the required attributes and styles. Set sets the cell at the given x position. String returns the string representation of the line. Any trailing spaces are removed. Line : expvar.Var Line : fmt.Stringer func NewLine(width int) Line func (*Buffer).Line(y int) Line func (*StyledString).Lines(m ansi.Method) []Line
LineData represents the metadata for a line. First and last changed cell indices. First and last changed cell indices.
Lines represents a slice of lines. Height returns the height of the lines. Render renders the lines to a styled string with all the required attributes and styles. String returns the string representation of the lines. Width returns the width of the widest line. Lines : expvar.Var Lines : fmt.Stringer
Logger is a simple logger interface. ( Logger) Printf(format string, v ...interface{}) golang.org/x/net/trace.EventLog (interface) google.golang.org/grpc/grpclog.Logger (interface) google.golang.org/grpc/grpclog/internal.Logger (interface) google.golang.org/grpc/grpclog/internal.LoggerWrapper *log.Logger func (*TerminalReader).SetLogger(logger Logger) func (*TerminalRenderer).SetLogger(logger Logger)
ModeReportEvent is a message that represents a mode report event (DECRPM). See: https://vt100.net/docs/vt510-rm/DECRPM.html Mode is the mode number. Value is the mode value.
ModifyOtherKeysEvent represents a modifyOtherKeys event. 0: disable 1: enable mode 1 2: enable mode 2 See: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_ See: https://invisible-island.net/xterm/manpage/xterm.html#VT100-Widget-Resources:modifyOtherKeys Mode int
Mouse represents a Mouse message. Use [MouseEvent] to represent all mouse messages. The X and Y coordinates are zero-based, with (0,0) being the upper left corner of the terminal. When using [MouseEncodingSGRPixel] (DEC mode 1016), X and Y are in pixel coordinates; otherwise they are in cell coordinates. // Catch all mouse events switch Event := Event.(type) { case MouseEvent: m := Event.Mouse() fmt.Println("Mouse event:", m.X, m.Y, m) } // Only catch mouse click events switch Event := Event.(type) { case MouseClickEvent: fmt.Println("Mouse click event:", Event.X, Event.Y, Event) } Button MouseButton Mod KeyMod X int Y int String returns a string representation of the mouse message. Mouse : expvar.Var Mouse : fmt.Stringer func MousePixelToCell(m Mouse, ws *Winsize) Mouse func MouseClickEvent.Mouse() Mouse func MouseEvent.Mouse() Mouse func MouseMotionEvent.Mouse() Mouse func MouseReleaseEvent.Mouse() Mouse func MouseWheelEvent.Mouse() Mouse func MousePixelToCell(m Mouse, ws *Winsize) Mouse
MouseButton represents the button that was pressed during a mouse message.
MouseClickEvent represents a mouse button click event. Button MouseButton Mod KeyMod X int Y int Mouse returns the underlying mouse event. This is a convenience method and syntactic sugar to satisfy the [MouseEvent] interface, and cast the mouse event to [Mouse]. String returns a string representation of the mouse click event. MouseClickEvent : MouseEvent MouseClickEvent : expvar.Var MouseClickEvent : fmt.Stringer
MouseEncoding represents the encoding used for mouse events. func (*TerminalScreen).MouseEncoding() MouseEncoding func EncodeMouseEncoding(w io.Writer, enc MouseEncoding) error func (*TerminalScreen).SetMouseEncoding(enc MouseEncoding) const MouseEncodingLegacy const MouseEncodingSGR const MouseEncodingSGRPixel
MouseEvent represents a mouse message. This is a generic mouse message that can represent any kind of mouse event. Mouse returns the underlying mouse event. ( MouseEvent) String() string MouseClickEvent MouseMotionEvent MouseReleaseEvent MouseWheelEvent MouseEvent : expvar.Var MouseEvent : fmt.Stringer
MouseMode represents the mouse tracking mode for the terminal. func (*TerminalScreen).MouseMode() MouseMode func EncodeMouseMode(w io.Writer, mode MouseMode) error func (*TerminalScreen).SetMouseMode(mode MouseMode) const MouseModeClick const MouseModeDrag const MouseModeMotion const MouseModeNone const MouseModePress
MouseMotionEvent represents a mouse motion event. Button MouseButton Mod KeyMod X int Y int Mouse returns the underlying mouse event. This is a convenience method and syntactic sugar to satisfy the [MouseEvent] interface, and cast the mouse event to [Mouse]. String returns a string representation of the mouse motion event. MouseMotionEvent : MouseEvent MouseMotionEvent : expvar.Var MouseMotionEvent : fmt.Stringer
MouseReleaseEvent represents a mouse button release event. Button MouseButton Mod KeyMod X int Y int Mouse returns the underlying mouse event. This is a convenience method and syntactic sugar to satisfy the [MouseEvent] interface, and cast the mouse event to [Mouse]. String returns a string representation of the mouse release event. MouseReleaseEvent : MouseEvent MouseReleaseEvent : expvar.Var MouseReleaseEvent : fmt.Stringer
MouseWheelEvent represents a mouse wheel message event. Button MouseButton Mod KeyMod X int Y int Mouse returns the underlying mouse event. This is a convenience method and syntactic sugar to satisfy the [MouseEvent] interface, and cast the mouse event to [Mouse]. String returns a string representation of the mouse wheel event. MouseWheelEvent : MouseEvent MouseWheelEvent : expvar.Var MouseWheelEvent : fmt.Stringer
MultiEvent represents multiple messages event. String returns a string representation of the multiple messages event. MultiEvent : expvar.Var MultiEvent : fmt.Stringer
Options represents options for creating a new [Terminal]. BufferSize is the size of the input buffer used for reading terminal events. If zero, [DefaultBufferSize] is used. EventTimeout is the duration to wait for input events before timing out. If zero, a default of 100 milliseconds is used. LegacyKeyEncoding represents any legacy key encoding ambiguities. By default, the terminal will use its preferred key encoding settings. Logger is an optional logger for tracing terminal I/O operations. If nil, no logging is performed. LookupKeys whether to use a lookup table for common key sequences. If true, the terminal will use a lookup table to quickly identify common key sequences, reducing the need for more complex decoding logic. This can improve performance for common key sequences at the cost of increased memory usage. This is enabled by default. UseTerminfoKeys whether to use terminfo databases key definitions to build up the keys lookup table. If true, the terminal will use terminfo databases key definitions to build up the keys lookup table, which can provide more accurate key mappings for legacy non-xterm like terminals. This won't take effect if [TerminalOptions.LookupKeys] is false, since the lookup table won't be used. This is disabled by default. func DefaultOptions() *Options func NewTerminal(con Console, opts *Options) *Terminal
PasteEndEvent is an message that is emitted when the terminal ends the bracketed-paste text.
PasteEvent is an message that is emitted when a terminal receives pasted text using bracketed-paste. Content is the pasted text content. String returns the pasted content as a string. PasteEvent : expvar.Var PasteEvent : fmt.Stringer
PasteStartEvent is an message that is emitted when the terminal starts the bracketed-paste text.
PixelSizeEvent represents the window size in pixels. Height int Width int Bounds returns the bounds corresponding to the size.
Position represents a position in a coordinate system.
PrimaryDeviceAttributesEvent is an event that represents the terminal primary device attributes. Common attributes include: - 1 132 columns - 2 Printer port - 4 Sixel - 6 Selective erase - 7 Soft character set (DRCS) - 8 User-defined keys (UDKs) - 9 National replacement character sets (NRCS) (International terminal only) - 12 Yugoslavian (SCS) - 15 Technical character set - 18 Windowing capability - 21 Horizontal scrolling - 23 Greek - 24 Turkish - 42 ISO Latin-2 character set - 44 PCTerm - 45 Soft key map - 46 ASCII emulation See [ansi.PrimaryDeviceAttributes] for more details.
ProgressBar represents the terminal progress bar. Support depends on the terminal. See https://learn.microsoft.com/en-us/windows/terminal/tutorials/progress-bar-sequences State is the current state of the progress bar. It can be one of [ProgressBarNone], [ProgressBarDefault], [ProgressBarError], [ProgressBarIndeterminate], and [ProgressBarWarning]. Value is the current value of the progress bar. It should be between 0 and 100. func NewProgressBar(state ProgressBarState, value int) *ProgressBar func (*TerminalScreen).ProgressBar() *ProgressBar func EncodeProgressBar(w io.Writer, pb *ProgressBar) error func (*TerminalScreen).SetProgressBar(pb *ProgressBar)
ProgressBarState represents the state of the progress bar. String return a human-readable value for the given [ProgressBarState]. ProgressBarState : expvar.Var ProgressBarState : fmt.Stringer func NewProgressBar(state ProgressBarState, value int) *ProgressBar const ProgressBarDefault const ProgressBarError const ProgressBarIndeterminate const ProgressBarNone const ProgressBarWarning
Rectangle represents a rectangular area.
RenderBuffer represents a buffer that keeps track of the current and new state of the screen, allowing for efficient rendering by only updating the parts of the screen that have changed. Buffer *Buffer Lines is a slice of lines that make up the cells of the buffer. Touched []*LineData Bounds returns the bounds of the buffer. The origin is always at (0, 0) and the maximum coordinates are determined by the width and height of the buffer. CellAt returns the cell at the given position. It returns nil if the position is out of bounds. Clear clears the buffer with space cells and marks all lines as touched. ClearArea clears the buffer with space cells within the specified rectangle and marks the affected lines as touched. Clone clones the entire buffer into a new buffer. CloneArea clones the area of the buffer within the specified rectangle. If the area is out of bounds, it returns nil. DeleteCell deletes cells at the given position, with the given optional cell, within the specified rectangles. If no rectangles are specified, it deletes cells in the entire buffer. This follows terminal [ansi.DCH] behavior. DeleteCellArea deletes cells at the given position, with the given optional cell, within the rectangle bounds. Only cells within the rectangle's bounds are affected, following terminal [ansi.DCH] behavior. DeleteLine deletes n lines at the given line position, with the given optional cell, within the specified rectangles. If no rectangles are specified, it deletes lines in the entire buffer. DeleteLineArea deletes lines at the given line position, with the given optional cell, within the rectangle bounds. Only cells within the rectangle's bounds are affected. Lines are shifted up within the bounds and new blank lines are created at the bottom. This follows terminal [ansi.DL] behavior. Draw draws the buffer to the given screen at the specified area. It implements the [Drawable] interface. Fill fills the buffer with the given cell and marks all lines as touched. FillArea fills the buffer with the given cell within the specified rectangle and marks the affected lines as touched. Height implements Screen. InsertCell inserts new cells at the given position, with the given optional cell, within the specified rectangles. If no rectangles are specified, it inserts cells in the entire buffer. This follows terminal [ansi.ICH] behavior. InsertCellArea inserts new cells at the given position, with the given optional cell, within the rectangle bounds. Only cells within the rectangle's bounds are affected, following terminal [ansi.ICH] behavior. InsertLine inserts n lines at the given line position, with the given optional cell, within the specified rectangles. If no rectangles are specified, it inserts lines in the entire buffer. Only cells within the rectangle's horizontal bounds are affected. Lines are pushed out of the rectangle bounds and lost. This follows terminal [ansi.IL] behavior. InsertLineArea inserts new lines at the given line position, with the given optional cell, within the rectangle bounds. Only cells within the rectangle's horizontal bounds are affected. Lines are pushed out of the rectangle bounds and lost. This follows terminal [ansi.IL] behavior. Line returns a pointer to the line at the given y position. If the line does not exist, it returns nil. Render renders the buffer to a styled string with all the required attributes and styles. Resize resizes the buffer to the given width and height. SetCell sets the cell at the given x, y position and marks the line as touched. String returns the string representation of the buffer. Touch marks the cell at the given x, y position as touched. TouchLine marks a line n times starting at the given x position as touched. TouchedLines returns the number of touched lines in the buffer. Width implements Screen. RenderBuffer : Drawable RenderBuffer : expvar.Var RenderBuffer : fmt.Stringer func NewRenderBuffer(width, height int) *RenderBuffer func (*TerminalRenderer).PrependString(newbuf *RenderBuffer, str string) func (*TerminalRenderer).Redraw(newbuf *RenderBuffer) func (*TerminalRenderer).Render(newbuf *RenderBuffer)
Screen represents a screen that can be drawn to. Bounds returns the bounds of the screen. This is the rectangle that includes the start and end points of the screen. CellAt returns the cell at the given position. If the position is out of bounds, it returns nil. Otherwise, it always returns a cell, even if it is empty (i.e., a cell with a space character and a width of 1). SetCell sets the cell at the given position. A nil cell is treated as an empty cell with a space character and a width of 1. WidthMethod returns the width method used by the screen. ScreenBuffer *TerminalScreen *Window *charm.land/lipgloss/v2.Canvas func (*Border).Draw(scr Screen, area Rectangle) func (*Buffer).Draw(scr Screen, area Rectangle) func Drawable.Draw(scr Screen, area Rectangle) func DrawableFunc.Draw(scr Screen, rect Rectangle) func (*StyledString).Draw(buf Screen, area Rectangle) func charm.land/lipgloss/v2.(*Canvas).Draw(scr Screen, area Rectangle) func charm.land/lipgloss/v2.(*Compositor).Draw(scr Screen, area image.Rectangle) func charm.land/lipgloss/v2.(*Layer).Draw(scr Screen, area Rectangle)
ScreenBuffer is a buffer that can be used as a [Screen]. Method ansi.Method RenderBuffer *RenderBuffer RenderBuffer.Buffer *Buffer Lines is a slice of lines that make up the cells of the buffer. RenderBuffer.Touched []*LineData Bounds returns the bounds of the buffer. The origin is always at (0, 0) and the maximum coordinates are determined by the width and height of the buffer. CellAt returns the cell at the given position. It returns nil if the position is out of bounds. Clear clears the buffer with space cells and marks all lines as touched. ClearArea clears the buffer with space cells within the specified rectangle and marks the affected lines as touched. Clone clones the entire buffer into a new buffer. CloneArea clones the area of the buffer within the specified rectangle. If the area is out of bounds, it returns nil. DeleteCell deletes cells at the given position, with the given optional cell, within the specified rectangles. If no rectangles are specified, it deletes cells in the entire buffer. This follows terminal [ansi.DCH] behavior. DeleteCellArea deletes cells at the given position, with the given optional cell, within the rectangle bounds. Only cells within the rectangle's bounds are affected, following terminal [ansi.DCH] behavior. DeleteLine deletes n lines at the given line position, with the given optional cell, within the specified rectangles. If no rectangles are specified, it deletes lines in the entire buffer. DeleteLineArea deletes lines at the given line position, with the given optional cell, within the rectangle bounds. Only cells within the rectangle's bounds are affected. Lines are shifted up within the bounds and new blank lines are created at the bottom. This follows terminal [ansi.DL] behavior. Draw draws the buffer to the given screen at the specified area. It implements the [Drawable] interface. Fill fills the buffer with the given cell and marks all lines as touched. FillArea fills the buffer with the given cell within the specified rectangle and marks the affected lines as touched. Height implements Screen. InsertCell inserts new cells at the given position, with the given optional cell, within the specified rectangles. If no rectangles are specified, it inserts cells in the entire buffer. This follows terminal [ansi.ICH] behavior. InsertCellArea inserts new cells at the given position, with the given optional cell, within the rectangle bounds. Only cells within the rectangle's bounds are affected, following terminal [ansi.ICH] behavior. InsertLine inserts n lines at the given line position, with the given optional cell, within the specified rectangles. If no rectangles are specified, it inserts lines in the entire buffer. Only cells within the rectangle's horizontal bounds are affected. Lines are pushed out of the rectangle bounds and lost. This follows terminal [ansi.IL] behavior. InsertLineArea inserts new lines at the given line position, with the given optional cell, within the rectangle bounds. Only cells within the rectangle's horizontal bounds are affected. Lines are pushed out of the rectangle bounds and lost. This follows terminal [ansi.IL] behavior. Line returns a pointer to the line at the given y position. If the line does not exist, it returns nil. Render renders the buffer to a styled string with all the required attributes and styles. Resize resizes the buffer to the given width and height. SetCell sets the cell at the given x, y position and marks the line as touched. String returns the string representation of the buffer. Touch marks the cell at the given x, y position as touched. TouchLine marks a line n times starting at the given x position as touched. TouchedLines returns the number of touched lines in the buffer. Width implements Screen. WidthMethod returns the width method used by the screen. It defaults to [ansi.WcWidth]. ScreenBuffer : Drawable ScreenBuffer : Screen ScreenBuffer : expvar.Var ScreenBuffer : fmt.Stringer func NewScreenBuffer(width, height int) ScreenBuffer
SecondaryDeviceAttributesEvent is an event that represents the terminal secondary device attributes. See [ansi.SecondaryDeviceAttributes] for more details.
Side represents a single border side with its properties. Content string Link Link Link.Params string Link.URL string Style Style Style.Attrs uint8 Style.Bg color.Color Style.Fg color.Color Style.Underline Underline Style.UnderlineColor color.Color Diff returns the ANSI sequence that sets the style as a diff from another style. Styled wraps the given string with the style's ANSI sequences and resets.
Size represents the size of the terminal window. Height int Width int Bounds returns the bounds corresponding to the size. func (*SizeNotifier).GetWindowSize() (cells Size, pixels Size, err error) func (*SizeNotifier).GetWindowSize() (cells Size, pixels Size, err error)
SizeNotifier represents a notifier that listens for window size changes using the SIGWINCH signal and notifies the given channel. Channel that receives terminal size change notifications. GetSize returns the current cell size of the terminal window. GetWindowSize returns the current size of the terminal window. Start starts listening for window size changes and notifies [SizeNotifier.C] about any changes. Stop stops the notifier and cleans up resources. func NewSizeNotifier(f term.File) *SizeNotifier
Style represents the style of a cell. Attrs uint8 Bg color.Color Fg color.Color Underline Underline UnderlineColor color.Color Diff returns the ANSI sequence that sets the style as a diff from another style. Equal returns true if the style is equal to the other style. IsZero returns true if the style is empty. String returns the ANSI SGR sequence for the style. Styled wraps the given string with the style's ANSI sequences and resets. *Style : expvar.Var *Style : fmt.Stringer func ConvertStyle(s Style, p colorprofile.Profile) Style func charm.land/lipgloss/v2.(*WrapWriter).Style() Style func ConvertStyle(s Style, p colorprofile.Profile) Style func ReadStyle(params ansi.Params, pen *Style) func StyleDiff(from, to *Style) string func Border.Style(style Style) Border func (*Style).Diff(from *Style) string func (*Style).Equal(o *Style) bool
StyledString is a string that can be decomposed into a series of styled lines and cells. It is used to disassemble a rendered string with ANSI escape codes into a series of cells that can be used in a [Buffer]. A StyledString supports reading [ansi.SGR] and [ansi.Hyperlink] escape codes. Tail is the string that will be appended to the end of the line when the string is truncated i.e. when [StyledString.Wrap] is false. Text is the original string that was used to create the styled string. Wrap determines whether the styled string should wrap to the next line. Bounds returns the minimum area that can contain the whole styled string. Draw renders the styled string to the given buffer at the specified area. Height returns the number of lines in the styled string. This is the number of lines that the styled string will occupy when rendered to the screen. Lines returns the styled string decomposed into a slice of [Line]s. String returns the text of the styled string. It implements the [fmt.Stringer] interface. UnicodeWidth returns the cells width of the widest line in the styled string using the [ansi.GraphemeWidth] method. WcWidth returns the cells width of the widest line in the styled string using the [ansi.WcWidth] method. *StyledString : Drawable *StyledString : expvar.Var *StyledString : fmt.Stringer func NewStyledString(str string) *StyledString
TabStops represents horizontal line tab stops. Clear removes all tab stops. Find returns the prev/next tab stop before/after the given column and delta. If delta is positive, it returns the next tab stop after the given column. If delta is negative, it returns the previous tab stop before the given column. If delta is zero, it returns the given column. IsStop returns true if the given column is a tab stop. Next returns the next tab stop after the given column. Prev returns the previous tab stop before the given column. Reset removes the tab stop at the given column. Resize resizes the tab stops to the given width. Set adds a tab stop at the given column. Width returns the width of the screen that the tab stops are set for. func DefaultTabStops(cols int) *TabStops func NewTabStops(width, interval int) *TabStops
Terminal represents an interactive terminal application. Events returns the terminal's event channel. GetSize returns the current size of the terminal in characters and pixels. GetWinsize returns the current size of the terminal as a [Winsize] struct. This includes both character dimensions (columns and rows) and pixel dimensions (xpixel and ypixel). Note that this only returns the pixel dimensions on Unix-like systems that support the TIOCGWINSZ ioctl. On other platforms, the pixel dimensions may be zero or not available. Read reads data from the terminal's console input. This is a low-level operation that bypasses the terminal event processing and reads directly from the console input handler, usually [os.Stdin] or the controlling TTY. Use this method with caution, as it may interfere with the terminal's event loop and screen management. Screen returns the terminal's screen. SendEvent sends an event to the terminal's event channel. This can be used to inject custom events into the terminal's event loop, such as timer events, signals, or application-specific events. Start starts the terminal application event loop. This is a non-blocking call. Use [Terminal.Wait] to wait for the terminal to exit. Stop stops the terminal event loop. It is safe to call Stop without a prior [Terminal.Start], and safe to call Stop multiple times in a row. After Stop returns, [Terminal.Start] may be called again to resume. Wait waits for the terminal event loop to exit and returns any error that occurred. Write writes data directly to the terminal's console output. This is a low-level operation that bypasses the terminal screen buffering and writes directly to the console output handler, usually [os.Stdout] or the controlling TTY. *Terminal : internal/bisect.Writer *Terminal : io.Reader *Terminal : io.ReadWriter *Terminal : io.Writer func ControllingTerminal() (*Terminal, error) func DefaultTerminal() *Terminal func NewTerminal(con Console, opts *Options) *Terminal
TerminalReader represents an input event loop that reads input events from a reader and parses them into human-readable events. It supports reading escape sequences, mouse events, and bracketed paste mode. EscTimeout is the escape character timeout duration. Most escape sequences start with an escape character [ansi.ESC] and are followed by one or more characters. If the next character is not received within this timeout, the reader will assume that the escape sequence is complete and will process the received characters as a complete escape sequence. By default, this is set to [DefaultEscTimeout] (50 milliseconds). EventDecoder EventDecoder Legacy is the legacy key encoding flags. These flags control the behavior of legacy terminal key encodings. See [LegacyKeyEncoding] for more details. UseTerminfo is a flag that controls whether to use the terminal type Terminfo database to map escape sequences to key events. This will override the default key sequences handled by the parser. MouseMode determines whether mouse events are enabled or not. This is a platform-specific feature and is only available on Windows. When this is true, the reader will be initialized to read mouse events using the Windows Console API. Decode finds the first recognized event sequence and returns it along with its length. It will return zero and nil no sequence is recognized or when the buffer is empty. If a sequence is not supported, an [UnknownEvent] is returned. Example: ```go var decoder EventDecoder var events []Event buf := []byte("\x00" + // Ctrl+Space "\x1b[A" + // Up arrow "Hello") // Text input for len(buf) > 0 { n, ev := decoder.Decode(buf) if ev != nil { events = append(events, ev) } buf = buf[n:] } ``` SetLogger sets the logger to use for debugging. If nil, no logging will be performed. StreamEvents sends events to the provided channel. It stops when the context is closed or when an error occurs. *TerminalReader : EventStreamer func NewTerminalReader(r io.Reader, termType string) *TerminalReader
TerminalRenderer is a terminal screen render and lazy writer that buffers the output until it is flushed. It handles rendering a screen from a [Buffer] to the terminal with the minimal necessary escape sequences to transition the terminal to the new buffer state. It uses various escape sequence optimizations to reduce the number of bytes sent to the terminal. It's designed to be lazy and only flush the output when necessary by calling the [TerminalRenderer.Flush] method. The renderer handles the terminal's alternate screen and cursor visibility via the [TerminalRenderer.EnterAltScreen], [TerminalRenderer.ExitAltScreen], [TerminalRenderer.ShowCursor] and [TerminalRenderer.HideCursor] methods. Using these methods will queue the appropriate escape sequences to enter or exit the alternate screen and show or hide the cursor respectively to be flushed to the terminal. Use the [io.Writer] and [io.StringWriter] interfaces to queue custom commands the renderer. The renderer is not thread-safe, the caller must protect the renderer when using it from multiple goroutines. Buffered returns the number of bytes buffered for the next flush. EnterAltScreen is a helper that queues the [ansi.ModeAltScreenSaveCursor] escape sequence to enter the alternate screen buffer and save cursor mode. It saves the current cursor properties, enables [TerminalRenderer.SetFullscreen] flag, and disables [TerminalRenderer.SetRelativeCursor] flag. On the next call to [TerminalRenderer.Render], it will move the cursor home and clear the screen to prepare for rendering the new buffer. Note: you might want to reapply the cursor visibility state after calling this method, as some terminals reset the cursor visibility when switching to the alternate screen. Erase marks the screen to be fully erased on the next render. ExitAltScreen is a helper that queues the [ansi.ModeAltScreenSaveCursor] escape sequence to exit the alternate screen buffer and restore cursor mode. It restores the saved cursor properties, disables [TerminalRenderer.SetFullscreen] flag, and enables [TerminalRenderer.SetRelativeCursor] flag. On the next call to [TerminalRenderer.Render], it will move the cursor to the first line and clear everything below the cursor to prepare for rendering the new buffer. Note: you might want to reapply the cursor visibility state after calling this method, as some terminals reset the cursor visibility when switching to the alternate screen. Flush flushes the buffer to the screen. Fullscreen returns whether whole screen is being used. This is usually paired with the alternate screen mode, and used to control cursor movements and optimizations when the terminal is occupying the whole screen. MoveTo calculates and writes the shortest sequence to move the cursor to the given position. It uses the current cursor position and the new position to calculate the shortest amount of sequences to move the cursor. Position returns the cursor position in the screen buffer after applying any pending transformations from the underlying buffer. PrependString adds the lines of the given string to the top of the terminal screen. The lines prepended are not managed by the renderer and will not be cleared or updated by the renderer. Using this when the terminal is using the alternate screen or when occupying the whole screen may not produce any visible effects. This is because once the terminal writes the prepended lines, they will get overwritten by the next frame. Redraw forces a full redraw of the screen. It's equivalent to calling [TerminalRenderer.Erase] and [TerminalRenderer.Render]. Render renders changes of the screen to the internal buffer. Call [terminalWriter.Flush] to flush pending changes to the screen. Resize updates the terminal screen tab stops. This is used to calculate terminal tab stops for hard tab optimizations. Resize also invalidates the cursor model when the renderer can recover from it: a terminal may move the cursor on any resize, so the remembered position no longer matches reality, and the next move will be absolute. In relative cursor mode there is no absolute move to fall back on, and -1 there means "first move, assume the origin" rather than "unknown", so invalidating would assert a position instead of forgetting one. Keep the old model in that mode and let the next render diff against it. RestoreCursor restores the saved cursor position and styles. This can be used when a program exits the alternate screen buffer mode using DECRST 1049 [ansi.ModeAltScreenSaveCursor] and wants to restore the cursor position and styles saved earlier. SaveCursor saves the current cursor position and styles. This can be used when a program enters the alternate screen buffer mode using DECSET 1049 [ansi.ModeAltScreenSaveCursor] and wants to restore the cursor position and styles later. SetBackspace sets whether to use backspace as a movement optimization. SetColorProfile sets the color profile to use for downsampling colors. This is used to determine the appropriate color the terminal can display. SetFullscreen sets whether whole screen is being used. This is usually paired with the alternate screen mode, and used to control cursor movements and optimizations when the terminal is occupying the whole screen. SetGraphemeWidth sets whether the terminal measures cell width using Unicode grapheme clustering (DEC mode 2027 / Unicode core). When enabled, the renderer measures string width using [ansi.GraphemeWidth]; otherwise it falls back to [ansi.WcWidth]. SetLogger sets the logger to use for debugging. If nil, no logging will be performed. SetMapNewline sets whether the terminal is currently mapping newlines to CRLF or carriage return and line feed. This is used to correctly determine how to move the cursor when writing to the screen. SetPosition changes the logical cursor position. This can be used when we change the cursor position outside of the screen and need to update the screen cursor position. This changes the cursor position for both normal and alternate screen buffers. SetRelativeCursor sets whether to use relative cursor movements. SetScrollOptim sets whether to use hard scroll optimizations. SetTabStops sets the tab stops for the terminal and enables hard tabs movement optimizations. Use -1 to disable hard tabs. This option is ignored when the terminal type is "linux" as it does not support hard tabs. SetWidthMethod sets the width method the renderer uses to measure the display width of strings. This should match the width method configured on the screen so that the renderer doesn't disagree with the cell widths it is asked to draw. Write writes the given bytes to the underlying buffer. WriteString writes the given string to the underlying buffer. *TerminalRenderer : internal/bisect.Writer *TerminalRenderer : io.StringWriter *TerminalRenderer : io.Writer func NewTerminalRenderer(w io.Writer, env []string) (s *TerminalRenderer)
TerminalScreen represents a terminal screen, providing methods for managing the screen state and rendering content. AltScreen returns whether the terminal is currently in the alternate screen buffer. BackgroundColor returns the current background color of the terminal. A nil color indicates that the background color is the default terminal background color. Bounds returns the bounds of the terminal screen as a rectangle. BracketedPaste returns whether bracketed paste mode is currently enabled. CellAt returns the cell at the specified x and y coordinates. CursorColor returns the current color of the terminal cursor. A nil color indicates that the cursor color is the default terminal cursor color. CursorPosition returns the last set cursor position of the terminal. If the cursor position is not set, it returns (-1, -1). This can be affected by [TerminalScreen.Render] and [TerminalScreen.SetCursorPosition] calls. CursorStyle returns the current style of the terminal cursor. CursorVisible returns whether the terminal cursor is currently visible. DisableBracketedPaste disables bracketed paste mode. The changes can be committed to the underlying writer by calling the [TerminalScreen.Flush] method. Display clears the screen and draws the given [Drawable] onto the terminal screen and flushes the changes to the underlying writer. This is a convenience method that combines [TerminalScreen.Render] and [TerminalScreen.Flush]. EnableBracketedPaste enables bracketed paste mode, allowing the terminal to distinguish between pasted content and user input. The changes can be committed to the underlying writer by calling the [TerminalScreen.Flush] method. EnterAltScreen switches the terminal to the alternate screen buffer, allowing applications to use a separate screen for their output without affecting the main screen. The changes can be committed to the underlying writer by calling the [TerminalScreen.Flush] method. ExitAltScreen switches the terminal back to the main screen buffer, restoring the previous screen state. The changes can be committed to the underlying writer by calling the [TerminalScreen.Flush] method. Flush writes any pending output to the underlying writer. ForegroundColor returns the current foreground color of the terminal. A nil color indicates that the foreground color is the default terminal foreground color. Height returns the height of the terminal screen. Note that this is not the actual height of the terminal window, but rather the height of the screen we're managing. The actual height of the terminal window can be obtained using [Terminal.GetSize] or by reading the "LINES" environment variable. HideCursor hides the terminal cursor. The changes can be committed to the underlying writer by calling the [TerminalScreen.Flush] method. InsertAbove inserts content above the screen pushing the current content down. This is useful for inserting content above the current screen content without affecting the current cursor position or screen state. Note that this won't have any visible effect if the screen is in alt screen mode, as the content will be inserted above the alt screen buffer, which is not visible. However, if the screen is in inline mode, the content will be inserted above and will not be managed by the renderer. Unlike other methods that modify the screen state, this method writes directly to the underlying writer, so there is no need to call [TerminalScreen.Flush] after calling this method. KeyboardEnhancements returns the current keyboard enhancements of the terminal. A nil value indicates that no keyboard enhancements are currently enabled. MouseEncoding returns the current mouse encoding of the terminal. MouseMode returns the current mouse tracking mode of the terminal. ProgressBar returns the current progress bar of the terminal. A nil value indicates that no progress bar is currently set. Render renders changes that transform the screen from its current state to the state represented by the [TerminalScreen]. The changes can be committed to the underlying writer by calling the [TerminalScreen.Flush] method. Reset resets the terminal screen to its default state, clearing the screen, switching back to the main screen buffer if necessary, and resetting all terminal settings to their defaults. The changes can be committed to the underlying writer by calling the [TerminalScreen.Flush] method. Resize resizes the terminal screen to the specified width and height, updating the render buffer and renderer accordingly. Restore restores the terminal screen to its previous state, applying any previous settings and state that were reset by the [TerminalScreen.Reset] method. The changes can be committed to the underlying writer by calling the [TerminalScreen.Flush] method. SetBackgroundColor sets the background color of the terminal. The changes can be committed to the underlying writer by calling the [TerminalScreen.Flush] method. SetCell sets the cell at the specified x and y coordinates. SetColorProfile sets the color profile for the terminal screen. This is automatically detected when creating the terminal screen. However, you can override it using this method. SetCursorColor sets the color of the terminal cursor. The changes can be committed to the underlying writer by calling the [TerminalScreen.Flush] method. SetCursorPosition sets the position of the terminal cursor to the specified coordinates. The changes can be committed to the underlying writer by calling the [TerminalScreen.Flush] method. SetCursorStyle sets the style of the terminal cursor. The changes can be committed to the underlying writer by calling the [TerminalScreen.Flush] method. SetForegroundColor sets the foreground color of the terminal. The changes can be committed to the underlying writer by calling the [TerminalScreen.Flush] method. SetKeyboardEnhancements sets the keyboard enhancements for the terminal, allowing applications to receive enhanced keyboard input. The changes can be committed to the underlying writer by calling the [TerminalScreen.Flush] method. SetMouseEncoding sets the mouse encoding for the terminal. The encoding determines how mouse coordinates and buttons are reported. This is only meaningful when mouse tracking is enabled via [TerminalScreen.SetMouseMode]. The changes can be committed to the underlying writer by calling the [TerminalScreen.Flush] method. SetMouseMode sets the mouse tracking mode for the terminal, allowing applications to receive mouse events. The changes can be committed to the underlying writer by calling the [TerminalScreen.Flush] method. SetProgressBar sets the progress bar for the terminal, allowing applications to display progress information. The changes can be committed to the underlying writer by calling the [TerminalScreen.Flush] method. SetSynchronizedUpdates sets whether to use synchronized updates (mode 2026), which allows applications to batch updates to the terminal screen and flush them all at once for improved performance. The changes can be committed to the underlying writer by calling the [TerminalScreen.Flush] method. SetWidthMethod sets the width method for the terminal screen. This is an override that propagates to the window/buffer and the renderer so that all width measurements use the same method. Calling this marks the width method as explicitly overridden, which disables automatic mode-2027 negotiation. SetWindowTitle sets the title of the terminal window. The changes can be committed to the underlying writer by calling the [TerminalScreen.Flush] method. ShowCursor shows the terminal cursor. The changes can be committed to the underlying writer by calling the [TerminalScreen.Flush] method. StringWidth returns the cell width of the given string using the terminal screen's width method. This accounts for the configured [WidthMethod] (e.g. wcwidth vs grapheme width) so callers don't need to import ansi directly. SynchronizedUpdates returns whether synchronized updates (mode 2026) are currently enabled. Width returns the width of the terminal screen. Note that this is not the actual width of the terminal window, but rather the width of the screen we're managing. The actual width of the terminal window can be obtained using [Terminal.GetSize] or by reading the "COLUMNS" environment variable. WidthMethod returns the width method used by the terminal screen. WindowTitle returns the current title of the terminal window. Write writes data to the underlying buffer queuing it for output. The changes can be committed to the underlying writer by calling the [TerminalScreen.Flush] method. WriteString writes a string to the underlying buffer queuing it for output. The changes can be committed to the underlying writer by calling the [TerminalScreen.Flush] method. *TerminalScreen : Screen *TerminalScreen : WidthMethod *TerminalScreen : internal/bisect.Writer *TerminalScreen : io.StringWriter *TerminalScreen : io.Writer func NewTerminalScreen(w io.Writer, env Environ) *TerminalScreen func (*Terminal).Screen() *TerminalScreen
TerminalVersionEvent is a message that represents the terminal version. Name string String returns the terminal version as a string. TerminalVersionEvent : expvar.Var TerminalVersionEvent : fmt.Stringer
TertiaryDeviceAttributesEvent is an event that represents the terminal tertiary device attributes. See [ansi.TertiaryDeviceAttributes] for more details.
TTY represents a Unix TTY device. It implements the [Console] interface. Close restores the console to its previous state and releases resources. Environ returns the console's environment variables. GetSize returns the current size of the console. GetWinsize returns the current size of the console in cells and pixels. Getenv retrieves the value of the environment variable named by the key. LookupEnv retrieves the value of the environment variable named by the key and a boolean indicating whether the variable is present. MakeRaw puts the console input side into raw mode. Read reads data from the console's input. Reader returns the input reader of the console. Restore restores the console to its previous state. Write writes data to the console's output. Writer returns the output writer of the console. TTY : Console TTY : internal/bisect.Writer TTY : io.Closer TTY : io.ReadCloser TTY : io.Reader TTY : io.ReadWriteCloser TTY : io.ReadWriter TTY : io.WriteCloser TTY : io.Writer
Underline is the style of underline to use for text.
UnderlineStyle is the style of underline to use for text. Deprecated: Use [Underline] instead.
UnknownApcEvent represents an unknown APC (Application Program Command) event. String returns a string representation of the unknown APC event. UnknownApcEvent : expvar.Var UnknownApcEvent : fmt.Stringer
UnknownCsiEvent represents an unknown CSI (Control Sequence Introducer) event. String returns a string representation of the unknown CSI event. UnknownCsiEvent : expvar.Var UnknownCsiEvent : fmt.Stringer
UnknownDcsEvent represents an unknown DCS (Device Control String) event. String returns a string representation of the unknown DCS event. UnknownDcsEvent : expvar.Var UnknownDcsEvent : fmt.Stringer
UnknownEvent represents an unknown event. String returns a string representation of the unknown event. UnknownEvent : expvar.Var UnknownEvent : fmt.Stringer
UnknownOscEvent represents an unknown OSC (Operating System Command) event. String returns a string representation of the unknown OSC event. UnknownOscEvent : expvar.Var UnknownOscEvent : fmt.Stringer
UnknownPmEvent represents an unknown PM (Privacy Message) event. String returns a string representation of the unknown PM event. UnknownPmEvent : expvar.Var UnknownPmEvent : fmt.Stringer
UnknownSosEvent represents an unknown SOS (Start of String) event. String returns a string representation of the unknown SOS event. UnknownSosEvent : expvar.Var UnknownSosEvent : fmt.Stringer
UnknownSs3Event represents an unknown SS3 (Single Shift 3) event. String returns a string representation of the unknown SS3 event. UnknownSs3Event : expvar.Var UnknownSs3Event : fmt.Stringer
WidthMethod determines how many columns a grapheme occupies on the screen. ( WidthMethod) StringWidth(s string) int *TerminalScreen github.com/charmbracelet/x/ansi.Method *github.com/mattn/go-runewidth.Condition func Screen.WidthMethod() WidthMethod func ScreenBuffer.WidthMethod() WidthMethod func (*TerminalScreen).WidthMethod() WidthMethod func (*Window).WidthMethod() WidthMethod func charm.land/lipgloss/v2.(*Canvas).WidthMethod() WidthMethod func NewCell(method WidthMethod, gr string) *Cell func NewWindow(width, height int, method WidthMethod) *Window func (*Window).SetWidthMethod(method WidthMethod)
WinCon represents a Windows Console. It implements the [Console] interface. Close restores the console to its previous state and releases resources. Environ returns the console's environment variables. GetSize returns the current size of the console. GetWinsize returns the current size of the console in cells and pixels. Getenv retrieves the value of the environment variable named by the key. LookupEnv retrieves the value of the environment variable named by the key and a boolean indicating whether the variable is present. MakeRaw puts the console input side into raw mode. Read reads data from the console's input. Reader returns the input reader of the console. Restore restores the console to its previous state. Write writes data to the console's output. Writer returns the output writer of the console. WinCon : Console WinCon : internal/bisect.Writer WinCon : io.Closer WinCon : io.ReadCloser WinCon : io.Reader WinCon : io.ReadWriteCloser WinCon : io.ReadWriter WinCon : io.WriteCloser WinCon : io.Writer
Window represents a rectangular area on the screen. It can be a root window with no parent, or a sub-window with a parent window. A window can have its own buffer or share the buffer of its parent window (view). Buffer *Buffer Lines is a slice of lines that make up the cells of the buffer. Bounds returns the bounds of the window as a rectangle. CellAt returns the cell at the given position. It returns nil if the position is out of bounds. Clear clears the buffer with space cells and rectangle. ClearArea clears the buffer with space cells within the specified rectangles. Only cells within the rectangle's bounds are affected. Clone creates an exact copy of the window, including its buffer and values. The cloned window will have the same parent and method as the original window. CloneArea creates an exact copy of the window, including its buffer and values, but only within the specified area. The cloned window will have the same parent and method as the original window, but its bounds will be limited to the specified area. DeleteCell deletes cells at the given position, with the given optional cell, within the specified rectangles. If no rectangles are specified, it deletes cells in the entire buffer. This follows terminal [ansi.DCH] behavior. DeleteCellArea deletes cells at the given position, with the given optional cell, within the rectangle bounds. Only cells within the rectangle's bounds are affected, following terminal [ansi.DCH] behavior. DeleteLine deletes n lines at the given line position, with the given optional cell, within the specified rectangles. If no rectangles are specified, it deletes lines in the entire buffer. DeleteLineArea deletes lines at the given line position, with the given optional cell, within the rectangle bounds. Only cells within the rectangle's bounds are affected. Lines are shifted up within the bounds and new blank lines are created at the bottom. This follows terminal [ansi.DL] behavior. Draw draws the buffer to the given screen at the specified area. It implements the [Drawable] interface. Fill fills the buffer with the given cell and rectangle. FillArea fills the buffer with the given cell and rectangle. HasParent returns whether the window has a parent window. This can be used to determine if the window is a root window or a sub-window. Height implements Screen. InsertCell inserts new cells at the given position, with the given optional cell, within the specified rectangles. If no rectangles are specified, it inserts cells in the entire buffer. This follows terminal [ansi.ICH] behavior. InsertCellArea inserts new cells at the given position, with the given optional cell, within the rectangle bounds. Only cells within the rectangle's bounds are affected, following terminal [ansi.ICH] behavior. InsertLine inserts n lines at the given line position, with the given optional cell, within the specified rectangles. If no rectangles are specified, it inserts lines in the entire buffer. Only cells within the rectangle's horizontal bounds are affected. Lines are pushed out of the rectangle bounds and lost. This follows terminal [ansi.IL] behavior. It returns the pushed out lines. InsertLineArea inserts new lines at the given line position, with the given optional cell, within the rectangle bounds. Only cells within the rectangle's horizontal bounds are affected. Lines are pushed out of the rectangle bounds and lost. This follows terminal [ansi.IL] behavior. Line returns a pointer to the line at the given y position. If the line does not exist, it returns nil. MoveBy moves the window by the specified delta x and delta y. MoveTo moves the window to the specified x and y coordinates. NewView creates a new view into the parent window at the specified position and size. Unlike [Window.NewWindow], this view shares the same buffer as the parent window. NewWindow creates a new window with its own buffer relative to the parent window at the specified position and size. This will panic if width or height is negative. Parent returns the parent window of the current window. If the window does not have a parent, it returns nil. Render renders the buffer to a styled string with all the required attributes and styles. Resize resizes the window to the specified width and height. SetCell sets the cell at the given x, y position. SetWidthMethod sets the width method for the window. String returns the string representation of the buffer. Width implements Screen. WidthMethod returns the method used to calculate the width of characters in the window. Window : Drawable *Window : Screen Window : expvar.Var Window : fmt.Stringer func NewWindow(width, height int, method WidthMethod) *Window func (*Window).Clone() *Window func (*Window).CloneArea(area Rectangle) *Window func (*Window).NewView(x, y, width, height int) *Window func (*Window).NewWindow(x, y, width, height int) *Window func (*Window).Parent() *Window
WindowOpEvent is a window operation (XTWINOPS) report event. This is used to report various window operations such as reporting the window size or cell size. Args []int Op int
WindowSizeEvent represents the window size in cells. Height int Width int Bounds returns the bounds corresponding to the size.
Winsize represents the size of a terminal in cells and pixels. This is the same as [unix.Winsize], but defined here for cross-platform compatibility. Col uint16 Row uint16 Xpixel uint16 Ypixel uint16 func Console.GetWinsize() (*Winsize, error) func (*Terminal).GetWinsize() (*Winsize, error) func MousePixelToCell(m Mouse, ws *Winsize) Mouse
Package-Level Functions (total 113, in which 58 are exported)
ASCIIBorder returns a table border with ASCII characters.
BlockBorder returns a border that takes the whole block.
ControllingConsole returns a new console instance that uses the current controlling terminal's input and output file descriptors.
ControllingTerminal creates a new [Terminal] instance using the controlling terminal's input and output file descriptors. Options can be nil to use the default options. This is a convenience function for creating a terminal that uses the controlling TTY of the current process.
ConvertStyle converts a style to respect the given color profile.
DefaultConsole returns a new default console instance that uses standard I/O [os.Stdin], [os.Stdout], and [os.Environ]. To use [os.Stderr] as the output, you can create a new console with [NewConsole] and pass [os.Stderr] as the output parameter.
DefaultOptions returns the default [Terminal] options.
DefaultTabStops creates a new set of tab stops with the default interval.
DefaultTerminal creates a new [Terminal] instance using the default standard console and the given options. Options can be nil to use the default options. This is a convenience function for creating a terminal that uses the standard input and output file descriptors.
DoubleBorder returns a border comprised of two thin strokes.
EncodeBackgroundColor encodes the background color to the given writer. Use nil to reset the background color to the default.
EncodeBracketedPaste encodes the bracketed paste mode to the given writer.
EncodeCursorColor encodes the cursor color to the given writer. Use nil to reset the cursor color to the default.
EncodeCursorStyle encodes the cursor style to the given writer.
EncodeForegroundColor encodes the foreground color to the given writer. Use nil to reset the foreground color to the default.
EncodeKeyboardEnhancements encodes the keyboard enhancements to the given writer.
EncodeMouseEncoding encodes the mouse encoding mode to the given writer. When enc is [MouseEncodingLegacy], all extended encodings are reset.
EncodeMouseMode encodes the mouse tracking mode to the given writer.
EncodeProgressBar encodes the progress bar to the given writer.
EncodeWindowTitle encodes the window title to the given writer.
HiddenBorder returns a border that renders as a series of single-cell spaces. It's useful for cases when you want to remove a standard border but maintain layout positioning. This said, you can still apply a background color to a hidden border.
InnerHalfBlockBorder returns a half-block border that sits inside the frame.
MarkdownBorder return a table border in markdown style.
MousePixelToCell converts a mouse event with pixel coordinates to cell coordinates. This is only meaningful when using [MouseEncodingSGRPixel] encoding, which reports mouse coordinates in pixels rather than cell units. The conversion is based on the terminal's reported pixel dimensions and cell dimensions. On Windows, or other platforms where [Terminal.GetWinsize] doesn't report pixel dimensions, you can query for the terminal window pixel dimensions via [ansi.WindowOp](4) and get back a [PixelSizeEvent] with the pixel dimensions. You can then construct a [Winsize] struct with the pixel dimensions and the cell dimensions from [Terminal.GetWinsize] and pass it to this function.
NewBuffer creates a new buffer with the given width and height. This is a convenience function that initializes a new buffer and resizes it.
NewCancelReader creates a new [cancelreader.CancelReader] that provides a cancelable reader interface that can be used to cancel reads.
NewCell creates a new cell from the given string grapheme. It will only use the first grapheme in the string and ignore the rest. The width of the cell is determined using the given width method.
NewConsole creates a new [Console] with the given input, output, and environment variables. You can use [OpenTTY] to open the current controlling console files and pass them to this function. Use [ControllingConsole] for a convenience function that does this for you. Use this to create a new terminal for PTY processes by passing the PTY slave file as the input and output and any environment variables the process needs.
NewCursor returns a new cursor with the default settings and the given position.
NewKeyboardEnhancements returns a new [KeyboardEnhancements] with the given options as flags. A zero, or negative, flags value is treated as no enhancements. See [ansi.KittyKeyboard] for more details on the supported keyboard enhancements.
NewLine creates a new line with the given width, filled with empty cells.
NewProgressBar returns a new progress bar with the given state and value. The value is ignored if the state is [ProgressBarNone] or [ProgressBarIndeterminate].
NewRenderBuffer creates a new [RenderBuffer] with the given width and height.
NewScreenBuffer creates a new ScreenBuffer with the given width and height.
NewSizeNotifier creates a new [SizeNotifier] that listens for window size changes on the given TTY file through SIGWINCH signals.
NewStyledString creates a new [StyledString] for the given method and styled string. The method is used to calculate the width of each line.
NewTabStops creates a new set of tab stops from a number of columns and an interval.
NewTerminal creates a new [Terminal] instance with the given console and options. Options can be nil to use the default options.
NewTerminalReader returns a new input event reader. The reader streams input events from the terminal and parses escape sequences into human-readable events. It supports reading Terminfo databases. Use [TerminalReader.UseTerminfo] to use Terminfo defined key sequences. Use [TerminalReader.Legacy] to control legacy key encoding behavior. Example: ```go var cr cancelreader.CancelReader var evc chan Event sc := NewTerminalReader(cr, os.Getenv("TERM")) go sc.StreamEvents(ctx, evc) ```
NewTerminalRenderer returns a new [TerminalRenderer] that uses the given writer, terminal type, and initializes the width of the terminal. The terminal type is used to determine the capabilities of the terminal and should be set to the value of the TERM environment variable. The renderer will try to detect the color profile from the output and the given environment variables. Use [TerminalRenderer.SetColorProfile] method to set a specific color profile for downsampling. See [TerminalRenderer] for more information on how to use the renderer.
NewTerminalScreen creates a new [TerminalScreen] with the given writer and environment.
NewWindow creates a new root [Window] with the given size and width method. If the method is nil, it defaults to [ansi.WcWidth]. The [WidthMethod] is used to calculate the width of characters in the window, which is important for correctly rendering text, especially when dealing with wide characters, combining characters, emojis, and other Unicode characters that may have varying widths. Use [ansi.WcWidth] as the default width method, which is a common implementation that handles a wide range of Unicode characters according to the Unicode Standard. Use [ansi.GraphemeWidth] if you know that your terminal supports grapheme clusters and proper rendering of combining characters and emojis, and you want to ensure that the width calculations are based on grapheme clusters rather than individual code points. This will panic if width or height is negative.
NormalBorder returns a standard-type border with a normal weight and 90 degree corners.
NotifyWinch sets up a channel to receive window size change signals and any other signals needed. This is a drop-in replacement for os/signal.Notify to ensure that SIGWINCH is included. On Windows, this will be a no-op for SIGWINCH, but other signals may still be handled.
NotifyWinchContext sets up a channel to receive window size change signals and any other signals needed, with context cancellation support. This is a drop-in replacement for os/signal.NotifyContext to ensure that SIGWINCH is included. On Windows, this will be a no-op for SIGWINCH, but other signals may still be handled.
OpenTTY opens the terminal's input and output file descriptors. It returns the input and output files, or an error if the terminal is not available. This is useful for applications that need to interact with the terminal directly while piping or redirecting input/output.
OuterHalfBlockBorder returns a half-block border that sits outside the frame.
Pos is a shorthand for creating a new [Position].
ReadStyle reads a Select Graphic Rendition (SGR) escape sequences from a list of parameters into pen.
Rect is a shorthand for creating a new [Rectangle].
RoundedBorder returns a border with rounded corners.
StyleDiff returns the SGR ANSI sequence necessary to transition from the "from" style to the "to" style.
Suspend suspends the current process group.
ThickBorder returns a border that's thicker than the one returned by NormalBorder.
TrimSpace trims trailing spaces from the end of each line in the given string.
Package-Level Variables (total 10, in which 6 are exported)
EmptyCell is a cell with a single space, width of 1, and no style or link.
ErrCanceled is returned when a poll or read operation is canceled.
ErrInvalidDimensions is returned when the dimensions of a window are invalid for the operation.
ErrNotTerminal is an error that indicates that the file is not a terminal.
ErrPlatformNotSupported is an error that indicates that the platform is not supported.
ErrReaderNotStarted is returned when the reader has not been started yet.
Package-Level Constants (total 250, in which 212 are exported)
These are the available text attributes that can be combined to create different styles.
These are the available text attributes that can be combined to create different styles.
These are the available text attributes that can be combined to create different styles.
These are the available text attributes that can be combined to create different styles.
These are the available text attributes that can be combined to create different styles.
These are the available text attributes that can be combined to create different styles.
These are the available text attributes that can be combined to create different styles.
Cursor shapes.
Cursor shapes.
Cursor shapes.
DefaultBufferSize is the default size of the input buffer used for reading terminal events.
DefaultEscTimeout is the default timeout at which the [TerminalReader] will process ESC sequences. It is set to 50 milliseconds.
DefaultEventTimeout is the default duration to wait for input events before timing out.
DefaultTabInterval is the default tab interval.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
KeyExtended is a special key code used to signify that a key event contains multiple runes.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Modifier keys.
Modifier keys.
Modifier keys.
Modifier keys.
Modifier keys.
Modifier keys.
Modifier keys.
Modifier keys.
Modifier keys.
Mouse event buttons This is based on X11 mouse button codes. 1 = left button 2 = middle button (pressing the scroll wheel) 3 = right button 4 = turn scroll wheel up 5 = turn scroll wheel down 6 = push scroll wheel left 7 = push scroll wheel right 8 = 4th button (aka browser backward button) 9 = 5th button (aka browser forward button) 10 11 Other buttons are not supported.
Mouse event buttons This is based on X11 mouse button codes. 1 = left button 2 = middle button (pressing the scroll wheel) 3 = right button 4 = turn scroll wheel up 5 = turn scroll wheel down 6 = push scroll wheel left 7 = push scroll wheel right 8 = 4th button (aka browser backward button) 9 = 5th button (aka browser forward button) 10 11 Other buttons are not supported.
Mouse event buttons This is based on X11 mouse button codes. 1 = left button 2 = middle button (pressing the scroll wheel) 3 = right button 4 = turn scroll wheel up 5 = turn scroll wheel down 6 = push scroll wheel left 7 = push scroll wheel right 8 = 4th button (aka browser backward button) 9 = 5th button (aka browser forward button) 10 11 Other buttons are not supported.
Mouse encodings. These determine how mouse coordinates and buttons are encoded in the terminal's escape sequences. The encoding is only meaningful when mouse tracking is enabled via [MouseMode].
Mouse encodings. These determine how mouse coordinates and buttons are encoded in the terminal's escape sequences. The encoding is only meaningful when mouse tracking is enabled via [MouseMode].
Mouse encodings. These determine how mouse coordinates and buttons are encoded in the terminal's escape sequences. The encoding is only meaningful when mouse tracking is enabled via [MouseMode].
Mouse event buttons This is based on X11 mouse button codes. 1 = left button 2 = middle button (pressing the scroll wheel) 3 = right button 4 = turn scroll wheel up 5 = turn scroll wheel down 6 = push scroll wheel left 7 = push scroll wheel right 8 = 4th button (aka browser backward button) 9 = 5th button (aka browser forward button) 10 11 Other buttons are not supported.
Mouse event buttons This is based on X11 mouse button codes. 1 = left button 2 = middle button (pressing the scroll wheel) 3 = right button 4 = turn scroll wheel up 5 = turn scroll wheel down 6 = push scroll wheel left 7 = push scroll wheel right 8 = 4th button (aka browser backward button) 9 = 5th button (aka browser forward button) 10 11 Other buttons are not supported.
Mouse event buttons This is based on X11 mouse button codes. 1 = left button 2 = middle button (pressing the scroll wheel) 3 = right button 4 = turn scroll wheel up 5 = turn scroll wheel down 6 = push scroll wheel left 7 = push scroll wheel right 8 = 4th button (aka browser backward button) 9 = 5th button (aka browser forward button) 10 11 Other buttons are not supported.
Mouse tracking modes. These determine which mouse events the terminal reports.
Mouse tracking modes. These determine which mouse events the terminal reports.
Mouse tracking modes. These determine which mouse events the terminal reports.
Mouse tracking modes. These determine which mouse events the terminal reports.
Mouse tracking modes. These determine which mouse events the terminal reports.
Mouse event buttons This is based on X11 mouse button codes. 1 = left button 2 = middle button (pressing the scroll wheel) 3 = right button 4 = turn scroll wheel up 5 = turn scroll wheel down 6 = push scroll wheel left 7 = push scroll wheel right 8 = 4th button (aka browser backward button) 9 = 5th button (aka browser forward button) 10 11 Other buttons are not supported.
Mouse event buttons This is based on X11 mouse button codes. 1 = left button 2 = middle button (pressing the scroll wheel) 3 = right button 4 = turn scroll wheel up 5 = turn scroll wheel down 6 = push scroll wheel left 7 = push scroll wheel right 8 = 4th button (aka browser backward button) 9 = 5th button (aka browser forward button) 10 11 Other buttons are not supported.
Mouse event buttons This is based on X11 mouse button codes. 1 = left button 2 = middle button (pressing the scroll wheel) 3 = right button 4 = turn scroll wheel up 5 = turn scroll wheel down 6 = push scroll wheel left 7 = push scroll wheel right 8 = 4th button (aka browser backward button) 9 = 5th button (aka browser forward button) 10 11 Other buttons are not supported.
Mouse event buttons This is based on X11 mouse button codes. 1 = left button 2 = middle button (pressing the scroll wheel) 3 = right button 4 = turn scroll wheel up 5 = turn scroll wheel down 6 = push scroll wheel left 7 = push scroll wheel right 8 = 4th button (aka browser backward button) 9 = 5th button (aka browser forward button) 10 11 Other buttons are not supported.
Mouse event buttons This is based on X11 mouse button codes. 1 = left button 2 = middle button (pressing the scroll wheel) 3 = right button 4 = turn scroll wheel up 5 = turn scroll wheel down 6 = push scroll wheel left 7 = push scroll wheel right 8 = 4th button (aka browser backward button) 9 = 5th button (aka browser forward button) 10 11 Other buttons are not supported.
Mouse event buttons This is based on X11 mouse button codes. 1 = left button 2 = middle button (pressing the scroll wheel) 3 = right button 4 = turn scroll wheel up 5 = turn scroll wheel down 6 = push scroll wheel left 7 = push scroll wheel right 8 = 4th button (aka browser backward button) 9 = 5th button (aka browser forward button) 10 11 Other buttons are not supported.
Clipboard selections.
Progress bar states.
Progress bar states.
Progress bar states.
Progress bar states.
Clipboard selections.
These are the available underline styles.
These are the available underline styles.
These are the available underline styles.
These are the available underline styles.
These are the available underline styles.
These are the available underline styles.
These are the available underline styles. Deprecated: Use the constants from [Underline] instead.
These are the available underline styles. Deprecated: Use the constants from [Underline] instead.
These are the available underline styles. Deprecated: Use the constants from [Underline] instead.
These are the available underline styles. Deprecated: Use the constants from [Underline] instead.
These are the available underline styles. Deprecated: Use the constants from [Underline] instead.
These are the available underline styles. Deprecated: Use the constants from [Underline] instead.