uv

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2025 License: MIT Imports: 37 Imported by: 0

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 (
	NoUnderline     = ansi.NoUnderlineStyle
	SingleUnderline = ansi.SingleUnderlineStyle
	DoubleUnderline = ansi.DoubleUnderlineStyle
	CurlyUnderline  = ansi.CurlyUnderlineStyle
	DottedUnderline = ansi.DottedUnderlineStyle
	DashedUnderline = ansi.DashedUnderlineStyle
)

These are the available underline styles.

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 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 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 returned when one of the I/O streams is not a terminal.
	ErrNotTerminal = fmt.Errorf("not a terminal")

	// ErrPlatformNotSupported is returned when the platform is not supported.
	ErrPlatformNotSupported = fmt.Errorf("platform not supported")

	// ErrStarted is returned when the terminal has already been started.
	ErrStarted = fmt.Errorf("terminal already started")
)
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 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 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 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 Suspend

func Suspend() error

Suspend suspends the current process group.

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
	// Touched represents the lines that have been modified or touched. It is
	// used to track which lines need to be redrawn.
	Touched []*LineData
}

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.

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

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

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

func (*Buffer) TouchLine

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

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

func (*Buffer) Width

func (b *Buffer) Width() int

Width implements Screen.

type CapabilityEvent

type CapabilityEvent 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

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

func (c *Cell) IsBlank() bool

IsBlank returns whether the cell represents a blank cell consisting of a space character.

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

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 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 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 the given string. The 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) MatchStrings

func (k Key) MatchStrings(ss ...string) bool

MatchStrings returns true if the Key matches any of the given strings. The strings can be key names 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. See Key.MatchString for more details.

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 the given string. The 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) MatchStrings

func (k KeyPressEvent) MatchStrings(ss ...string) bool

MatchStrings returns true if the Key matches any of the given strings. The strings can be key names 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. See Key.MatchString for more details.

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 the given string. The 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) MatchStrings

func (k KeyReleaseEvent) MatchStrings(ss ...string) bool

MatchStrings returns true if the Key matches any of the given strings. The strings can be key names 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. See Key.MatchString for more details.

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 KittyEnhancementsEvent

type KittyEnhancementsEvent int

KittyEnhancementsEvent represents a Kitty enhancements event.

func (KittyEnhancementsEvent) Contains

func (e KittyEnhancementsEvent) Contains(enhancements int) bool

Contains reports whether m contains the given enhancements.

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 (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() (s 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 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 uint8

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 (
	// ButtonMouseMode enables basic mouse button clicks and releases.
	ButtonMouseMode MouseMode = 1 << iota
	// DragMouseMode enables basic mouse buttons [ButtonMouseMode] as well as
	// click-and-drag mouse motion events.
	DragMouseMode
	// AllMouseMode enables all mouse events including button clicks, releases,
	// and all motion events. This inclodes the [ButtonMouseMode] and
	// [DragMouseMode] modes.
	AllMouseMode
)

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 PasteEndEvent

type PasteEndEvent struct{}

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

type PasteEvent

type PasteEvent string

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

type PasteStartEvent

type PasteStartEvent struct{}

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

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 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 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 {
	*Buffer
	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 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 Style

type Style struct {
	Fg      color.Color
	Bg      color.Color
	Ul      color.Color
	UlStyle UnderlineStyle
	Attrs   StyleAttrs
}

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 NewStyle

func NewStyle() Style

NewStyle is a convenience function to create a new Style.

func (Style) Background

func (s Style) Background(c color.Color) Style

Background returns a new style with the background color set to the given color.

func (Style) Bold

func (s Style) Bold(v bool) Style

Bold returns a new style with the bold attribute set to the given value.

func (Style) Conceal

func (s Style) Conceal(v bool) Style

Conceal returns a new style with the conceal attribute set to the given value.

func (*Style) DiffSequence

func (s *Style) DiffSequence(o Style) string

DiffSequence 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) Faint

func (s Style) Faint(v bool) Style

Faint returns a new style with the faint attribute set to the given value.

func (Style) Foreground

func (s Style) Foreground(c color.Color) Style

Foreground returns a new style with the foreground color set to the given color.

func (*Style) IsBlank

func (s *Style) IsBlank() bool

IsBlank returns whether the style consists of only attributes that don't affect appearance of a space character.

func (*Style) IsZero

func (s *Style) IsZero() bool

IsZero returns true if the style is empty.

func (Style) Italic

func (s Style) Italic(v bool) Style

Italic returns a new style with the italic attribute set to the given value.

func (s Style) RapidBlink(v bool) Style

RapidBlink returns a new style with the rapid blink attribute set to the given value.

func (Style) Reverse

func (s Style) Reverse(v bool) Style

Reverse returns a new style with the reverse attribute set to the given value.

func (*Style) Sequence

func (s *Style) Sequence() string

Sequence returns the ANSI sequence that sets the style.

func (s Style) SlowBlink(v bool) Style

SlowBlink returns a new style with the slow blink attribute set to the given value.

func (Style) Strikethrough

func (s Style) Strikethrough(v bool) Style

Strikethrough returns a new style with the strikethrough attribute set to the given value.

func (Style) Underline

func (s Style) Underline(c color.Color) Style

Underline returns a new style with the underline color set to the given color.

func (Style) UnderlineStyle

func (s Style) UnderlineStyle(st UnderlineStyle) Style

UnderlineStyle returns a new style with the underline style set to the given style.

type StyleAttrs

type StyleAttrs uint8

StyleAttrs is a bitmask for text attributes that can change the look of text. These attributes can be combined to create different styles.

const (
	BoldAttr StyleAttrs = 1 << iota
	FaintAttr
	ItalicAttr
	SlowBlinkAttr
	RapidBlinkAttr
	ReverseAttr
	ConcealAttr
	StrikethroughAttr

	ResetAttr StyleAttrs = 0
)

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

func (StyleAttrs) Add

func (a StyleAttrs) Add(attr StyleAttrs) StyleAttrs

Add adds the attribute to the attribute mask.

func (StyleAttrs) Contains

func (a StyleAttrs) Contains(attr StyleAttrs) bool

Contains returns whether the attribute mask contains the attribute.

func (StyleAttrs) Remove

func (a StyleAttrs) Remove(attr StyleAttrs) StyleAttrs

Remove removes the attribute from the attribute mask.

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) 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 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 a terminal screen that can be manipulated and drawn to. It handles reading events from the terminal using [WinChReceiver], [SequenceReceiver], and [ConReceiver].

func DefaultTerminal

func DefaultTerminal() *Terminal

DefaultTerminal returns a new default terminal instance that uses os.Stdin, os.Stdout, and os.Environ.

func NewTerminal

func NewTerminal(in io.Reader, out io.Writer, env []string) *Terminal

NewTerminal creates a new Terminal instance with the given terminal size. Use term.GetSize to get the size of the output screen.

func (*Terminal) Bounds

func (t *Terminal) Bounds() Rectangle

Bounds returns the bounds of the terminal screen buffer. This is the rectangle that contains start and end points of the screen buffer. This is different from Terminal.GetSize which queries the size of the terminal window. The screen buffer can occupy a portion or all of the terminal window. Use Terminal.Resize to change the size of the screen buffer.

func (*Terminal) Buffered

func (t *Terminal) Buffered() int

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

func (*Terminal) CellAt

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

CellAt returns the cell at the given x, y position in the terminal buffer.

func (*Terminal) Clear

func (t *Terminal) Clear()

Clear fills the terminal screen with empty cells, and clears the terminal screen.

This is different from Terminal.Erase, which only fills the screen buffer with empty cells without erasing the terminal screen first.

func (*Terminal) ClearArea

func (t *Terminal) ClearArea(area Rectangle)

ClearArea fills the given area of the terminal screen with empty cells.

func (*Terminal) Clone

func (t *Terminal) Clone() *Buffer

Clone returns a copy of the terminal screen buffer. This is useful for creating a snapshot of the current terminal state without modifying the original buffer.

func (*Terminal) CloneArea

func (t *Terminal) CloneArea(area Rectangle) *Buffer

CloneArea clones the given area of the terminal screen and returns a new buffer with the same size as the area. The new buffer will contain the same cells as the area in the terminal screen.

func (*Terminal) Close

func (t *Terminal) Close() error

Close close any resources used by the terminal and restore the terminal to its original state.

func (*Terminal) ColorModel

func (t *Terminal) ColorModel() color.Model

ColorModel returns the color model of the terminal screen.

func (*Terminal) ColorProfile

func (t *Terminal) ColorProfile() colorprofile.Profile

ColorProfile returns the currently used color profile for the terminal.

func (*Terminal) Convert

func (t *Terminal) Convert(c color.Color) color.Color

Convert converts the given color to the terminal's color profile. This implements the color.Model interface, allowing you to convert any color to the terminal's preferred color model.

func (*Terminal) DisableBracketedPaste

func (t *Terminal) DisableBracketedPaste()

DisableBracketedPaste disables bracketed paste mode on the terminal. This is typically used to disable support for pasting text into the terminal.

func (*Terminal) DisableFocusEvents

func (t *Terminal) DisableFocusEvents()

DisableFocusEvents disables focus/blur receiving notification events on the terminal.

func (*Terminal) DisableMode

func (t *Terminal) DisableMode(modes ...ansi.Mode)

DisableMode disables the given modes on the terminal. This is typically used to disable mouse support, bracketed paste mode, and other terminal features.

Note that this won't take any effect until the next Terminal.Display or Terminal.Flush call.

func (*Terminal) DisableMouse

func (t *Terminal) DisableMouse()

DisableMouse disables mouse support on the terminal. This will disable mouse button and button motion events.

Note that on Unix, this won't take any effect until the next Terminal.Display or Terminal.Flush call.

func (*Terminal) Display

func (t *Terminal) Display() error

Display computes the necessary changes to the terminal screen and renders the current buffer to the terminal screen.

Typically, you would call this after modifying the terminal buffer using Terminal.SetCell or Terminal.PrependString.

func (*Terminal) EnableBracketedPaste

func (t *Terminal) EnableBracketedPaste()

EnableBracketedPaste enables bracketed paste mode on the terminal. This is typically used to enable support for pasting text into the terminal without interfering with the terminal's input handling.

func (*Terminal) EnableFocusEvents

func (t *Terminal) EnableFocusEvents()

EnableFocusEvents enables focus/blur receiving notification events on the terminal.

func (*Terminal) EnableMode

func (t *Terminal) EnableMode(modes ...ansi.Mode)

EnableMode enables the given modes on the terminal. This is typically used to enable mouse support, bracketed paste mode, and other terminal features.

Note that this won't take any effect until the next Terminal.Display or Terminal.Flush call.

func (*Terminal) EnableMouse

func (t *Terminal) EnableMouse(modes ...MouseMode)

EnableMouse enables mouse support on the terminal. Calling this without any modes will enable all mouse modes by default. The available modes are:

Note that on Unix, this won't take any effect until the next Terminal.Display or Terminal.Flush call.

func (*Terminal) EnterAltScreen

func (t *Terminal) EnterAltScreen()

EnterAltScreen enters the alternate screen buffer. This is typically used for applications that want to take over the entire terminal screen.

The Terminal manages the alternate screen buffer for you based on the [Viewport] used during Terminal.Display. This means that you don't need to call this unless you know what you're doing.

Note that this won't take any effect until the next Terminal.Display or Terminal.Flush call.

func (*Terminal) Erase

func (t *Terminal) Erase()

Erase fills the screen buffer with empty cells, and wipe the terminal screen. This is different from Terminal.Clear, which only fills the terminal with empty cells.

This won't take any effect until the next Terminal.Display or Terminal.Flush call.

func (*Terminal) Events

func (t *Terminal) Events() chan Event

Events returns the event channel for the terminal. This channel is used to receive and send events from the terminal.

func (*Terminal) ExitAltScreen

func (t *Terminal) ExitAltScreen()

ExitAltScreen exits the alternate screen buffer and returns to the normal screen buffer.

The Terminal manages the alternate screen buffer for you based on the [Viewport] used during Terminal.Display. This means that you don't need to call this unless you know what you're doing.

Note that this won't take any effect until the next Terminal.Display or Terminal.Flush call.

func (*Terminal) Fill

func (t *Terminal) Fill(c *Cell)

Fill fills the terminal screen with the given cell. If the cell is nil, it fills the screen with empty cells.

func (*Terminal) FillArea

func (t *Terminal) FillArea(c *Cell, area Rectangle)

FillArea fills the given area of the terminal screen with the given cell. If the cell is nil, it fills the area with empty cells.

func (*Terminal) Flush

func (t *Terminal) Flush() error

Flush flushes any pending renders to the terminal screen. This is typically used to flush the underlying screen buffer to the terminal.

Use Terminal.Buffered to check how many bytes pending to be flushed.

func (*Terminal) GetMode

func (t *Terminal) GetMode(mode ansi.Mode) ansi.ModeSetting

GetMode returns the current state of the given mode in the terminal. This is typically used to check if a specific mode is enabled or disabled on the terminal.

func (*Terminal) GetSize

func (t *Terminal) GetSize() (width, height int, err error)

GetSize returns the size of the terminal screen. It errors if the size cannot be determined.

func (*Terminal) HideCursor

func (t *Terminal) HideCursor()

HideCursor hides the terminal cursor.

The Terminal manages the visibility of the cursor for you based on the [Viewport] used during Terminal.Display. This means that you don't need to call this unless you know what you're doing.

Note that this won't take any effect until the next Terminal.Display or Terminal.Flush call.

func (*Terminal) MoveTo

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

MoveTo moves the cursor to the given x, y position in the terminal. This won't take any effect until the next Terminal.Display or Terminal.Flush call.

func (*Terminal) Position

func (t *Terminal) Position() (int, int)

Position returns the last known position of the cursor in the terminal.

func (*Terminal) PrependLines

func (t *Terminal) PrependLines(lines ...Line) error

PrependLines adds lines of cells to the top of the terminal screen. The added line is unmanaged and will not be cleared or updated by the Terminal.

This will truncate each line to the terminal width, so if the string is longer than the terminal width, it will be truncated to fit.

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 (*Terminal) PrependString

func (t *Terminal) PrependString(str string) error

PrependString adds the given string to the top of the terminal screen. The string is split into lines and each line is added as a new line at the top of the screen. The added lines are not managed by the terminal and will not be cleared or updated by the Terminal.

This will truncate each line to the terminal width, so if the string is longer than the terminal width, it will be truncated to fit.

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.

Note that this won't take any effect until the next Terminal.Display or Terminal.Flush call.

func (*Terminal) Render

func (t *Terminal) Render()

Render computes the necessary changes to the terminal screen and marks the current buffer pending to be rendered to the terminal screen.

Use Terminal.Display or Terminal.Flush to actually render the buffer to the terminal screen.

func (*Terminal) RequestBackgroundColor

func (t *Terminal) RequestBackgroundColor()

RequestBackgroundColor requests the current background color of the terminal.

Note that this won't take any effect until the next Terminal.Display or Terminal.Flush call.

func (*Terminal) RequestCursorColor

func (t *Terminal) RequestCursorColor()

RequestCursorColor requests the current cursor color of the terminal.

Note that this won't take any effect until the next Terminal.Display or Terminal.Flush call.

func (*Terminal) RequestForegroundColor

func (t *Terminal) RequestForegroundColor()

RequestForegroundColor requests the current foreground color of the terminal.

Note that this won't take any effect until the next Terminal.Display or Terminal.Flush call.

func (*Terminal) RequestMode

func (t *Terminal) RequestMode(mode ansi.Mode)

RequestMode requests the current state of the given modes from the terminal. This is typically used to check if a specific mode is recognized, enabled, or disabled on the terminal.

Note that this won't take any effect until the next Terminal.Display or Terminal.Flush call.

func (*Terminal) ResetBackgroundColor

func (t *Terminal) ResetBackgroundColor()

ResetBackgroundColor resets the terminal background color to the default color.

Note that this won't take any effect until the next Terminal.Display or Terminal.Flush call.

func (*Terminal) ResetCursorColor

func (t *Terminal) ResetCursorColor()

ResetCursorColor resets the terminal cursor color to the default color.

Note that this won't take any effect until the next Terminal.Display or Terminal.Flush call.

func (*Terminal) ResetForegroundColor

func (t *Terminal) ResetForegroundColor()

ResetForegroundColor resets the terminal foreground color to the default color.

Note that this won't take any effect until the next Terminal.Display or Terminal.Flush call.

func (*Terminal) Resize

func (t *Terminal) Resize(width, height int) error

Resize resizes the terminal screen buffer to the given width and height. This won't affect [Terminal.Size] or the terminal size, but it will resize the screen buffer used by the terminal.

func (*Terminal) Restore

func (t *Terminal) Restore() error

Restore restores the terminal to its original state. This can be called after [Terminal.MakeRaw] to restore the terminal to its original state. It will also disable any modes that were enabled by the terminal, such as exiting the alternate screen buffer, showing the cursor, and resetting terminal modes.

Most of the time, you don't need to call this manually, as it is called automatically when the terminal is shutdown or closed using Terminal.Close or Terminal.Shutdown.

func (*Terminal) SendEvent

func (t *Terminal) SendEvent(ctx context.Context, ev Event)

SendEvent is a helper function to send an event to the event channel. It blocks until the event is sent or the context is done. If the context is done, it will not send the event and will return immediately. This is useful to control the terminal from outside the event loop.

func (*Terminal) SetBackgroundColor

func (t *Terminal) SetBackgroundColor(c color.Color)

SetBackgroundColor sets the terminal default background color.

Note that this won't take any effect until the next Terminal.Display or Terminal.Flush call.

func (*Terminal) SetCell

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

SetCell sets the cell at the given x, y position in the terminal buffer.

func (*Terminal) SetColorProfile

func (t *Terminal) SetColorProfile(p colorprofile.Profile)

SetColorProfile sets a custom color profile for the terminal. This is useful for forcing a specific color output. By default, the terminal will use the system's color profile inferred by the environment variables.

func (*Terminal) SetCursorColor

func (t *Terminal) SetCursorColor(c color.Color)

SetCursorColor sets the terminal cursor color.

Note that this won't take any effect until the next Terminal.Display or Terminal.Flush call.

func (*Terminal) SetCursorShape

func (t *Terminal) SetCursorShape(shape CursorShape, blink bool)

SetCursorShape sets the terminal cursor shape and blinking style.

Note that this won't take any effect until the next Terminal.Display or Terminal.Flush call.

func (*Terminal) SetForegroundColor

func (t *Terminal) SetForegroundColor(c color.Color)

SetForegroundColor sets the terminal default foreground color.

Note that this won't take any effect until the next Terminal.Display or Terminal.Flush call.

func (*Terminal) SetLogger

func (t *Terminal) SetLogger(logger Logger)

SetLogger sets the debug logger for the terminal. This is used to log debug information about the terminal I/O. By default, it is set to a no-op logger.

func (*Terminal) SetMode

func (t *Terminal) SetMode(mode ansi.Mode, setting ansi.ModeSetting)

SetMode sets the given mode and its setting in the Terminal. This is usually used when an ansi.Mode was enabled/disabled outside the context of Terminal.

func (*Terminal) SetPosition

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

SetPosition sets the position of the cursor in the terminal. This is typically used when the cursor was moved manually outside of the Terminal context.

func (*Terminal) SetTitle

func (t *Terminal) SetTitle(title string)

SetTitle sets the title of the terminal window. This is typically used to set the title of the terminal window to the name of the application.

Note that this won't take any effect until the next Terminal.Display or Terminal.Flush call.

func (*Terminal) SetWidthMethod

func (t *Terminal) SetWidthMethod(method ansi.Method)

SetWidthMethod sets the width method used by the terminal. This is typically used to determine how the terminal calculates the width of a single grapheme. The default method is ansi.WcWidth.

func (*Terminal) ShowCursor

func (t *Terminal) ShowCursor()

ShowCursor shows the terminal cursor.

The Terminal manages the visibility of the cursor for you based on the [Viewport] used during Terminal.Display. This means that you don't need to call this unless you know what you're doing.

Note that this won't take any effect until the next Terminal.Display or Terminal.Flush call.

func (*Terminal) Shutdown

func (t *Terminal) Shutdown(ctx context.Context) (rErr error)

Shutdown restores the terminal to its original state and stops the event channel in a graceful manner. This waits for any pending events to be processed or the context to be done before closing the event channel.

func (*Terminal) Start

func (t *Terminal) Start() error

Start prepares the terminal for use. It starts the input reader and initializes the terminal state. This should be called before using the terminal.

func (*Terminal) StreamEvents

func (t *Terminal) StreamEvents(ctx context.Context, evch chan<- Event) error

StreamEvents streams input events from the terminal to the event channel.

func (*Terminal) Touched

func (t *Terminal) Touched() int

Touched returns the number of touched lines in the terminal buffer.

func (*Terminal) WidthMethod

func (t *Terminal) WidthMethod() WidthMethod

WidthMethod returns the width method used by the terminal. This is typically used to determine how the terminal calculates the width of a single grapheme.

func (*Terminal) Write

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

Write writes the given bytes to the underlying terminal renderer. This is typically used to write arbitrary data to the terminal, usually escape sequences or control characters.

This can affect the renderer state and the terminal screen, so it should be used with caution.

Note that this won't take any effect until the next Terminal.Display or Terminal.Flush call.

func (*Terminal) WriteString

func (t *Terminal) WriteString(s string) (n int, err error)

WriteString writes the given string to the underlying terminal renderer. This is typically used to write arbitrary data to the terminal, usually escape sequences or control characters.

This can affect the renderer state and the terminal screen, so it should be used with caution.

Note that this won't take any effect until the next Terminal.Display or Terminal.Flush call.

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

func (s *TerminalRenderer) AltScreen() bool

AltScreen returns whether the alternate screen is enabled. This returns the state of the renderer's alternate screen which does not necessarily reflect the actual alternate screen state of the terminal if it was changed outside the renderer.

func (*TerminalRenderer) Buffered

func (s *TerminalRenderer) Buffered() int

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

func (*TerminalRenderer) CursorHidden

func (s *TerminalRenderer) CursorHidden() bool

CursorHidden returns the current cursor visibility state. This returns the state of the renderer's cursor visibility which does not necessarily reflect the actual cursor visibility state of the terminal if it was changed outside the renderer.

func (*TerminalRenderer) EnterAltScreen

func (s *TerminalRenderer) EnterAltScreen()

EnterAltScreen enters the alternate screen. This is used to switch to a different screen buffer. This queues the escape sequence command to enter the alternate screen, the current cursor visibility state, saves the current cursor properties, and queues a screen clear command.

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 exits the alternate screen. This is used to switch back to the main screen buffer. This queues the escape sequence command to exit the alternate screen, , the last cursor visibility state, restores the cursor properties, and queues a screen clear command.

func (*TerminalRenderer) Flush

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

Flush flushes the buffer to the screen.

func (*TerminalRenderer) HideCursor

func (s *TerminalRenderer) HideCursor()

HideCursor queues the escape sequence to hide the cursor. This is used to make the text cursor invisible on the 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) PrependLines

func (s *TerminalRenderer) PrependLines(lines ...Line)

PrependLines adds lines of cells to the top of the terminal screen. The added lines are unmanaged 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) PrependString

func (s *TerminalRenderer) PrependString(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 *Buffer)

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 *Buffer)

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

func (s *TerminalRenderer) SetAltScreen(v bool)

SetAltScreen sets whether the alternate screen is enabled. This is used to control the internal alternate screen state when it was changed outside the renderer.

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

func (s *TerminalRenderer) SetCursorHidden(v bool)

SetCursorHidden sets whether the cursor is hidden. This is used to control the internal cursor visibility state when it was changed outside the renderer.

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

func (s *TerminalRenderer) ShowCursor()

ShowCursor queues the escape sequence to show the cursor. This is used to make the text cursor visible on the screen.

func (*TerminalRenderer) Touched

func (s *TerminalRenderer) Touched(buf *Buffer) (n int)

Touched returns the number of lines that have been touched or changed.

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 TerminalVersionEvent

type TerminalVersionEvent string

TerminalVersionEvent is a message that represents the terminal version.

type UnderlineStyle

type UnderlineStyle = ansi.UnderlineStyle

UnderlineStyle is the style of underline to use for text.

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

type WindowPixelSizeEvent Size

WindowPixelSizeEvent represents the window size in pixels.

func (WindowPixelSizeEvent) Bounds

func (s WindowPixelSizeEvent) Bounds() Rectangle

Bounds returns the bounds corresponding to the 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 WindowSizeNotifier

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

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

func NewWindowSizeNotifier

func NewWindowSizeNotifier(f term.File) *WindowSizeNotifier

NewWindowSizeNotifier creates a new WindowSizeNotifier with the given file.

func (*WindowSizeNotifier) GetSize

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

GetSize returns the current cell size of the terminal window.

func (*WindowSizeNotifier) GetWindowSize

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

GetWindowSize returns the current size of the terminal window.

func (*WindowSizeNotifier) Start

func (n *WindowSizeNotifier) Start() error

Start starts the notifier by registering for the SIGWINCH signal. It must be called before using [WindowSizeNotifier.Notify] or WindowSizeNotifier.StreamEvents.

func (*WindowSizeNotifier) Stop

func (n *WindowSizeNotifier) Stop() error

Stop stops the notifier and cleans up resources.

func (*WindowSizeNotifier) StreamEvents

func (n *WindowSizeNotifier) StreamEvents(ctx context.Context, ch chan<- Event) error

StreamEvents reads the terminal size change events and sends them to the given channel. It stops when the context is done.

Source Files

  • border.go
  • buffer.go
  • cancelreader_other.go
  • cell.go
  • decoder.go
  • doc.go
  • environ.go
  • event.go
  • key.go
  • key_table.go
  • logger.go
  • mouse.go
  • styled.go
  • tabstop.go
  • terminal.go
  • terminal_bsdly.go
  • terminal_reader.go
  • terminal_reader_other.go
  • terminal_renderer.go
  • terminal_renderer_hardscroll.go
  • terminal_renderer_hashmap.go
  • terminal_tabdly.go
  • terminal_unix.go
  • tty.go
  • tty_unix.go
  • utils.go
  • uv.go
  • winch.go
  • winch_unix.go

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