uv

package module
v0.0.0-...-41ff2ba Latest Latest
Warning

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

Go to latest
Published: Feb 15, 2026 License: MIT Imports: 38 Imported by: 6

README

Ultraviolet

Charm Ultraviolet

GoDoc Build Status

Ultraviolet is a set of primitives for manipulating terminal emulators, with a focus on terminal user interfaces (TUIs). It provides a set of tools and abstractions for interaction that can handle user input and display dynamic, cell-based content. It’s the product of many years of research, development, collaboration and ingenuity.

Ultraviolet is not a framework by design, however it can be used standalone to create powerful terminal applications. It’s in use in production and powers critical portions of Bubble Tea v2 and Lip Gloss v2, and was instrumental in the development of Crush.

[!CAUTION] This project currently exists to serve internal use cases. API stability is a goal, but expect no stability guarantees as of now.

Features

Ultraviolet is built with several core features in mind to make terminal application development easy and performant:

👺 The Cursed Renderer

The cell-based rendering model—called The Cursed Render—was inspired by the infamous ncurses library, which has been an essential part of terminal applications for decades. Ultraviolet takes this concept and modernizes it for the Go programming language, providing a more ergonomic and efficient way to work with terminal cells without the need for archaic technologies like terminfo or termcap databases.

Unlike ncurses, it supports both full-window and inline use-cases as we see inline TUIs as important in maintaining user context and flow.

🏎️ High Speeds and Low Bandwidth

The built-in terminal renderer efficiently handles content updates by utilizing a powerful cell-based diffing algorithm that minimizes the amount of data written to the terminal using various ANSI escape sequences to accomplish this. This allows applications to update only the parts of the terminal that have changed, significantly improving performance and responsiveness.

In practical terms, Ultraviolet optimizes for fast redraws that use minimal data transfer. This is very important locally and critically important over the network (for example, via SSH).

💬 Universal Input

Input handling in terminals can be complex, especially when dealing with multiple input sources, different platforms, and ancient terminal baggage. Ultraviolet simplifies this by providing a unified interface for handling user input, allowing developers to focus on building their applications without getting bogged down in the intricacies of terminal input handling.

🎮 Cross-Platform Compatibility

Ultraviolet is designed to work seamlessly across different platforms and terminal emulators. It abstracts away the differences in terminal capabilities and provides a consistent API for developers to work with, ensuring that applications built with Ultraviolet will run smoothly on various systems.

On Windows, it uses the Windows Console API to provide a consistent experience, while on Unix-like systems, it relies on the standard Termios API along with ANSI escape sequences to manipulate the terminal.

In short: Ultraviolet provides first-class support for both Unix and Windows-based systems.

🧩 Extensible Architecture

Ultraviolet is built with extensibility in mind, providing a solid API that can be embedded into other applications or used as a foundation for building custom terminal user interfaces. It allows developers to create their own components, styles, and behaviors, making it a versatile tool for building terminal applications.

FAQ

🐈 What about other Charm libraries?

Ultraviolet is not a replacement for existing libraries like Bubble Tea or Lip Gloss. Instead, it serves as a foundation for the latest versions of both of these libraries and others like them, providing the underlying primitives and abstractions needed to build terminal user interfaces applications and frameworks.

🛁 How is it different from Bubble Tea?

Ultraviolet is a lower-level library that focuses on the core primitives of terminal manipulation, rendering, and input handling. It provides the building blocks for creating terminal applications, while Bubble Tea is a higher-level framework that builds on top of Ultraviolet to provide a more structured and opinionated way to build terminal user interfaces.

💋 Is it a replacement for Lip Gloss?

Simply put, no. Ultraviolet is not a replacement for Lip Gloss. Instead, it provides the underlying rendering capabilities that Lip Gloss can use to create styled terminal content. Lip Gloss is a higher-level library that builds on top of Ultraviolet by utilizing the cell-based rendering model to provide a simplified and ergonomic way to create styled terminal content and composition of terminal user interfaces.

✏️ Tutorial

You can find a simple tutorial on how to create a UV application that displays "Hello, World!" on the screen in the TUTORIAL.md file.

Whatcha think?

We’d love to hear your thoughts on this project. Feel free to drop us a note!

License

MIT


Part of Charm.

The Charm logo

Charm热爱开源 • Charm loves open source • نحنُ نحب المصادر المفتوحة

Documentation

Overview

Package uv (Ultraviolet) is a library for creating terminal-based user interfaces in Go.

Index

Constants

View Source
const (
	AttrBold = 1 << iota
	AttrFaint
	AttrItalic
	AttrBlink
	AttrRapidBlink // Not widely supported
	AttrReverse
	AttrConceal
	AttrStrikethrough

	AttrReset = 0
)

These are the available text attributes that can be combined to create different styles.

View Source
const (
	UnderlineNone   = ansi.UnderlineNone
	UnderlineSingle = ansi.UnderlineSingle
	UnderlineDouble = ansi.UnderlineDouble
	UnderlineCurly  = ansi.UnderlineCurly
	UnderlineDotted = ansi.UnderlineDotted
	UnderlineDashed = ansi.UnderlineDashed
)

These are the available underline styles.

View Source
const (
	UnderlineStyleNone   = ansi.UnderlineNone
	UnderlineStyleSingle = ansi.UnderlineSingle
	UnderlineStyleDouble = ansi.UnderlineDouble
	UnderlineStyleCurly  = ansi.UnderlineCurly
	UnderlineStyleDotted = ansi.UnderlineDotted
	UnderlineStyleDashed = ansi.UnderlineDashed
)

These are the available underline styles.

Deprecated: Use the constants from Underline instead.

View Source
const (
	KeyUp rune = KeyExtended + iota + 1
	KeyDown
	KeyRight
	KeyLeft
	KeyBegin
	KeyFind
	KeyInsert
	KeyDelete
	KeySelect
	KeyPgUp
	KeyPgDown
	KeyHome
	KeyEnd

	KeyKpEnter
	KeyKpEqual
	KeyKpMultiply
	KeyKpPlus
	KeyKpComma
	KeyKpMinus
	KeyKpDecimal
	KeyKpDivide
	KeyKp0
	KeyKp1
	KeyKp2
	KeyKp3
	KeyKp4
	KeyKp5
	KeyKp6
	KeyKp7
	KeyKp8
	KeyKp9

	KeyKpSep
	KeyKpUp
	KeyKpDown
	KeyKpLeft
	KeyKpRight
	KeyKpPgUp
	KeyKpPgDown
	KeyKpHome
	KeyKpEnd
	KeyKpInsert
	KeyKpDelete
	KeyKpBegin

	KeyF1
	KeyF2
	KeyF3
	KeyF4
	KeyF5
	KeyF6
	KeyF7
	KeyF8
	KeyF9
	KeyF10
	KeyF11
	KeyF12
	KeyF13
	KeyF14
	KeyF15
	KeyF16
	KeyF17
	KeyF18
	KeyF19
	KeyF20
	KeyF21
	KeyF22
	KeyF23
	KeyF24
	KeyF25
	KeyF26
	KeyF27
	KeyF28
	KeyF29
	KeyF30
	KeyF31
	KeyF32
	KeyF33
	KeyF34
	KeyF35
	KeyF36
	KeyF37
	KeyF38
	KeyF39
	KeyF40
	KeyF41
	KeyF42
	KeyF43
	KeyF44
	KeyF45
	KeyF46
	KeyF47
	KeyF48
	KeyF49
	KeyF50
	KeyF51
	KeyF52
	KeyF53
	KeyF54
	KeyF55
	KeyF56
	KeyF57
	KeyF58
	KeyF59
	KeyF60
	KeyF61
	KeyF62
	KeyF63

	KeyCapsLock
	KeyScrollLock
	KeyNumLock
	KeyPrintScreen
	KeyPause
	KeyMenu

	KeyMediaPlay
	KeyMediaPause
	KeyMediaPlayPause
	KeyMediaReverse
	KeyMediaStop
	KeyMediaFastForward
	KeyMediaRewind
	KeyMediaNext
	KeyMediaPrev
	KeyMediaRecord

	KeyLowerVol
	KeyRaiseVol
	KeyMute

	KeyLeftShift
	KeyLeftAlt
	KeyLeftCtrl
	KeyLeftSuper
	KeyLeftHyper
	KeyLeftMeta
	KeyRightShift
	KeyRightAlt
	KeyRightCtrl
	KeyRightSuper
	KeyRightHyper
	KeyRightMeta
	KeyIsoLevel3Shift
	KeyIsoLevel5Shift

	KeyBackspace = rune(ansi.DEL)
	KeyTab       = rune(ansi.HT)
	KeyEnter     = rune(ansi.CR)
	KeyReturn    = KeyEnter
	KeyEscape    = rune(ansi.ESC)
	KeyEsc       = KeyEscape

	KeySpace = rune(ansi.SP)
)

Special key symbols.

View Source
const (
	MouseNone       = ansi.MouseNone
	MouseLeft       = ansi.MouseLeft
	MouseMiddle     = ansi.MouseMiddle
	MouseRight      = ansi.MouseRight
	MouseWheelUp    = ansi.MouseWheelUp
	MouseWheelDown  = ansi.MouseWheelDown
	MouseWheelLeft  = ansi.MouseWheelLeft
	MouseWheelRight = ansi.MouseWheelRight
	MouseBackward   = ansi.MouseBackward
	MouseForward    = ansi.MouseForward
	MouseButton10   = ansi.MouseButton10
	MouseButton11   = ansi.MouseButton11
)

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.

View Source
const (
	AttrSlowBlink = AttrBlink
)

AttrSlowBlink is an alias for AttrBlink.

Deprecated: Use AttrBlink instead.

View Source
const DefaultBufferSize = 4096

DefaultBufferSize is the default size of the input buffer used for reading terminal events.

View Source
const DefaultEscTimeout = 50 * time.Millisecond

DefaultEscTimeout is the default timeout at which the TerminalReader will process ESC sequences. It is set to 50 milliseconds.

View Source
const DefaultEventTimeout = 100 * time.Millisecond

DefaultEventTimeout is the default duration to wait for input events before timing out.

View Source
const DefaultTabInterval = 8

DefaultTabInterval is the default tab interval.

View Source
const (
	// KeyExtended is a special key code used to signify that a key event
	// contains multiple runes.
	KeyExtended = unicode.MaxRune + 1
)

Variables

View Source
var (
	// ErrNotTerminal is an error that indicates that the file is not a terminal.
	ErrNotTerminal = fmt.Errorf("not a terminal")
	// ErrPlatformNotSupported is an error that indicates that the platform is not supported.
	ErrPlatformNotSupported = fmt.Errorf("platform not supported")
)
View Source
var EmptyCell = Cell{Content: " ", Width: 1}

EmptyCell is a cell with a single space, width of 1, and no style or link.

View Source
var ErrCanceled = fmt.Errorf("poll canceled")

ErrCanceled is returned when a poll or read operation is canceled.

View Source
var ErrInvalidDimensions = errors.New("invalid dimensions")

ErrInvalidDimensions is returned when the dimensions of a window are invalid for the operation.

View Source
var ErrReaderNotStarted = fmt.Errorf("reader not started")

ErrReaderNotStarted is returned when the reader has not been started yet.

Functions

func EncodeBackgroundColor

func EncodeBackgroundColor(w io.Writer, c color.Color) error

EncodeBackgroundColor encodes the background color to the given writer. Use nil to reset the background color to the default.

func EncodeBracketedPaste

func EncodeBracketedPaste(w io.Writer, enable bool) error

EncodeBracketedPaste encodes the bracketed paste mode to the given writer.

func EncodeCursorColor

func EncodeCursorColor(w io.Writer, c color.Color) error

EncodeCursorColor encodes the cursor color to the given writer. Use nil to reset the cursor color to the default.

func EncodeCursorStyle

func EncodeCursorStyle(w io.Writer, shape CursorShape, blink bool) error

EncodeCursorStyle encodes the cursor style to the given writer.

func EncodeForegroundColor

func EncodeForegroundColor(w io.Writer, c color.Color) error

EncodeForegroundColor encodes the foreground color to the given writer. Use nil to reset the foreground color to the default.

func EncodeKeyboardEnhancements

func EncodeKeyboardEnhancements(w io.Writer, ke *KeyboardEnhancements) error

EncodeKeyboardEnhancements encodes the keyboard enhancements to the given writer.

func EncodeMouseMode

func EncodeMouseMode(w io.Writer, mode MouseMode) error

EncodeMouseMode encodes the mouse mode to the given writer.

func EncodeProgressBar

func EncodeProgressBar(w io.Writer, pb *ProgressBar) error

EncodeProgressBar encodes the progress bar to the given writer.

func EncodeWindowTitle

func EncodeWindowTitle(w io.Writer, title string) error

EncodeWindowTitle encodes the window title to the given writer.

func NewCancelReader

func NewCancelReader(r io.Reader) (cancelreader.CancelReader, error)

NewCancelReader creates a new cancelreader.CancelReader that provides a cancelable reader interface that can be used to cancel reads.

func NotifyWinch

func NotifyWinch(c chan os.Signal, sigs ...os.Signal)

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.

func NotifyWinchContext

func NotifyWinchContext(ctx context.Context, sigs ...os.Signal) (context.Context, context.CancelFunc)

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.

func OpenTTY

func OpenTTY() (inTty, outTty *os.File, err error)

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.

func ReadLink(p []byte, link *Link)

ReadLink reads a hyperlink escape sequence from a data buffer into link.

func ReadStyle

func ReadStyle(params ansi.Params, pen *Style)

ReadStyle reads a Select Graphic Rendition (SGR) escape sequences from a list of parameters into pen.

func StyleDiff

func StyleDiff(from, to *Style) string

StyleDiff returns the SGR ANSI sequence necessary to transition from the "from" style to the "to" style.

func Suspend

func Suspend() error

Suspend suspends the current process group.

func TrimSpace

func TrimSpace(s string) string

TrimSpace trims trailing spaces from the end of each line in the given string.

Types

type BackgroundColorEvent

type BackgroundColorEvent struct{ color.Color }

BackgroundColorEvent represents a background color event. This event is emitted when the terminal requests the terminal background color using ansi.RequestBackgroundColor.

func (BackgroundColorEvent) IsDark

func (e BackgroundColorEvent) IsDark() bool

IsDark returns whether the color is dark.

func (BackgroundColorEvent) String

func (e BackgroundColorEvent) String() string

String returns the hex representation of the color.

type BlurEvent

type BlurEvent struct{}

BlurEvent represents a terminal blur event. This occurs when the terminal loses focus.

type Border

type Border struct {
	Top         Side
	Bottom      Side
	Left        Side
	Right       Side
	TopLeft     Side
	TopRight    Side
	BottomLeft  Side
	BottomRight Side
}

Border represents a border with its properties.

func ASCIIBorder

func ASCIIBorder() Border

ASCIIBorder returns a table border with ASCII characters.

func BlockBorder

func BlockBorder() Border

BlockBorder returns a border that takes the whole block.

func DoubleBorder

func DoubleBorder() Border

DoubleBorder returns a border comprised of two thin strokes.

func HiddenBorder

func HiddenBorder() Border

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.

func InnerHalfBlockBorder

func InnerHalfBlockBorder() Border

InnerHalfBlockBorder returns a half-block border that sits inside the frame.

func MarkdownBorder

func MarkdownBorder() Border

MarkdownBorder return a table border in markdown style.

func NormalBorder

func NormalBorder() Border

NormalBorder returns a standard-type border with a normal weight and 90 degree corners.

func OuterHalfBlockBorder

func OuterHalfBlockBorder() Border

OuterHalfBlockBorder returns a half-block border that sits outside the frame.

func RoundedBorder

func RoundedBorder() Border

RoundedBorder returns a border with rounded corners.

func ThickBorder

func ThickBorder() Border

ThickBorder returns a border that's thicker than the one returned by NormalBorder.

func (*Border) Draw

func (b *Border) Draw(scr Screen, area Rectangle)

Draw draws the border around the given component.

func (b Border) Link(link Link) Border

Link returns a new Border with the given link applied to all [Side]s.

func (Border) Style

func (b Border) Style(style Style) Border

Style returns a new Border with the given style applied to all [Side]s.

type Buffer

type Buffer struct {
	// Lines is a slice of lines that make up the cells of the buffer.
	Lines []Line
}

Buffer represents a cell buffer that contains the contents of a screen.

func NewBuffer

func NewBuffer(width int, height int) *Buffer

NewBuffer creates a new buffer with the given width and height. This is a convenience function that initializes a new buffer and resizes it.

func (*Buffer) Bounds

func (b *Buffer) Bounds() Rectangle

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.

func (*Buffer) CellAt

func (b *Buffer) CellAt(x int, y int) *Cell

CellAt returns the cell at the given position. It returns nil if the position is out of bounds.

func (*Buffer) Clear

func (b *Buffer) Clear()

Clear clears the buffer with space cells and rectangle.

func (*Buffer) ClearArea

func (b *Buffer) ClearArea(area Rectangle)

ClearArea clears the buffer with space cells within the specified rectangles. Only cells within the rectangle's bounds are affected.

func (*Buffer) Clone

func (b *Buffer) Clone() *Buffer

Clone clones the entire buffer into a new buffer.

func (*Buffer) CloneArea

func (b *Buffer) CloneArea(area Rectangle) *Buffer

CloneArea clones the area of the buffer within the specified rectangle. If the area is out of bounds, it returns nil.

func (*Buffer) DeleteCell

func (b *Buffer) DeleteCell(x, y, n int, c *Cell)

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.

func (*Buffer) DeleteCellArea

func (b *Buffer) DeleteCellArea(x, y, n int, c *Cell, area Rectangle)

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.

func (*Buffer) DeleteLine

func (b *Buffer) DeleteLine(y, n int, c *Cell)

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.

func (*Buffer) DeleteLineArea

func (b *Buffer) DeleteLineArea(y, n int, c *Cell, area Rectangle)

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.

func (*Buffer) Draw

func (b *Buffer) Draw(scr Screen, area Rectangle)

Draw draws the buffer to the given screen at the specified area. It implements the Drawable interface.

func (*Buffer) Fill

func (b *Buffer) Fill(c *Cell)

Fill fills the buffer with the given cell and rectangle.

func (*Buffer) FillArea

func (b *Buffer) FillArea(c *Cell, area Rectangle)

FillArea fills the buffer with the given cell and rectangle.

func (*Buffer) Height

func (b *Buffer) Height() int

Height implements Screen.

func (*Buffer) InsertCell

func (b *Buffer) InsertCell(x, y, n int, c *Cell)

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.

func (*Buffer) InsertCellArea

func (b *Buffer) InsertCellArea(x, y, n int, c *Cell, area Rectangle)

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.

func (*Buffer) InsertLine

func (b *Buffer) InsertLine(y, n int, c *Cell)

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.

func (*Buffer) InsertLineArea

func (b *Buffer) InsertLineArea(y, n int, c *Cell, area Rectangle)

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.

func (*Buffer) Line

func (b *Buffer) Line(y int) Line

Line returns a pointer to the line at the given y position. If the line does not exist, it returns nil.

func (*Buffer) Render

func (b *Buffer) Render() string

Render renders the buffer to a styled string with all the required attributes and styles.

func (*Buffer) Resize

func (b *Buffer) Resize(width int, height int)

Resize resizes the buffer to the given width and height.

func (*Buffer) SetCell

func (b *Buffer) SetCell(x, y int, c *Cell)

SetCell sets the cell at the given x, y position.

func (*Buffer) String

func (b *Buffer) String() string

String returns the string representation of the buffer.

func (*Buffer) Width

func (b *Buffer) Width() int

Width implements Screen.

type CapabilityEvent

type CapabilityEvent struct {
	Content string
}

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

func (CapabilityEvent) String

func (e CapabilityEvent) String() string

String returns the capability content.

type Cell

type Cell struct {
	// 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.
	Content string

	// The style of the cell. Nil style means no style. Zero value prints a
	// reset sequence.
	Style Style

	// Link is the hyperlink of the cell.
	Link Link

	// Width is the mono-spaced width of the grapheme cluster.
	Width int
}

Cell represents a single cell in the terminal screen.

func NewCell

func NewCell(method WidthMethod, gr string) *Cell

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.

func (*Cell) Clone

func (c *Cell) Clone() (n *Cell)

Clone returns a copy of the cell.

func (*Cell) Empty

func (c *Cell) Empty()

Empty makes the cell an empty cell by setting its content to a single space and width to 1.

func (*Cell) Equal

func (c *Cell) Equal(o *Cell) bool

Equal returns whether the cell is equal to the other cell.

func (*Cell) IsZero

func (c *Cell) IsZero() bool

IsZero returns whether the cell is an empty cell.

func (*Cell) String

func (c *Cell) String() string

String returns the string content of the cell excluding any styles, links, and escape sequences.

type CellSizeEvent

type CellSizeEvent Size

CellSizeEvent represents the cell size in pixels.

func (CellSizeEvent) Bounds

func (s CellSizeEvent) Bounds() Rectangle

Bounds returns the bounds corresponding to the size.

type ClipboardEvent

type ClipboardEvent struct {
	Content   string
	Selection ClipboardSelection
}

ClipboardEvent is a clipboard read message event. This message is emitted when a terminal receives an OSC52 clipboard read message event.

func (ClipboardEvent) Clipboard

func (e ClipboardEvent) Clipboard() ClipboardSelection

Clipboard returns the clipboard selection. This can be either SystemClipboard 'c' or PrimaryClipboard 'p'.

func (ClipboardEvent) String

func (e ClipboardEvent) String() string

String returns the string representation of the clipboard message.

type ClipboardSelection

type ClipboardSelection = byte

ClipboardSelection represents a clipboard selection. The most common clipboard selections are "system" and "primary" and selections.

const (
	SystemClipboard  ClipboardSelection = ansi.SystemClipboard
	PrimaryClipboard ClipboardSelection = ansi.PrimaryClipboard
)

Clipboard selections.

type Console

type Console interface {
	io.ReadWriteCloser

	// Environ returns the console's environment variables.
	Environ() []string

	// Getenv retrieves the value of the environment variable named by the key.
	Getenv(key string) string

	// LookupEnv retrieves the value of the environment variable named by the key
	// and a boolean indicating whether the variable is present.
	LookupEnv(key string) (string, bool)

	// Reader returns the input reader of the console.
	Reader() io.Reader

	// Writer returns the output writer of the console.
	Writer() io.Writer

	// MakeRaw puts the console input side into raw mode.
	MakeRaw() (state *term.State, err error)

	// Restore restores the console to its previous state.
	Restore() error

	// GetSize returns the current size of the console.
	GetSize() (width, height int, err error)

	// GetWinsize returns the current size of the console in cells and pixels.
	GetWinsize() (*Winsize, error)
}

Console represents a cross-platform console I/O interface.

func ControllingConsole

func ControllingConsole() (Console, error)

ControllingConsole returns a new console instance that uses the current controlling terminal's input and output file descriptors.

func DefaultConsole

func DefaultConsole() Console

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.

func NewConsole

func NewConsole(input, output File, environ []string) Console

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.

type Cursor

type Cursor struct {
	// Position is a [Position] that determines the cursor's position on the
	// screen relative to the top left corner of the frame.
	Position

	// Color is a [color.Color] that determines the cursor's color.
	Color color.Color

	// Shape is a [CursorShape] that determines the cursor's shape.
	Shape CursorShape

	// Blink is a boolean that determines whether the cursor should blink.
	Blink bool

	// 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.
	Hidden bool
}

Cursor represents a cursor on the terminal screen.

func NewCursor

func NewCursor(x, y int) *Cursor

NewCursor returns a new cursor with the default settings and the given position.

type CursorColorEvent

type CursorColorEvent struct{ color.Color }

CursorColorEvent represents a cursor color change event. This event is emitted when the program requests the terminal cursor color using ansi.RequestCursorColor.

func (CursorColorEvent) IsDark

func (e CursorColorEvent) IsDark() bool

IsDark returns whether the color is dark.

func (CursorColorEvent) String

func (e CursorColorEvent) String() string

String returns the hex representation of the color.

type CursorPositionEvent

type CursorPositionEvent struct {
	X, Y int
}

CursorPositionEvent represents a cursor position event. Where X is the zero-based column and Y is the zero-based row.

type CursorShape

type CursorShape int

CursorShape represents a terminal cursor shape.

const (
	CursorBlock CursorShape = iota
	CursorUnderline
	CursorBar
)

Cursor shapes.

func (CursorShape) Encode

func (s CursorShape) Encode(blink bool) int

Encode returns the encoded value for the cursor shape.

type DarkColorSchemeEvent

type DarkColorSchemeEvent struct{}

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.

type Drawable

type Drawable interface {
	// Draw renders the component on the screen for the given area.
	Draw(scr Screen, area Rectangle)
}

Drawable represents a drawable component on a Screen.

type DrawableFunc

type DrawableFunc func(scr Screen, rect Rectangle)

DrawableFunc is a function that implements the Drawable interface.

func (DrawableFunc) Draw

func (f DrawableFunc) Draw(scr Screen, rect Rectangle)

Draw implements the Drawable interface.

type Environ

type Environ []string

Environ is a slice of strings that represents the environment variables of the program.

func (Environ) Getenv

func (p Environ) Getenv(key string) (v string)

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.

func (Environ) LookupEnv

func (p Environ) LookupEnv(key string) (s string, v bool)

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.

type Event

type Event interface{}

Event represents an input event that can be received from an input source.

type EventDecoder

type EventDecoder struct {
	// Legacy is the legacy key encoding flags. These flags control the
	// behavior of legacy terminal key encodings. See [LegacyKeyEncoding] for
	// more details.
	Legacy LegacyKeyEncoding
	// 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.
	UseTerminfo bool
	// contains filtered or unexported fields
}

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.

func (*EventDecoder) Decode

func (p *EventDecoder) Decode(buf []byte) (n int, Event Event)

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:]
}
```

type EventStreamer

type EventStreamer interface {
	StreamEvents(ctx context.Context, ch chan<- Event) error
}

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.

type File

type File interface {
	io.ReadWriteCloser
	term.File

	// Name returns the name of the file.
	Name() string
}

File is an interface that represents a file with a file descriptor.

This is typically an os.File like os.Stdin and os.Stdout.

type FocusEvent

type FocusEvent struct{}

FocusEvent represents a terminal focus event. This occurs when the terminal gains focus.

type ForegroundColorEvent

type ForegroundColorEvent struct{ color.Color }

ForegroundColorEvent represents a foreground color event. This event is emitted when the terminal requests the terminal foreground color using ansi.RequestForegroundColor.

func (ForegroundColorEvent) IsDark

func (e ForegroundColorEvent) IsDark() bool

IsDark returns whether the color is dark.

func (ForegroundColorEvent) String

func (e ForegroundColorEvent) String() string

String returns the hex representation of the color.

type Key

type Key struct {
	// 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).
	Text string

	// Mod represents modifier keys, like [ModCtrl], [ModAlt], and so on.
	Mod KeyMod

	// Code represents the key pressed. This is usually a special key like
	// [KeyTab], [KeyEnter], [KeyF1], or a printable character like 'a'.
	Code rune

	// 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.
	ShiftedCode rune

	// 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.
	BaseCode rune

	// 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.
	IsRepeat bool
}

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.).

func (Key) Keystroke

func (k Key) Keystroke() string

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".

func (Key) MatchString

func (k Key) MatchString(s ...string) bool

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.

func (Key) String

func (k Key) String() string

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.

type KeyEvent

type KeyEvent interface {
	fmt.Stringer

	// Key returns the underlying key event.
	Key() Key
}

KeyEvent represents a key event. This can be either a key press or a key release event.

type KeyMod

type KeyMod int

KeyMod represents modifier keys.

const (
	ModShift KeyMod = 1 << iota
	ModAlt
	ModCtrl
	ModMeta

	ModHyper
	ModSuper // Windows/Command keys

	ModCapsLock
	ModNumLock
	ModScrollLock // Defined in Windows API only
)

Modifier keys.

func (KeyMod) Contains

func (m KeyMod) Contains(mods KeyMod) bool

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

type KeyPressEvent

type KeyPressEvent Key

KeyPressEvent represents a key press event.

func (KeyPressEvent) Key

func (k KeyPressEvent) Key() Key

Key returns the underlying key event. This is a syntactic sugar for casting the key event to a Key.

func (KeyPressEvent) Keystroke

func (k KeyPressEvent) Keystroke() string

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".

func (KeyPressEvent) MatchString

func (k KeyPressEvent) MatchString(s ...string) bool

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.

func (KeyPressEvent) String

func (k KeyPressEvent) String() string

String implements fmt.Stringer and is quite useful for matching key events. For details, on what this returns see Key.String.

type KeyReleaseEvent

type KeyReleaseEvent Key

KeyReleaseEvent represents a key release event.

func (KeyReleaseEvent) Key

func (k KeyReleaseEvent) Key() Key

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.

func (KeyReleaseEvent) Keystroke

func (k KeyReleaseEvent) Keystroke() string

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".

func (KeyReleaseEvent) MatchString

func (k KeyReleaseEvent) MatchString(s ...string) bool

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.

func (KeyReleaseEvent) String

func (k KeyReleaseEvent) String() string

String implements fmt.Stringer and is quite useful for matching key events. For details, on what this returns see Key.String.

type KeyboardEnhancements

type KeyboardEnhancements struct {
	// 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.
	DisambiguateEscapeCodes bool

	// 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.
	ReportEventTypes bool
}

KeyboardEnhancements defines different keyboard enhancement features that can be requested from the terminal.

func NewKeyboardEnhancements

func NewKeyboardEnhancements(flags int) *KeyboardEnhancements

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.

func (KeyboardEnhancements) Flags

func (ke KeyboardEnhancements) Flags() int

Flags returns the keyboard enhancements as bits that can be used to set the appropriate terminal modes.

type KeyboardEnhancementsEvent

type KeyboardEnhancementsEvent struct {
	// 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
	Flags int
}

KeyboardEnhancementsEvent represents a keyboard enhancements report event.

func (KeyboardEnhancementsEvent) Contains

func (e KeyboardEnhancementsEvent) Contains(enhancements int) bool

Contains reports whether m contains the given enhancements.

func (KeyboardEnhancementsEvent) SupportsKeyDisambiguation

func (e KeyboardEnhancementsEvent) SupportsKeyDisambiguation() bool

SupportsKeyDisambiguation returns whether the terminal supports reporting disambiguous keys as escape codes.

func (KeyboardEnhancementsEvent) SupportsKeyReleases

func (e KeyboardEnhancementsEvent) SupportsKeyReleases() bool

SupportsKeyReleases returns whether the terminal supports key release events.

func (KeyboardEnhancementsEvent) SupportsUniformKeyLayout

func (e KeyboardEnhancementsEvent) SupportsUniformKeyLayout() bool

SupportsUniformKeyLayout returns whether the terminal supports reporting key events as though they were on a PC-101 layout.

type KittyGraphicsEvent

type KittyGraphicsEvent struct {
	Options kitty.Options
	Payload []byte
}

KittyGraphicsEvent represents a Kitty Graphics response event.

See https://sw.kovidgoyal.net/kitty/graphics-protocol/

type LegacyKeyEncoding

type LegacyKeyEncoding uint32

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>.

func (LegacyKeyEncoding) Backspace

func (l LegacyKeyEncoding) Backspace(v bool) LegacyKeyEncoding

Backspace returns a LegacyKeyEncoding with whether the backspace key is mapped to ansi.BS (0x08) instead of ansi.DEL (0x7F).

func (LegacyKeyEncoding) CtrlAt

CtrlAt returns a LegacyKeyEncoding with whether ansi.NUL (0x00) is mapped to ctrl+at instead of ctrl+space.

func (LegacyKeyEncoding) CtrlI

CtrlI returns a LegacyKeyEncoding with whether ansi.HT (0x09) is mapped to ctrl+i instead of the tab key.

func (LegacyKeyEncoding) CtrlM

CtrlM returns a LegacyKeyEncoding with whether ansi.CR (0x0D) is mapped to ctrl+m instead of the enter key.

func (LegacyKeyEncoding) CtrlOpenBracket

func (l LegacyKeyEncoding) CtrlOpenBracket(v bool) LegacyKeyEncoding

CtrlOpenBracket returns a LegacyKeyEncoding with whether ansi.ESC (0x1B) is mapped to ctrl+[ instead of the escape key.

func (LegacyKeyEncoding) FKeys

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.

func (LegacyKeyEncoding) Find

Find returns a LegacyKeyEncoding with whether the legacy find key is mapped to the home key.

func (LegacyKeyEncoding) Select

Select returns a LegacyKeyEncoding with whether the legacy select key is mapped to the end key.

type LightColorSchemeEvent

type LightColorSchemeEvent struct{}

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.

type Line

type Line []Cell

Line represents cells in a line.

func NewLine

func NewLine(width int) Line

NewLine creates a new line with the given width, filled with empty cells.

func (Line) At

func (l Line) At(x int) *Cell

At returns the cell at the given x position. If the cell does not exist, it returns nil.

func (Line) Render

func (l Line) Render() string

Render renders the line to a string with all the required attributes and styles.

func (Line) Set

func (l Line) Set(x int, c *Cell)

Set sets the cell at the given x position.

func (Line) String

func (l Line) String() string

String returns the string representation of the line. Any trailing spaces are removed.

type LineData

type LineData struct {
	// First and last changed cell indices.
	FirstCell, LastCell int
	// contains filtered or unexported fields
}

LineData represents the metadata for a line.

type Lines

type Lines []Line

Lines represents a slice of lines.

func (Lines) Height

func (ls Lines) Height() int

Height returns the height of the lines.

func (Lines) Render

func (ls Lines) Render() string

Render renders the lines to a styled string with all the required attributes and styles.

func (Lines) String

func (ls Lines) String() string

String returns the string representation of the lines.

func (Lines) Width

func (ls Lines) Width() int

Width returns the width of the widest line.

type Link struct {
	URL    string
	Params string
}

Link represents a hyperlink in the terminal screen.

func ConvertLink(h Link, p colorprofile.Profile) Link

ConvertLink converts a hyperlink to respect the given color profile.

func NewLink(url string, params ...string) Link

NewLink creates a new hyperlink with the given URL and parameters.

func (*Link) Equal

func (h *Link) Equal(o *Link) bool

Equal returns whether the hyperlink is equal to the other hyperlink.

func (*Link) IsZero

func (h *Link) IsZero() bool

IsZero returns whether the hyperlink is empty.

func (*Link) String

func (h *Link) String() string

String returns a string representation of the hyperlink.

type Logger

type Logger interface {
	Printf(format string, v ...interface{})
}

Logger is a simple logger interface.

type ModeReportEvent

type ModeReportEvent struct {
	// Mode is the mode number.
	Mode ansi.Mode

	// Value is the mode value.
	Value ansi.ModeSetting
}

ModeReportEvent is a message that represents a mode report event (DECRPM).

See: https://vt100.net/docs/vt510-rm/DECRPM.html

type ModifyOtherKeysEvent

type ModifyOtherKeysEvent struct {
	Mode int
}

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

type Mouse

type Mouse struct {
	X, Y   int
	Button MouseButton
	Mod    KeyMod
}

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.

// 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)
}

func (Mouse) String

func (m Mouse) String() (s string)

String returns a string representation of the mouse message.

type MouseButton

type MouseButton = ansi.MouseButton

MouseButton represents the button that was pressed during a mouse message.

type MouseClickEvent

type MouseClickEvent Mouse

MouseClickEvent represents a mouse button click event.

func (MouseClickEvent) Mouse

func (e MouseClickEvent) Mouse() Mouse

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.

func (MouseClickEvent) String

func (e MouseClickEvent) String() string

String returns a string representation of the mouse click event.

type MouseEvent

type MouseEvent interface {
	fmt.Stringer

	// Mouse returns the underlying mouse event.
	Mouse() Mouse
}

MouseEvent represents a mouse message. This is a generic mouse message that can represent any kind of mouse event.

type MouseMode

type MouseMode byte

MouseMode represents the mouse mode for the terminal. It is used to enable or disable mouse support on the terminal.

const (
	MouseModeNone MouseMode = iota
	MouseModeClick
	MouseModeDrag
	MouseModeMotion
)

Mouse modes.

type MouseMotionEvent

type MouseMotionEvent Mouse

MouseMotionEvent represents a mouse motion event.

func (MouseMotionEvent) Mouse

func (e MouseMotionEvent) Mouse() Mouse

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.

func (MouseMotionEvent) String

func (e MouseMotionEvent) String() string

String returns a string representation of the mouse motion event.

type MouseReleaseEvent

type MouseReleaseEvent Mouse

MouseReleaseEvent represents a mouse button release event.

func (MouseReleaseEvent) Mouse

func (e MouseReleaseEvent) Mouse() Mouse

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.

func (MouseReleaseEvent) String

func (e MouseReleaseEvent) String() string

String returns a string representation of the mouse release event.

type MouseWheelEvent

type MouseWheelEvent Mouse

MouseWheelEvent represents a mouse wheel message event.

func (MouseWheelEvent) Mouse

func (e MouseWheelEvent) Mouse() Mouse

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.

func (MouseWheelEvent) String

func (e MouseWheelEvent) String() string

String returns a string representation of the mouse wheel event.

type MultiEvent

type MultiEvent []Event

MultiEvent represents multiple messages event.

func (MultiEvent) String

func (e MultiEvent) String() string

String returns a string representation of the multiple messages event.

type Options

type Options struct {
	// BufferSize is the size of the input buffer used for reading terminal
	// events. If zero, [DefaultBufferSize] is used.
	BufferSize int

	// EventTimeout is the duration to wait for input events before timing out.
	// If zero, a default of 100 milliseconds is used.
	EventTimeout time.Duration

	// LegacyKeyEncoding represents any legacy key encoding ambiguities. By
	// default, the terminal will use its preferred key encoding settings.
	LegacyKeyEncoding LegacyKeyEncoding

	// 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.
	LookupKeys bool

	// 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.
	UseTerminfoKeys bool
}

Options represents options for creating a new Terminal.

func DefaultOptions

func DefaultOptions() *Options

DefaultOptions returns the default Terminal options.

type PasteEndEvent

type PasteEndEvent struct{}

PasteEndEvent is an message that is emitted when the terminal ends the bracketed-paste text.

type PasteEvent

type PasteEvent struct {
	// Content is the pasted text content.
	Content string
}

PasteEvent is an message that is emitted when a terminal receives pasted text using bracketed-paste.

func (PasteEvent) String

func (e PasteEvent) String() string

String returns the pasted content as a string.

type PasteStartEvent

type PasteStartEvent struct{}

PasteStartEvent is an message that is emitted when the terminal starts the bracketed-paste text.

type PixelSizeEvent

type PixelSizeEvent Size

PixelSizeEvent represents the window size in pixels.

func (PixelSizeEvent) Bounds

func (s PixelSizeEvent) Bounds() Rectangle

Bounds returns the bounds corresponding to the size.

type Position

type Position = image.Point

Position represents a position in a coordinate system.

func Pos

func Pos(x, y int) Position

Pos is a shorthand for creating a new Position.

type PrimaryDeviceAttributesEvent

type PrimaryDeviceAttributesEvent []int

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.

type ProgressBar

type ProgressBar struct {
	// State is the current state of the progress bar. It can be one of
	// [ProgressBarNone], [ProgressBarDefault], [ProgressBarError],
	// [ProgressBarIndeterminate], and [ProgressBarWarning].
	State ProgressBarState
	// Value is the current value of the progress bar. It should be between
	// 0 and 100.
	Value int
}

ProgressBar represents the terminal progress bar.

Support depends on the terminal.

See https://learn.microsoft.com/en-us/windows/terminal/tutorials/progress-bar-sequences

func NewProgressBar

func NewProgressBar(state ProgressBarState, value int) *ProgressBar

NewProgressBar returns a new progress bar with the given state and value. The value is ignored if the state is ProgressBarNone or ProgressBarIndeterminate.

type ProgressBarState

type ProgressBarState int

ProgressBarState represents the state of the progress bar.

const (
	ProgressBarNone ProgressBarState = iota
	ProgressBarDefault
	ProgressBarError
	ProgressBarIndeterminate
	ProgressBarWarning
)

Progress bar states.

func (ProgressBarState) String

func (s ProgressBarState) String() string

String return a human-readable value for the given ProgressBarState.

type Rectangle

type Rectangle = image.Rectangle

Rectangle represents a rectangular area.

func Rect

func Rect(x, y, w, h int) Rectangle

Rect is a shorthand for creating a new Rectangle.

type RenderBuffer

type RenderBuffer struct {
	*Buffer
	Touched []*LineData
}

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.

func NewRenderBuffer

func NewRenderBuffer(width, height int) *RenderBuffer

NewRenderBuffer creates a new RenderBuffer with the given width and height.

func (*RenderBuffer) DeleteCell

func (b *RenderBuffer) DeleteCell(x, y, n int, c *Cell)

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.

func (*RenderBuffer) DeleteCellArea

func (b *RenderBuffer) DeleteCellArea(x, y, n int, c *Cell, area Rectangle)

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.

func (*RenderBuffer) DeleteLine

func (b *RenderBuffer) DeleteLine(y, n int, c *Cell)

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.

func (*RenderBuffer) DeleteLineArea

func (b *RenderBuffer) DeleteLineArea(y, n int, c *Cell, area Rectangle)

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.

func (*RenderBuffer) InsertCell

func (b *RenderBuffer) InsertCell(x, y, n int, c *Cell)

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.

func (*RenderBuffer) InsertCellArea

func (b *RenderBuffer) InsertCellArea(x, y, n int, c *Cell, area Rectangle)

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.

func (*RenderBuffer) InsertLine

func (b *RenderBuffer) InsertLine(y, n int, c *Cell)

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.

func (*RenderBuffer) InsertLineArea

func (b *RenderBuffer) InsertLineArea(y, n int, c *Cell, area Rectangle)

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.

func (*RenderBuffer) SetCell

func (b *RenderBuffer) SetCell(x, y int, c *Cell)

SetCell sets the cell at the given x, y position and marks the line as touched.

func (*RenderBuffer) Touch

func (b *RenderBuffer) Touch(x, y int)

Touch marks the cell at the given x, y position as touched.

func (*RenderBuffer) TouchLine

func (b *RenderBuffer) TouchLine(x, y, n int)

TouchLine marks a line n times starting at the given x position as touched.

func (*RenderBuffer) TouchedLines

func (b *RenderBuffer) TouchedLines() int

TouchedLines returns the number of touched lines in the buffer.

type Screen

type Screen interface {
	// Bounds returns the bounds of the screen. This is the rectangle that
	// includes the start and end points of the screen.
	Bounds() Rectangle

	// 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).
	CellAt(x, y int) *Cell

	// 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.
	SetCell(x, y int, c *Cell)

	// WidthMethod returns the width method used by the screen.
	WidthMethod() WidthMethod
}

Screen represents a screen that can be drawn to.

type ScreenBuffer

type ScreenBuffer struct {
	*RenderBuffer
	Method ansi.Method
}

ScreenBuffer is a buffer that can be used as a Screen.

func NewScreenBuffer

func NewScreenBuffer(width, height int) ScreenBuffer

NewScreenBuffer creates a new ScreenBuffer with the given width and height.

func (ScreenBuffer) WidthMethod

func (s ScreenBuffer) WidthMethod() WidthMethod

WidthMethod returns the width method used by the screen. It defaults to ansi.WcWidth.

type SecondaryDeviceAttributesEvent

type SecondaryDeviceAttributesEvent []int

SecondaryDeviceAttributesEvent is an event that represents the terminal secondary device attributes.

See ansi.SecondaryDeviceAttributes for more details.

type Side

type Side struct {
	Content string
	Style
	Link
}

Side represents a single border side with its properties.

type Size

type Size struct {
	Width  int
	Height int
}

Size represents the size of the terminal window.

func (Size) Bounds

func (s Size) Bounds() Rectangle

Bounds returns the bounds corresponding to the size.

type SizeNotifier

type SizeNotifier struct {
	// Channel that receives terminal size change notifications.
	C <-chan os.Signal
	// contains filtered or unexported fields
}

SizeNotifier represents a notifier that listens for window size changes using the SIGWINCH signal and notifies the given channel.

func NewSizeNotifier

func NewSizeNotifier(f term.File) *SizeNotifier

NewSizeNotifier creates a new SizeNotifier that listens for window size changes on the given TTY file through SIGWINCH signals.

func (*SizeNotifier) GetSize

func (n *SizeNotifier) GetSize() (width, height int, err error)

GetSize returns the current cell size of the terminal window.

func (*SizeNotifier) GetWindowSize

func (n *SizeNotifier) GetWindowSize() (cells Size, pixels Size, err error)

GetWindowSize returns the current size of the terminal window.

func (*SizeNotifier) Start

func (n *SizeNotifier) Start() error

Start starts listening for window size changes and notifies [SizeNotifier.C] about any changes.

func (*SizeNotifier) Stop

func (n *SizeNotifier) Stop() error

Stop stops the notifier and cleans up resources.

type Style

type Style struct {
	Fg             color.Color
	Bg             color.Color
	UnderlineColor color.Color
	Underline      Underline
	Attrs          uint8
}

Style represents the style of a cell.

func ConvertStyle

func ConvertStyle(s Style, p colorprofile.Profile) Style

ConvertStyle converts a style to respect the given color profile.

func (*Style) Diff

func (s *Style) Diff(from *Style) string

Diff returns the ANSI sequence that sets the style as a diff from another style.

func (*Style) Equal

func (s *Style) Equal(o *Style) bool

Equal returns true if the style is equal to the other style.

func (*Style) IsZero

func (s *Style) IsZero() bool

IsZero returns true if the style is empty.

func (*Style) String

func (s *Style) String() string

String returns the ANSI SGR sequence for the style.

func (*Style) Styled

func (s *Style) Styled(str string) string

Styled wraps the given string with the style's ANSI sequences and resets.

type StyledString

type StyledString struct {
	// Text is the original string that was used to create the styled string.
	Text string
	// Wrap determines whether the styled string should wrap to the next line.
	Wrap bool
	// 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.
	Tail string
}

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.

func NewStyledString

func NewStyledString(str string) *StyledString

NewStyledString creates a new StyledString for the given method and styled string. The method is used to calculate the width of each line.

func (*StyledString) Bounds

func (s *StyledString) Bounds() Rectangle

Bounds returns the minimum area that can contain the whole styled string.

func (*StyledString) Draw

func (s *StyledString) Draw(buf Screen, area Rectangle)

Draw renders the styled string to the given buffer at the specified area.

func (*StyledString) Height

func (s *StyledString) Height() int

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.

func (*StyledString) Lines

func (s *StyledString) Lines(m ansi.Method) []Line

Lines returns the styled string decomposed into a slice of [Line]s.

func (*StyledString) String

func (s *StyledString) String() string

String returns the text of the styled string.

It implements the fmt.Stringer interface.

func (*StyledString) UnicodeWidth

func (s *StyledString) UnicodeWidth() int

UnicodeWidth returns the cells width of the widest line in the styled string using the ansi.GraphemeWidth method.

func (*StyledString) WcWidth

func (s *StyledString) WcWidth() int

WcWidth returns the cells width of the widest line in the styled string using the ansi.WcWidth method.

type TTY

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

TTY represents a Unix TTY device. It implements the Console interface.

func (TTY) Close

func (t TTY) Close() error

Close restores the console to its previous state and releases resources.

func (TTY) Environ

func (t TTY) Environ() []string

Environ returns the console's environment variables.

func (TTY) GetSize

func (t TTY) GetSize() (width, height int, err error)

GetSize returns the current size of the console.

func (TTY) GetWinsize

func (t TTY) GetWinsize() (*Winsize, error)

GetWinsize returns the current size of the console in cells and pixels.

func (TTY) Getenv

func (t TTY) Getenv(key string) string

Getenv retrieves the value of the environment variable named by the key.

func (TTY) LookupEnv

func (t TTY) LookupEnv(key string) (string, bool)

LookupEnv retrieves the value of the environment variable named by the key and a boolean indicating whether the variable is present.

func (TTY) MakeRaw

func (t TTY) MakeRaw() (state *term.State, err error)

MakeRaw puts the console input side into raw mode.

func (TTY) Read

func (t TTY) Read(p []byte) (n int, err error)

Read reads data from the console's input.

func (TTY) Reader

func (t TTY) Reader() io.Reader

Reader returns the input reader of the console.

func (TTY) Restore

func (t TTY) Restore() error

Restore restores the console to its previous state.

func (TTY) Write

func (t TTY) Write(p []byte) (n int, err error)

Write writes data to the console's output.

func (TTY) Writer

func (t TTY) Writer() io.Writer

Writer returns the output writer of the console.

type TabStops

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

TabStops represents horizontal line tab stops.

func DefaultTabStops

func DefaultTabStops(cols int) *TabStops

DefaultTabStops creates a new set of tab stops with the default interval.

func NewTabStops

func NewTabStops(width, interval int) *TabStops

NewTabStops creates a new set of tab stops from a number of columns and an interval.

func (*TabStops) Clear

func (ts *TabStops) Clear()

Clear removes all tab stops.

func (TabStops) Find

func (ts TabStops) Find(col, delta int) int

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.

func (TabStops) IsStop

func (ts TabStops) IsStop(col int) bool

IsStop returns true if the given column is a tab stop.

func (TabStops) Next

func (ts TabStops) Next(col int) int

Next returns the next tab stop after the given column.

func (TabStops) Prev

func (ts TabStops) Prev(col int) int

Prev returns the previous tab stop before the given column.

func (*TabStops) Reset

func (ts *TabStops) Reset(col int)

Reset removes the tab stop at the given column.

func (*TabStops) Resize

func (ts *TabStops) Resize(width int)

Resize resizes the tab stops to the given width.

func (*TabStops) Set

func (ts *TabStops) Set(col int)

Set adds a tab stop at the given column.

func (*TabStops) Width

func (ts *TabStops) Width() int

Width returns the width of the screen that the tab stops are set for.

type Terminal

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

Terminal represents an interactive terminal application.

func ControllingTerminal

func ControllingTerminal() (*Terminal, error)

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.

func DefaultTerminal

func DefaultTerminal() *Terminal

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.

func NewTerminal

func NewTerminal(con Console, opts *Options) *Terminal

NewTerminal creates a new Terminal instance with the given console and options. Options can be nil to use the default options.

func (*Terminal) Events

func (t *Terminal) Events() <-chan Event

Events returns the terminal's event channel.

func (*Terminal) Read

func (t *Terminal) Read(p []byte) (n int, err error)

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.

func (*Terminal) Screen

func (t *Terminal) Screen() *TerminalScreen

Screen returns the terminal's screen.

func (*Terminal) SendEvent

func (t *Terminal) SendEvent(e Event)

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.

func (*Terminal) SetLogger

func (t *Terminal) SetLogger(logger Logger)

SetLogger sets the terminal's logger for tracing I/O operations.

func (*Terminal) Start

func (t *Terminal) Start() error

Start starts the terminal application event loop. This is a non-blocking call. Use Terminal.Wait to wait for the terminal to exit.

func (*Terminal) Stop

func (t *Terminal) Stop() error

Stop stops the terminal event loop. This is a non-blocking call. Use Terminal.Wait to wait for the terminal to exit.

func (*Terminal) Wait

func (t *Terminal) Wait() error

Wait waits for the terminal event loop to exit and returns any error that occurred.

func (*Terminal) Write

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

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.

type TerminalReader

type TerminalReader struct {
	EventDecoder

	// 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.
	MouseMode *MouseMode

	// 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).
	EscTimeout time.Duration
	// contains filtered or unexported fields
}

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.

func NewTerminalReader

func NewTerminalReader(r io.Reader, termType string) *TerminalReader

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)
```

func (*TerminalReader) SetLogger

func (d *TerminalReader) SetLogger(logger Logger)

SetLogger sets the logger to use for debugging. If nil, no logging will be performed.

func (*TerminalReader) StreamEvents

func (d *TerminalReader) StreamEvents(ctx context.Context, eventc chan<- Event) error

StreamEvents sends events to the provided channel. It stops when the context is closed or when an error occurs.

type TerminalRenderer

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

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.

func NewTerminalRenderer

func NewTerminalRenderer(w io.Writer, env []string) (s *TerminalRenderer)

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.

func (*TerminalRenderer) Buffered

func (s *TerminalRenderer) Buffered() int

Buffered returns the number of bytes buffered for the next flush.

func (*TerminalRenderer) EnterAltScreen

func (s *TerminalRenderer) EnterAltScreen()

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.

func (*TerminalRenderer) Erase

func (s *TerminalRenderer) Erase()

Erase marks the screen to be fully erased on the next render.

func (*TerminalRenderer) ExitAltScreen

func (s *TerminalRenderer) ExitAltScreen()

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.

func (*TerminalRenderer) Flush

func (s *TerminalRenderer) Flush() (err error)

Flush flushes the buffer to the screen.

func (*TerminalRenderer) Fullscreen

func (s *TerminalRenderer) Fullscreen() bool

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.

func (*TerminalRenderer) MoveTo

func (s *TerminalRenderer) MoveTo(x, y int)

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.

func (*TerminalRenderer) Position

func (s *TerminalRenderer) Position() (x, y int)

Position returns the cursor position in the screen buffer after applying any pending transformations from the underlying buffer.

func (*TerminalRenderer) PrependString

func (s *TerminalRenderer) PrependString(newbuf *RenderBuffer, str string)

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.

func (*TerminalRenderer) Redraw

func (s *TerminalRenderer) Redraw(newbuf *RenderBuffer)

Redraw forces a full redraw of the screen. It's equivalent to calling TerminalRenderer.Erase and TerminalRenderer.Render.

func (*TerminalRenderer) Render

func (s *TerminalRenderer) Render(newbuf *RenderBuffer)

Render renders changes of the screen to the internal buffer. Call [terminalWriter.Flush] to flush pending changes to the screen.

func (*TerminalRenderer) Resize

func (s *TerminalRenderer) Resize(width, _ int)

Resize updates the terminal screen tab stops. This is used to calculate terminal tab stops for hard tab optimizations.

func (*TerminalRenderer) RestoreCursor

func (s *TerminalRenderer) RestoreCursor()

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.

func (*TerminalRenderer) SaveCursor

func (s *TerminalRenderer) SaveCursor()

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.

func (*TerminalRenderer) SetBackspace

func (s *TerminalRenderer) SetBackspace(v bool)

SetBackspace sets whether to use backspace as a movement optimization.

func (*TerminalRenderer) SetColorProfile

func (s *TerminalRenderer) SetColorProfile(profile colorprofile.Profile)

SetColorProfile sets the color profile to use for downsampling colors. This is used to determine the appropriate color the terminal can display.

func (*TerminalRenderer) SetFullscreen

func (s *TerminalRenderer) SetFullscreen(v bool)

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.

func (*TerminalRenderer) SetLogger

func (s *TerminalRenderer) SetLogger(logger Logger)

SetLogger sets the logger to use for debugging. If nil, no logging will be performed.

func (*TerminalRenderer) SetMapNewline

func (s *TerminalRenderer) SetMapNewline(v bool)

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.

func (*TerminalRenderer) SetPosition

func (s *TerminalRenderer) SetPosition(x, y int)

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.

func (*TerminalRenderer) SetRelativeCursor

func (s *TerminalRenderer) SetRelativeCursor(v bool)

SetRelativeCursor sets whether to use relative cursor movements.

func (*TerminalRenderer) SetScrollOptim

func (s *TerminalRenderer) SetScrollOptim(v bool)

SetScrollOptim sets whether to use hard scroll optimizations.

func (*TerminalRenderer) SetTabStops

func (s *TerminalRenderer) SetTabStops(width int)

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.

func (*TerminalRenderer) Write

func (s *TerminalRenderer) Write(b []byte) (int, error)

Write writes the given bytes to the underlying buffer.

func (*TerminalRenderer) WriteString

func (s *TerminalRenderer) WriteString(str string) (int, error)

WriteString writes the given string to the underlying buffer.

type TerminalScreen

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

TerminalScreen represents a terminal screen, providing methods for managing the screen state and rendering content.

func NewTerminalScreen

func NewTerminalScreen(w io.Writer, env Environ) *TerminalScreen

NewTerminalScreen creates a new TerminalScreen with the given writer and environment.

func (*TerminalScreen) AltScreen

func (s *TerminalScreen) AltScreen() bool

AltScreen returns whether the terminal is currently in the alternate screen buffer.

func (*TerminalScreen) BackgroundColor

func (s *TerminalScreen) BackgroundColor() color.Color

BackgroundColor returns the current background color of the terminal.

A nil color indicates that the background color is the default terminal background color.

func (*TerminalScreen) Bounds

func (s *TerminalScreen) Bounds() Rectangle

Bounds returns the bounds of the terminal screen as a rectangle.

func (*TerminalScreen) BracketedPaste

func (s *TerminalScreen) BracketedPaste() bool

BracketedPaste returns whether bracketed paste mode is currently enabled.

func (*TerminalScreen) CellAt

func (s *TerminalScreen) CellAt(x, y int) *Cell

CellAt returns the cell at the specified x and y coordinates.

func (*TerminalScreen) CursorColor

func (s *TerminalScreen) CursorColor() color.Color

CursorColor returns the current color of the terminal cursor.

A nil color indicates that the cursor color is the default terminal cursor color.

func (*TerminalScreen) CursorPosition

func (s *TerminalScreen) CursorPosition() (x, y int)

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.

func (*TerminalScreen) CursorStyle

func (s *TerminalScreen) CursorStyle() (shape CursorShape, blink bool)

CursorStyle returns the current style of the terminal cursor.

func (*TerminalScreen) CursorVisible

func (s *TerminalScreen) CursorVisible() bool

CursorVisible returns whether the terminal cursor is currently visible.

func (*TerminalScreen) DisableBracketedPaste

func (s *TerminalScreen) DisableBracketedPaste() error

DisableBracketedPaste disables bracketed paste mode.

The changes can be committed to the underlying writer by calling the TerminalScreen.Flush method.

func (*TerminalScreen) Display

func (s *TerminalScreen) Display(d Drawable) error

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.

func (*TerminalScreen) EnableBracketedPaste

func (s *TerminalScreen) EnableBracketedPaste() error

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.

func (*TerminalScreen) EnterAltScreen

func (s *TerminalScreen) EnterAltScreen() error

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.

func (*TerminalScreen) ExitAltScreen

func (s *TerminalScreen) ExitAltScreen() error

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.

func (*TerminalScreen) Flush

func (s *TerminalScreen) Flush() error

Flush writes any pending output to the underlying writer.

func (*TerminalScreen) ForegroundColor

func (s *TerminalScreen) ForegroundColor() color.Color

ForegroundColor returns the current foreground color of the terminal.

A nil color indicates that the foreground color is the default terminal foreground color.

func (*TerminalScreen) HideCursor

func (s *TerminalScreen) HideCursor() error

HideCursor hides the terminal cursor.

The changes can be committed to the underlying writer by calling the TerminalScreen.Flush method.

func (*TerminalScreen) InsertAbove

func (s *TerminalScreen) InsertAbove(content string) error

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.

func (*TerminalScreen) KeyboardEnhancements

func (s *TerminalScreen) KeyboardEnhancements() *KeyboardEnhancements

KeyboardEnhancements returns the current keyboard enhancements of the terminal.

A nil value indicates that no keyboard enhancements are currently enabled.

func (*TerminalScreen) MouseMode

func (s *TerminalScreen) MouseMode() MouseMode

MouseMode returns the current mouse mode of the terminal.

func (*TerminalScreen) ProgressBar

func (s *TerminalScreen) ProgressBar() *ProgressBar

ProgressBar returns the current progress bar of the terminal.

A nil value indicates that no progress bar is currently set.

func (*TerminalScreen) Render

func (s *TerminalScreen) Render() error

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.

func (*TerminalScreen) Reset

func (s *TerminalScreen) Reset() error

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.

func (*TerminalScreen) Resize

func (s *TerminalScreen) Resize(width, height int) error

Resize resizes the terminal screen to the specified width and height, updating the render buffer and renderer accordingly.

func (*TerminalScreen) Restore

func (s *TerminalScreen) Restore() error

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.

func (*TerminalScreen) SetBackgroundColor

func (s *TerminalScreen) SetBackgroundColor(c color.Color) error

SetBackgroundColor sets the background color of the terminal.

The changes can be committed to the underlying writer by calling the TerminalScreen.Flush method.

func (*TerminalScreen) SetCell

func (s *TerminalScreen) SetCell(x, y int, cell *Cell)

SetCell sets the cell at the specified x and y coordinates.

func (*TerminalScreen) SetColorProfile

func (s *TerminalScreen) SetColorProfile(profile colorprofile.Profile)

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.

func (*TerminalScreen) SetCursorColor

func (s *TerminalScreen) SetCursorColor(c color.Color) error

SetCursorColor sets the color of the terminal cursor.

The changes can be committed to the underlying writer by calling the TerminalScreen.Flush method.

func (*TerminalScreen) SetCursorPosition

func (s *TerminalScreen) SetCursorPosition(x, y int) error

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.

func (*TerminalScreen) SetCursorStyle

func (s *TerminalScreen) SetCursorStyle(shape CursorShape, blink bool) error

SetCursorStyle sets the style of the terminal cursor.

The changes can be committed to the underlying writer by calling the TerminalScreen.Flush method.

func (*TerminalScreen) SetForegroundColor

func (s *TerminalScreen) SetForegroundColor(c color.Color) error

SetForegroundColor sets the foreground color of the terminal.

The changes can be committed to the underlying writer by calling the TerminalScreen.Flush method.

func (*TerminalScreen) SetKeyboardEnhancements

func (s *TerminalScreen) SetKeyboardEnhancements(enh *KeyboardEnhancements) error

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.

func (*TerminalScreen) SetMouseMode

func (s *TerminalScreen) SetMouseMode(mode MouseMode) error

SetMouseMode sets the mouse 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.

func (*TerminalScreen) SetProgressBar

func (s *TerminalScreen) SetProgressBar(pb *ProgressBar) error

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.

func (*TerminalScreen) SetWidthMethod

func (s *TerminalScreen) SetWidthMethod(method ansi.Method)

SetWidthMethod sets the width method for the terminal screen.

func (*TerminalScreen) SetWindowTitle

func (s *TerminalScreen) SetWindowTitle(title string) error

SetWindowTitle sets the title of the terminal window.

The changes can be committed to the underlying writer by calling the TerminalScreen.Flush method.

func (*TerminalScreen) ShowCursor

func (s *TerminalScreen) ShowCursor() error

ShowCursor shows the terminal cursor.

The changes can be committed to the underlying writer by calling the TerminalScreen.Flush method.

func (*TerminalScreen) WidthMethod

func (s *TerminalScreen) WidthMethod() WidthMethod

WidthMethod returns the width method used by the terminal screen.

func (*TerminalScreen) WindowTitle

func (s *TerminalScreen) WindowTitle() string

WindowTitle returns the current title of the terminal window.

func (*TerminalScreen) Write

func (s *TerminalScreen) Write(p []byte) (n int, err error)

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.

func (*TerminalScreen) WriteString

func (s *TerminalScreen) WriteString(str string) (n int, err error)

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.

type TerminalVersionEvent

type TerminalVersionEvent struct {
	Name string
}

TerminalVersionEvent is a message that represents the terminal version.

func (TerminalVersionEvent) String

func (e TerminalVersionEvent) String() string

String returns the terminal version as a string.

type TertiaryDeviceAttributesEvent

type TertiaryDeviceAttributesEvent string

TertiaryDeviceAttributesEvent is an event that represents the terminal tertiary device attributes.

See ansi.TertiaryDeviceAttributes for more details.

type Underline

type Underline = ansi.Underline

Underline is the style of underline to use for text.

type UnderlineStyle deprecated

type UnderlineStyle = ansi.Underline

UnderlineStyle is the style of underline to use for text.

Deprecated: Use Underline instead.

type UnknownApcEvent

type UnknownApcEvent string

UnknownApcEvent represents an unknown APC (Application Program Command) event.

func (UnknownApcEvent) String

func (e UnknownApcEvent) String() string

String returns a string representation of the unknown APC event.

type UnknownCsiEvent

type UnknownCsiEvent string

UnknownCsiEvent represents an unknown CSI (Control Sequence Introducer) event.

func (UnknownCsiEvent) String

func (e UnknownCsiEvent) String() string

String returns a string representation of the unknown CSI event.

type UnknownDcsEvent

type UnknownDcsEvent string

UnknownDcsEvent represents an unknown DCS (Device Control String) event.

func (UnknownDcsEvent) String

func (e UnknownDcsEvent) String() string

String returns a string representation of the unknown DCS event.

type UnknownEvent

type UnknownEvent string

UnknownEvent represents an unknown event.

func (UnknownEvent) String

func (e UnknownEvent) String() string

String returns a string representation of the unknown event.

type UnknownOscEvent

type UnknownOscEvent string

UnknownOscEvent represents an unknown OSC (Operating System Command) event.

func (UnknownOscEvent) String

func (e UnknownOscEvent) String() string

String returns a string representation of the unknown OSC event.

type UnknownPmEvent

type UnknownPmEvent string

UnknownPmEvent represents an unknown PM (Privacy Message) event.

func (UnknownPmEvent) String

func (e UnknownPmEvent) String() string

String returns a string representation of the unknown PM event.

type UnknownSosEvent

type UnknownSosEvent string

UnknownSosEvent represents an unknown SOS (Start of String) event.

func (UnknownSosEvent) String

func (e UnknownSosEvent) String() string

String returns a string representation of the unknown SOS event.

type UnknownSs3Event

type UnknownSs3Event string

UnknownSs3Event represents an unknown SS3 (Single Shift 3) event.

func (UnknownSs3Event) String

func (e UnknownSs3Event) String() string

String returns a string representation of the unknown SS3 event.

type WidthMethod

type WidthMethod interface {
	StringWidth(s string) int
}

WidthMethod determines how many columns a grapheme occupies on the screen.

type WinCon

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

WinCon represents a Windows Console. It implements the Console interface.

func (WinCon) Close

func (t WinCon) Close() error

Close restores the console to its previous state and releases resources.

func (WinCon) Environ

func (t WinCon) Environ() []string

Environ returns the console's environment variables.

func (WinCon) GetSize

func (t WinCon) GetSize() (width, height int, err error)

GetSize returns the current size of the console.

func (WinCon) GetWinsize

func (t WinCon) GetWinsize() (*Winsize, error)

GetWinsize returns the current size of the console in cells and pixels.

func (WinCon) Getenv

func (t WinCon) Getenv(key string) string

Getenv retrieves the value of the environment variable named by the key.

func (WinCon) LookupEnv

func (t WinCon) LookupEnv(key string) (string, bool)

LookupEnv retrieves the value of the environment variable named by the key and a boolean indicating whether the variable is present.

func (WinCon) MakeRaw

func (t WinCon) MakeRaw() (state *term.State, err error)

MakeRaw puts the console input side into raw mode.

func (WinCon) Read

func (t WinCon) Read(p []byte) (n int, err error)

Read reads data from the console's input.

func (WinCon) Reader

func (t WinCon) Reader() io.Reader

Reader returns the input reader of the console.

func (WinCon) Restore

func (t WinCon) Restore() error

Restore restores the console to its previous state.

func (WinCon) Write

func (t WinCon) Write(p []byte) (n int, err error)

Write writes data to the console's output.

func (WinCon) Writer

func (t WinCon) Writer() io.Writer

Writer returns the output writer of the console.

type Window

type Window struct {
	*Buffer
	// contains filtered or unexported fields
}

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).

func NewScreen

func NewScreen(width, height int) *Window

NewScreen creates a new root Window with the given size and width method.

This will panic if width or height is negative.

func (*Window) Bounds

func (w *Window) Bounds() Rectangle

Bounds returns the bounds of the window as a rectangle.

func (*Window) Clone

func (w *Window) Clone() *Window

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.

func (*Window) CloneArea

func (w *Window) CloneArea(area Rectangle) *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.

func (*Window) HasParent

func (w *Window) HasParent() bool

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.

func (*Window) MoveBy

func (w *Window) MoveBy(dx, dy int)

MoveBy moves the window by the specified delta x and delta y.

func (*Window) MoveTo

func (w *Window) MoveTo(x, y int)

MoveTo moves the window to the specified x and y coordinates.

func (*Window) NewView

func (w *Window) NewView(x, y, width, height int) *Window

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.

func (*Window) NewWindow

func (w *Window) NewWindow(x, y, width, height int) *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.

func (*Window) Parent

func (w *Window) Parent() *Window

Parent returns the parent window of the current window. If the window does not have a parent, it returns nil.

func (*Window) Resize

func (w *Window) Resize(width, height int)

Resize resizes the window to the specified width and height.

func (*Window) SetWidthMethod

func (w *Window) SetWidthMethod(method WidthMethod)

SetWidthMethod sets the width method for the window.

func (*Window) WidthMethod

func (w *Window) WidthMethod() WidthMethod

WidthMethod returns the method used to calculate the width of characters in the window.

type WindowOpEvent

type WindowOpEvent struct {
	Op   int
	Args []int
}

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.

type WindowSizeEvent

type WindowSizeEvent Size

WindowSizeEvent represents the window size in cells.

func (WindowSizeEvent) Bounds

func (s WindowSizeEvent) Bounds() Rectangle

Bounds returns the bounds corresponding to the size.

type Winsize

type Winsize struct {
	Row    uint16
	Col    uint16
	Xpixel uint16
	Ypixel uint16
}

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.

Directories

Path Synopsis
Package screen provides functions and helpers to manipulate a uv.Screen.
Package screen provides functions and helpers to manipulate a uv.Screen.

Jump to

Keyboard shortcuts

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