Package-Level Type Names (total 105, in which 94 are exported)
/* sort exporteds by: | */
BackgroundColorEvent represents a background color event. This event is
emitted when the terminal requests the terminal background color using
[ansi.RequestBackgroundColor].Colorcolor.Color IsDark returns whether the color is dark. RGBA returns the alpha-premultiplied red, green, blue and alpha values
for the color. Each value ranges within [0, 0xffff], but is represented
by a uint32 so that multiplying by a blend factor up to 0xffff will not
overflow.
An alpha-premultiplied color component c has been scaled by alpha (a),
so has valid values 0 <= c <= a. String returns the hex representation of the color.
BackgroundColorEvent : github.com/charmbracelet/x/ansi.Color
BackgroundColorEvent : expvar.Var
BackgroundColorEvent : fmt.Stringer
BackgroundColorEvent : image/color.Color
BackgroundColorEvent : context.stringer
BackgroundColorEvent : os/signal.stringer
BackgroundColorEvent : runtime.stringer
BlurEvent represents a terminal blur event.
This occurs when the terminal loses focus.
Buffer represents a cell buffer that contains the contents of a screen. Lines is a slice of lines that make up the cells of the buffer. Bounds returns the bounds of the buffer.
The origin is always at (0, 0) and the maximum coordinates are determined by
the width and height of the buffer. CellAt returns the cell at the given position. It returns nil if the
position is out of bounds. Clear clears the buffer with space cells and rectangle. ClearArea clears the buffer with space cells within the specified
rectangles. Only cells within the rectangle's bounds are affected. Clone clones the entire buffer into a new buffer. CloneArea clones the area of the buffer within the specified rectangle. If
the area is out of bounds, it returns nil. DeleteCell deletes cells at the given position, with the given optional
cell, within the specified rectangles. If no rectangles are specified, it
deletes cells in the entire buffer. This follows terminal [ansi.DCH]
behavior. DeleteCellArea deletes cells at the given position, with the given
optional cell, within the rectangle bounds. Only cells within the
rectangle's bounds are affected, following terminal [ansi.DCH] behavior. DeleteLine deletes n lines at the given line position, with the given
optional cell, within the specified rectangles. If no rectangles are
specified, it deletes lines in the entire buffer. DeleteLineArea deletes lines at the given line position, with the given
optional cell, within the rectangle bounds. Only cells within the
rectangle's bounds are affected. Lines are shifted up within the bounds and
new blank lines are created at the bottom. This follows terminal [ansi.DL]
behavior. Draw draws the buffer to the given screen at the specified area.
It implements the [Drawable] interface. Fill fills the buffer with the given cell and rectangle. FillArea fills the buffer with the given cell and rectangle. Height implements Screen. InsertCell inserts new cells at the given position, with the given optional
cell, within the specified rectangles. If no rectangles are specified, it
inserts cells in the entire buffer. This follows terminal [ansi.ICH]
behavior. InsertCellArea inserts new cells at the given position, with the given
optional cell, within the rectangle bounds. Only cells within the
rectangle's bounds are affected, following terminal [ansi.ICH] behavior. InsertLine inserts n lines at the given line position, with the given
optional cell, within the specified rectangles. If no rectangles are
specified, it inserts lines in the entire buffer. Only cells within the
rectangle's horizontal bounds are affected. Lines are pushed out of the
rectangle bounds and lost. This follows terminal [ansi.IL] behavior.
It returns the pushed out lines. InsertLineArea inserts new lines at the given line position, with the
given optional cell, within the rectangle bounds. Only cells within the
rectangle's horizontal bounds are affected. Lines are pushed out of the
rectangle bounds and lost. This follows terminal [ansi.IL] behavior. Line returns a pointer to the line at the given y position.
If the line does not exist, it returns nil. Render renders the buffer to a styled string with all the required
attributes and styles. Resize resizes the buffer to the given width and height. SetCell sets the cell at the given x, y position. String returns the string representation of the buffer. Width implements Screen.
*Buffer : Drawable
*Buffer : expvar.Var
*Buffer : fmt.Stringer
*Buffer : context.stringer
*Buffer : os/signal.stringer
*Buffer : runtime.stringer
func NewBuffer(width int, height int) *Buffer
func (*Buffer).Clone() *Buffer
func (*Buffer).CloneArea(area Rectangle) *Buffer
CapabilityEvent represents a Termcap/Terminfo response event. Termcap
responses are generated by the terminal in response to RequestTermcap
(XTGETTCAP) requests.
See: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Operating-System-Commands Content is the pasted text content. String returns the capability content.
CapabilityEvent : expvar.Var
CapabilityEvent : fmt.Stringer
CapabilityEvent : context.stringer
CapabilityEvent : os/signal.stringer
CapabilityEvent : runtime.stringer
func parseTermcap(data []byte) CapabilityEvent
CellSizeEvent represents the cell size in pixels.HeightintWidthint Bounds returns the bounds corresponding to the size.
ClipboardEvent is a clipboard read message event. This message is emitted when
a terminal receives an OSC52 clipboard read message event.ContentstringSelectionClipboardSelection Clipboard returns the clipboard selection. This can be either
[SystemClipboard] 'c' or [PrimaryClipboard] 'p'. String returns the string representation of the clipboard message.
ClipboardEvent : expvar.Var
ClipboardEvent : fmt.Stringer
ClipboardEvent : context.stringer
ClipboardEvent : os/signal.stringer
ClipboardEvent : runtime.stringer
ClipboardSelection represents a clipboard selection. The most common
clipboard selections are "system" and "primary" and selections.
Console represents a cross-platform console I/O interface.( Console) Close() error Environ returns the console's environment variables. GetSize returns the current size of the console. GetWinsize returns the current size of the console in cells and pixels. Getenv retrieves the value of the environment variable named by the key. LookupEnv retrieves the value of the environment variable named by the key
and a boolean indicating whether the variable is present. MakeRaw puts the console input side into raw mode.( Console) Read(p []byte) (n int, err error) Reader returns the input reader of the console. Restore restores the console to its previous state.( Console) Write([]byte) (int, error) Writer returns the output writer of the console.TTYWinCon
*console
Console : internal/bisect.Writer
Console : io.Closer
Console : io.ReadCloser
Console : io.Reader
Console : io.ReadWriteCloser
Console : io.ReadWriter
Console : io.WriteCloser
Console : io.Writer
Console : crypto/tls.transcriptHash
func ControllingConsole() (Console, error)
func DefaultConsole() Console
func NewConsole(input, output File, environ []string) Console
func NewTerminal(con Console, opts *Options) *Terminal
Cursor represents a cursor on the terminal screen. Blink is a boolean that determines whether the cursor should blink. Color is a [color.Color] that determines the cursor's color. Hidden is a boolean that determines whether the cursor is hidden. You
can use this if you want to hide the cursor but still want to change its
position. Position is a [Position] that determines the cursor's position on the
screen relative to the top left corner of the frame.Position.XintPosition.Yint Shape is a [CursorShape] that determines the cursor's shape. Add returns the vector p+q. Div returns the vector p/k. Eq reports whether p and q are equal. In reports whether p is in r. Mod returns the point q in r such that p.X-q.X is a multiple of r's width
and p.Y-q.Y is a multiple of r's height. Mul returns the vector p*k. String returns a string representation of p like "(3,4)". Sub returns the vector p-q.
Cursor : expvar.Var
Cursor : fmt.Stringer
Cursor : context.stringer
Cursor : os/signal.stringer
Cursor : runtime.stringer
func NewCursor(x, y int) *Cursor
CursorColorEvent represents a cursor color change event. This event is
emitted when the program requests the terminal cursor color using
[ansi.RequestCursorColor].Colorcolor.Color IsDark returns whether the color is dark. RGBA returns the alpha-premultiplied red, green, blue and alpha values
for the color. Each value ranges within [0, 0xffff], but is represented
by a uint32 so that multiplying by a blend factor up to 0xffff will not
overflow.
An alpha-premultiplied color component c has been scaled by alpha (a),
so has valid values 0 <= c <= a. String returns the hex representation of the color.
CursorColorEvent : github.com/charmbracelet/x/ansi.Color
CursorColorEvent : expvar.Var
CursorColorEvent : fmt.Stringer
CursorColorEvent : image/color.Color
CursorColorEvent : context.stringer
CursorColorEvent : os/signal.stringer
CursorColorEvent : runtime.stringer
CursorPositionEvent represents a cursor position event. Where X is the
zero-based column and Y is the zero-based row.XintYint
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.
DrawableFunc is a function that implements the [Drawable] interface. Draw implements the [Drawable] interface.
DrawableFunc : Drawable
Environ is a slice of strings that represents the environment variables of
the program. Getenv returns the value of the environment variable named by the key. If
the variable is not present in the environment, the value returned will be
the empty string. LookupEnv retrieves the value of the environment variable named by the key.
If the variable is present in the environment the value (which may be empty)
is returned and the boolean is true. Otherwise the returned value will be
empty and the boolean will be false.
func NewTerminalScreen(w io.Writer, env Environ) *TerminalScreen
func newConsole(in File, out File, env Environ) *TTY
EventDecoder decodes terminal input events from a byte buffer. Terminal
input events are typically encoded as Unicode or ASCII characters, control
codes, or ANSI escape sequences. Legacy is the legacy key encoding flags. These flags control the
behavior of legacy terminal key encodings. See [LegacyKeyEncoding] for
more details. UseTerminfo is a flag that controls whether to use the terminal type
Terminfo database to map escape sequences to key events. This will
override the default key sequences handled by the parser. // the last control key state for the previous key event record. 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:]
}
```(*EventDecoder) parseApc(b []byte) (int, Event)(*EventDecoder) parseControl(b byte) Event(*EventDecoder) parseCsi(b []byte) (int, Event)(*EventDecoder) parseDcs(b []byte) (int, Event)(*EventDecoder) parseOsc(b []byte) (int, Event) parseSs3 parses a SS3 sequence.
See https://vt100.net/docs/vt220-rm/chapter4.html#S4.4.4.2 parseStTerminated parses a control sequence that gets terminated by a ST character.(*EventDecoder) parseUtf8(b []byte) (int, Event) parseWin32InputKeyEvent converts a Windows Input Record Key Event into a
KeyPressEvent, KeyReleaseEvent, or MultiEvent including multiple of the
former type.
A special case is when the key is either part of VtInputMode which produces
vkc == 0, or when a key is a UTF-16 surrogate pair. In both of these cases,
we need to handle key encoding and properly parse the key event.
EventStreamer is an interface that defines a method to stream events from an
input source. It takes a context and a channel to send events to. The
streamer should block until the context is done or an error occurs. The
channel should never be closed by the streamer, as it is the responsibility
of the consumer to close it when done.( EventStreamer) StreamEvents(ctx context.Context, ch chan<- Event) error
*TerminalReader
FocusEvent represents a terminal focus event.
This occurs when the terminal gains focus.
ForegroundColorEvent represents a foreground color event. This event is
emitted when the terminal requests the terminal foreground color using
[ansi.RequestForegroundColor].Colorcolor.Color IsDark returns whether the color is dark. RGBA returns the alpha-premultiplied red, green, blue and alpha values
for the color. Each value ranges within [0, 0xffff], but is represented
by a uint32 so that multiplying by a blend factor up to 0xffff will not
overflow.
An alpha-premultiplied color component c has been scaled by alpha (a),
so has valid values 0 <= c <= a. String returns the hex representation of the color.
ForegroundColorEvent : github.com/charmbracelet/x/ansi.Color
ForegroundColorEvent : expvar.Var
ForegroundColorEvent : fmt.Stringer
ForegroundColorEvent : image/color.Color
ForegroundColorEvent : context.stringer
ForegroundColorEvent : os/signal.stringer
ForegroundColorEvent : runtime.stringer
Key represents a Key press or release event. It contains information about
the Key pressed, like the runes, the type of Key, and the modifiers pressed.
There are a couple general patterns you could use to check for key presses
or releases:
// Switch on the string representation of the key (shorter)
switch ev := ev.(type) {
case KeyPressEvent:
switch ev.String() {
case "enter":
fmt.Println("you pressed enter!")
case "a":
fmt.Println("you pressed a!")
}
}
// Switch on the key type (more foolproof)
switch ev := ev.(type) {
case KeyEvent:
// catch both KeyPressEvent and KeyReleaseEvent
switch key := ev.Key(); key.Code {
case KeyEnter:
fmt.Println("you pressed enter!")
default:
switch key.Text {
case "a":
fmt.Println("you pressed a!")
}
}
}
Note that [Key.Text] will be empty for special keys like [KeyEnter],
[KeyTab], and for keys that don't represent printable characters like key
combos with modifier keys. In other words, [Key.Text] is populated only for
keys that represent printable characters shifted or unshifted (like 'a',
'A', '1', '!', etc.). BaseCode is the key pressed according to the standard PC-101 key layout.
On international keyboards, this is the key that would be pressed if the
keyboard was set to US PC-101 layout.
For example, if the user presses 'q' on a French AZERTY keyboard,
[Key.BaseCode] will be 'q'.
This is only available with the Kitty Keyboard Protocol or the Windows
Console API. Code represents the key pressed. This is usually a special key like
[KeyTab], [KeyEnter], [KeyF1], or a printable character like 'a'. IsRepeat indicates whether the key is being held down and sending events
repeatedly.
This is only available with the Kitty Keyboard Protocol or the Windows
Console API. Mod represents modifier keys, like [ModCtrl], [ModAlt], and so on. ShiftedCode is the actual, shifted key pressed by the user. For example,
if the user presses shift+a, or caps lock is on, [Key.ShiftedCode] will
be 'A' and [Key.Code] will be 'a'.
In the case of non-latin keyboards, like Arabic, [Key.ShiftedCode] is the
unshifted key on the keyboard.
This is only available with the Kitty Keyboard Protocol or the Windows
Console API. Text contains the actual characters received. This usually the same as
[Key.Code]. When [Key.Text] is non-empty, it indicates that the key
pressed represents printable character(s). Keystroke returns the keystroke representation of the [Key]. While less type
safe than looking at the individual fields, it will usually be more
convenient and readable to use this method when matching against keys.
Note that modifier keys are always printed in the following order:
- ctrl
- alt
- shift
- meta
- hyper
- super
For example, you'll always see "ctrl+shift+alt+a" and never
"shift+ctrl+alt+a". MatchString returns true if the [Key] matches one of the given strings.
A string can be a key name like "enter", "tab", "a", or a printable
character like "1" or " ". It can also have combinations of modifiers like
"ctrl+a", "shift+enter", "alt+tab", "ctrl+shift+enter", etc. String implements [fmt.Stringer] and is quite useful for matching key
events. It will return the textual representation of the [Key] if there is
one, otherwise, it will fallback to [Key.Keystroke].
For example, you'll always get "?" and instead of "shift+/" on a US ANSI
keyboard.
Key : expvar.Var
Key : fmt.Stringer
Key : context.stringer
Key : os/signal.stringer
Key : runtime.stringer
func KeyEvent.Key() Key
func KeyPressEvent.Key() Key
func KeyReleaseEvent.Key() Key
func buildKeysTable(flags LegacyKeyEncoding, term string, useTerminfo bool) map[string]Key
func buildTerminfoKeys(flags LegacyKeyEncoding, term string) map[string]Key
func defaultTerminfoKeys(flags LegacyKeyEncoding) map[string]Key
func ensureKeyCase(key Key, cks uint32) Key
func ensureKeyCase(key Key, cks uint32) Key
func keyMatchString(k Key, s string) bool
KeyboardEnhancements defines different keyboard enhancement features that
can be requested from the terminal. DisambiguateEscapeCodes requests the terminal to report ambiguous keys
such as Ctrl+i and Tab, and Ctrl+m and Enter, and others as distinct key
code sequences.
If supported, your program will receive distinct [KeyPressEvent]s for
these keys. ReportAllKeysAsEscapeCodes requests the terminal to report all key
events, including plain text keys, as escape codes.
When this is enabled, text won't be sent as plain text but instead as
escape codes that encode the key value and modifiers. ReportAlternateKeys requests the terminal to report alternate key values
in addition to the main ones.
Note that only key events represented as escape codes will affected by
this enhancement. ReportAssociatedText requests the terminal to report the text associated
with key events.
Note that this is an enhancement to
[KeyboardEnhancements.ReportAllKeysAsEscapeCodes] and only has an effect
if that is enabled. ReportEventTypes requests the terminal to report key repeat and release
events.
If supported, your program will receive [KeyReleaseEvent]s and
[KeyPressEvent] with the [Key.IsRepeat] field set indicating that this
is a it's part of a key repeat sequence. Flags returns the keyboard enhancements as bits that can be used to set the
appropriate terminal modes.
func NewKeyboardEnhancements(flags int) *KeyboardEnhancements
func (*TerminalScreen).KeyboardEnhancements() *KeyboardEnhancements
func EncodeKeyboardEnhancements(w io.Writer, ke *KeyboardEnhancements) error
func (*TerminalScreen).SetKeyboardEnhancements(enh *KeyboardEnhancements)
KeyboardEnhancementsEvent represents a keyboard enhancements report event. Flags are the Kitty Keyboard Enhancement flags.
Bit values:
00000001: Disambiguate escape codes
00000010: Report event types
00000100: Report alternate keys
00001000: Report all keys as escape codes
00010000: Report associated text
See: https://sw.kovidgoyal.net/kitty/keyboard-protocol/#keyboard-enhancements Contains reports whether m contains the given enhancements. SupportsKeyDisambiguation returns whether the terminal supports reporting
disambiguous keys as escape codes. SupportsKeyReleases returns whether the terminal supports key release
events. SupportsUniformKeyLayout returns whether the terminal supports reporting key
events as though they were on a PC-101 layout.
KeyEvent represents a key event. This can be either a key press or a key
release event. Key returns the underlying key event.( KeyEvent) String() stringKeyPressEventKeyReleaseEvent
KeyEvent : expvar.Var
KeyEvent : fmt.Stringer
KeyEvent : context.stringer
KeyEvent : os/signal.stringer
KeyEvent : runtime.stringer
KeyPressEvent represents a key press event. BaseCode is the key pressed according to the standard PC-101 key layout.
On international keyboards, this is the key that would be pressed if the
keyboard was set to US PC-101 layout.
For example, if the user presses 'q' on a French AZERTY keyboard,
[Key.BaseCode] will be 'q'.
This is only available with the Kitty Keyboard Protocol or the Windows
Console API. Code represents the key pressed. This is usually a special key like
[KeyTab], [KeyEnter], [KeyF1], or a printable character like 'a'. IsRepeat indicates whether the key is being held down and sending events
repeatedly.
This is only available with the Kitty Keyboard Protocol or the Windows
Console API. Mod represents modifier keys, like [ModCtrl], [ModAlt], and so on. ShiftedCode is the actual, shifted key pressed by the user. For example,
if the user presses shift+a, or caps lock is on, [Key.ShiftedCode] will
be 'A' and [Key.Code] will be 'a'.
In the case of non-latin keyboards, like Arabic, [Key.ShiftedCode] is the
unshifted key on the keyboard.
This is only available with the Kitty Keyboard Protocol or the Windows
Console API. Text contains the actual characters received. This usually the same as
[Key.Code]. When [Key.Text] is non-empty, it indicates that the key
pressed represents printable character(s). Key returns the underlying key event. This is a syntactic sugar for casting
the key event to a [Key]. Keystroke returns the keystroke representation of the [Key]. While less type
safe than looking at the individual fields, it will usually be more
convenient and readable to use this method when matching against keys.
Note that modifier keys are always printed in the following order:
- ctrl
- alt
- shift
- meta
- hyper
- super
For example, you'll always see "ctrl+shift+alt+a" and never
"shift+ctrl+alt+a". MatchString returns true if the [Key] matches one of the given strings.
A string can be a key name like "enter", "tab", "a", or a printable
character like "1" or " ". It can also have combinations of modifiers like
"ctrl+a", "shift+enter", "alt+tab", "ctrl+shift+enter", etc. String implements [fmt.Stringer] and is quite useful for matching key
events. For details, on what this returns see [Key.String].
KeyPressEvent : KeyEvent
KeyPressEvent : expvar.Var
KeyPressEvent : fmt.Stringer
KeyPressEvent : context.stringer
KeyPressEvent : os/signal.stringer
KeyPressEvent : runtime.stringer
func parseKittyKeyboardExt(params ansi.Params, k KeyPressEvent) Event
KeyReleaseEvent represents a key release event. BaseCode is the key pressed according to the standard PC-101 key layout.
On international keyboards, this is the key that would be pressed if the
keyboard was set to US PC-101 layout.
For example, if the user presses 'q' on a French AZERTY keyboard,
[Key.BaseCode] will be 'q'.
This is only available with the Kitty Keyboard Protocol or the Windows
Console API. Code represents the key pressed. This is usually a special key like
[KeyTab], [KeyEnter], [KeyF1], or a printable character like 'a'. IsRepeat indicates whether the key is being held down and sending events
repeatedly.
This is only available with the Kitty Keyboard Protocol or the Windows
Console API. Mod represents modifier keys, like [ModCtrl], [ModAlt], and so on. ShiftedCode is the actual, shifted key pressed by the user. For example,
if the user presses shift+a, or caps lock is on, [Key.ShiftedCode] will
be 'A' and [Key.Code] will be 'a'.
In the case of non-latin keyboards, like Arabic, [Key.ShiftedCode] is the
unshifted key on the keyboard.
This is only available with the Kitty Keyboard Protocol or the Windows
Console API. Text contains the actual characters received. This usually the same as
[Key.Code]. When [Key.Text] is non-empty, it indicates that the key
pressed represents printable character(s). Key returns the underlying key event. This is a convenience method and
syntactic sugar to satisfy the [KeyEvent] interface, and cast the key event to
[Key]. Keystroke returns the keystroke representation of the [Key]. While less type
safe than looking at the individual fields, it will usually be more
convenient and readable to use this method when matching against keys.
Note that modifier keys are always printed in the following order:
- ctrl
- alt
- shift
- meta
- hyper
- super
For example, you'll always see "ctrl+shift+alt+a" and never
"shift+ctrl+alt+a". MatchString returns true if the [Key] matches one of the given strings.
A string can be a key name like "enter", "tab", "a", or a printable
character like "1" or " ". It can also have combinations of modifiers like
"ctrl+a", "shift+enter", "alt+tab", "ctrl+shift+enter", etc. String implements [fmt.Stringer] and is quite useful for matching key
events. For details, on what this returns see [Key.String].
KeyReleaseEvent : KeyEvent
KeyReleaseEvent : expvar.Var
KeyReleaseEvent : fmt.Stringer
KeyReleaseEvent : context.stringer
KeyReleaseEvent : os/signal.stringer
KeyReleaseEvent : runtime.stringer
KittyGraphicsEvent represents a Kitty Graphics response event.
See https://sw.kovidgoyal.net/kitty/graphics-protocol/Optionskitty.OptionsPayload[]byte
LegacyKeyEncoding is a set of flags that control the behavior of legacy
terminal key encodings. Historically, ctrl+<key> input events produce
control characters (0x00-0x1F) that collide with some special keys like Tab,
Enter, and Escape. This controls the expected behavior of encoding these
keys.
This type has the following default values:
- CtrlAt maps 0x00 [ansi.NUL] to ctrl+space instead of ctrl+@.
- CtrlI maps 0x09 [ansi.HT] to the tab key instead of ctrl+i.
- CtrlM maps 0x0D [ansi.CR] to the enter key instead of ctrl+m.
- CtrlOpenBracket maps 0x1B [ansi.ESC] to the escape key instead of ctrl+[.
- Backspace maps the backspace key to 0x08 [ansi.BS] instead of 0x7F [ansi.DEL].
- Find maps the legacy find key to the home key.
- Select maps the legacy select key to the end key.
- FKeys maps high function keys instead of treating them as Function+<modifiers>. Backspace returns a [LegacyKeyEncoding] with whether the backspace key is
mapped to [ansi.BS] (0x08) instead of [ansi.DEL] (0x7F). CtrlAt returns a [LegacyKeyEncoding] with whether [ansi.NUL] (0x00)
is mapped to ctrl+at instead of ctrl+space. CtrlI returns a [LegacyKeyEncoding] with whether [ansi.HT] (0x09)
is mapped to ctrl+i instead of the tab key. CtrlM returns a [LegacyKeyEncoding] with whether [ansi.CR] (0x0D)
is mapped to ctrl+m instead of the enter key. CtrlOpenBracket returns a [LegacyKeyEncoding] with whether [ansi.ESC] (0x1B)
is mapped to ctrl+[ instead of the escape key. FKeys returns a [LegacyKeyEncoding] with whether high function keys are
mapped to high function keys (beyond F20) instead of treating them as
Function+<modifiers> keys. Find returns a [LegacyKeyEncoding] with whether the legacy find key
is mapped to the home key. Select returns a [LegacyKeyEncoding] with whether the legacy select key
is mapped to the end key.
func LegacyKeyEncoding.Backspace(v bool) LegacyKeyEncoding
func LegacyKeyEncoding.CtrlAt(v bool) LegacyKeyEncoding
func LegacyKeyEncoding.CtrlI(v bool) LegacyKeyEncoding
func LegacyKeyEncoding.CtrlM(v bool) LegacyKeyEncoding
func LegacyKeyEncoding.CtrlOpenBracket(v bool) LegacyKeyEncoding
func LegacyKeyEncoding.Find(v bool) LegacyKeyEncoding
func LegacyKeyEncoding.FKeys(v bool) LegacyKeyEncoding
func LegacyKeyEncoding.Select(v bool) LegacyKeyEncoding
func buildKeysTable(flags LegacyKeyEncoding, term string, useTerminfo bool) map[string]Key
func buildTerminfoKeys(flags LegacyKeyEncoding, term string) map[string]Key
func defaultTerminfoKeys(flags LegacyKeyEncoding) map[string]Key
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.
LineData represents the metadata for a line. First and last changed cell indices. First and last changed cell indices. Old index used for scrolling
Lines represents a slice of lines. Height returns the height of the lines. Render renders the lines to a styled string with all the required attributes
and styles. String returns the string representation of the lines. Width returns the width of the widest line.
Lines : expvar.Var
Lines : fmt.Stringer
Lines : context.stringer
Lines : os/signal.stringer
Lines : runtime.stringer
Logger is a simple logger interface.( Logger) Printf(format string, v ...interface{})
golang.org/x/net/trace.EventLog(interface)
google.golang.org/grpc/grpclog.Logger(interface)
google.golang.org/grpc/grpclog/internal.Logger(interface)
google.golang.org/grpc/grpclog/internal.LoggerWrapper
*log.Logger
*golang.org/x/net/trace.eventLog
google.golang.org/grpc.traceEventLog(interface)
func (*TerminalReader).SetLogger(logger Logger)
func (*TerminalRenderer).SetLogger(logger Logger)
func logf(logger Logger, format string, v ...interface{})
ModeReportEvent is a message that represents a mode report event (DECRPM).
See: https://vt100.net/docs/vt510-rm/DECRPM.html Mode is the mode number. Value is the mode value.
Mouse represents a Mouse message. Use [MouseEvent] to represent all mouse
messages.
The X and Y coordinates are zero-based, with (0,0) being the upper left
corner of the terminal. When using [MouseEncodingSGRPixel] (DEC mode 1016),
X and Y are in pixel coordinates; otherwise they are in cell coordinates.
// Catch all mouse events
switch Event := Event.(type) {
case MouseEvent:
m := Event.Mouse()
fmt.Println("Mouse event:", m.X, m.Y, m)
}
// Only catch mouse click events
switch Event := Event.(type) {
case MouseClickEvent:
fmt.Println("Mouse click event:", Event.X, Event.Y, Event)
}ButtonMouseButtonModKeyModXintYint String returns a string representation of the mouse message.
Mouse : expvar.Var
Mouse : fmt.Stringer
Mouse : context.stringer
Mouse : os/signal.stringer
Mouse : runtime.stringer
func MousePixelToCell(m Mouse, ws *Winsize) Mouse
func MouseClickEvent.Mouse() Mouse
func MouseEvent.Mouse() Mouse
func MouseMotionEvent.Mouse() Mouse
func MouseReleaseEvent.Mouse() Mouse
func MouseWheelEvent.Mouse() Mouse
func MousePixelToCell(m Mouse, ws *Winsize) Mouse
MouseButton represents the button that was pressed during a mouse message.
MouseClickEvent represents a mouse button click event.ButtonMouseButtonModKeyModXintYint Mouse returns the underlying mouse event. This is a convenience method and
syntactic sugar to satisfy the [MouseEvent] interface, and cast the mouse
event to [Mouse]. String returns a string representation of the mouse click event.
MouseClickEvent : MouseEvent
MouseClickEvent : expvar.Var
MouseClickEvent : fmt.Stringer
MouseClickEvent : context.stringer
MouseClickEvent : os/signal.stringer
MouseClickEvent : runtime.stringer
MouseMotionEvent represents a mouse motion event.ButtonMouseButtonModKeyModXintYint Mouse returns the underlying mouse event. This is a convenience method and
syntactic sugar to satisfy the [MouseEvent] interface, and cast the mouse
event to [Mouse]. String returns a string representation of the mouse motion event.
MouseMotionEvent : MouseEvent
MouseMotionEvent : expvar.Var
MouseMotionEvent : fmt.Stringer
MouseMotionEvent : context.stringer
MouseMotionEvent : os/signal.stringer
MouseMotionEvent : runtime.stringer
MouseReleaseEvent represents a mouse button release event.ButtonMouseButtonModKeyModXintYint Mouse returns the underlying mouse event. This is a convenience method and
syntactic sugar to satisfy the [MouseEvent] interface, and cast the mouse
event to [Mouse]. String returns a string representation of the mouse release event.
MouseReleaseEvent : MouseEvent
MouseReleaseEvent : expvar.Var
MouseReleaseEvent : fmt.Stringer
MouseReleaseEvent : context.stringer
MouseReleaseEvent : os/signal.stringer
MouseReleaseEvent : runtime.stringer
MouseWheelEvent represents a mouse wheel message event.ButtonMouseButtonModKeyModXintYint Mouse returns the underlying mouse event. This is a convenience method and
syntactic sugar to satisfy the [MouseEvent] interface, and cast the mouse
event to [Mouse]. String returns a string representation of the mouse wheel event.
MouseWheelEvent : MouseEvent
MouseWheelEvent : expvar.Var
MouseWheelEvent : fmt.Stringer
MouseWheelEvent : context.stringer
MouseWheelEvent : os/signal.stringer
MouseWheelEvent : runtime.stringer
MultiEvent represents multiple messages event. String returns a string representation of the multiple messages event.
MultiEvent : expvar.Var
MultiEvent : fmt.Stringer
MultiEvent : context.stringer
MultiEvent : os/signal.stringer
MultiEvent : runtime.stringer
Options represents options for creating a new [Terminal]. BufferSize is the size of the input buffer used for reading terminal
events. If zero, [DefaultBufferSize] is used. EventTimeout is the duration to wait for input events before timing out.
If zero, a default of 100 milliseconds is used. LegacyKeyEncoding represents any legacy key encoding ambiguities. By
default, the terminal will use its preferred key encoding settings. Logger is an optional logger for tracing terminal I/O operations.
If nil, no logging is performed. LookupKeys whether to use a lookup table for common key sequences. If
true, the terminal will use a lookup table to quickly identify common
key sequences, reducing the need for more complex decoding logic. This
can improve performance for common key sequences at the cost of
increased memory usage.
This is enabled by default. UseTerminfoKeys whether to use terminfo databases key definitions to
build up the keys lookup table. If true, the terminal will use terminfo
databases key definitions to build up the keys lookup table, which can
provide more accurate key mappings for legacy non-xterm like terminals.
This won't take effect if [TerminalOptions.LookupKeys] is false, since
the lookup table won't be used.
This is disabled by default.
func DefaultOptions() *Options
func NewTerminal(con Console, opts *Options) *Terminal
PasteEndEvent is an message that is emitted when the terminal ends the
bracketed-paste text.
PasteEvent is an message that is emitted when a terminal receives pasted text
using bracketed-paste. Content is the pasted text content. String returns the pasted content as a string.
PasteEvent : expvar.Var
PasteEvent : fmt.Stringer
PasteEvent : context.stringer
PasteEvent : os/signal.stringer
PasteEvent : runtime.stringer
PasteStartEvent is an message that is emitted when the terminal starts the
bracketed-paste text.
PixelSizeEvent represents the window size in pixels.HeightintWidthint Bounds returns the bounds corresponding to the size.
Position represents a position in a coordinate system.
PrimaryDeviceAttributesEvent is an event that represents the terminal
primary device attributes.
Common attributes include:
- 1 132 columns
- 2 Printer port
- 4 Sixel
- 6 Selective erase
- 7 Soft character set (DRCS)
- 8 User-defined keys (UDKs)
- 9 National replacement character sets (NRCS) (International terminal only)
- 12 Yugoslavian (SCS)
- 15 Technical character set
- 18 Windowing capability
- 21 Horizontal scrolling
- 23 Greek
- 24 Turkish
- 42 ISO Latin-2 character set
- 44 PCTerm
- 45 Soft key map
- 46 ASCII emulation
See [ansi.PrimaryDeviceAttributes] for more details.
ProgressBar represents the terminal progress bar.
Support depends on the terminal.
See https://learn.microsoft.com/en-us/windows/terminal/tutorials/progress-bar-sequences State is the current state of the progress bar. It can be one of
[ProgressBarNone], [ProgressBarDefault], [ProgressBarError],
[ProgressBarIndeterminate], and [ProgressBarWarning]. Value is the current value of the progress bar. It should be between
0 and 100.
func NewProgressBar(state ProgressBarState, value int) *ProgressBar
func (*TerminalScreen).ProgressBar() *ProgressBar
func EncodeProgressBar(w io.Writer, pb *ProgressBar) error
func (*TerminalScreen).SetProgressBar(pb *ProgressBar)
RenderBuffer represents a buffer that keeps track of the current and new
state of the screen, allowing for efficient rendering by only updating the
parts of the screen that have changed.Buffer*Buffer Lines is a slice of lines that make up the cells of the buffer.Touched[]*LineData Bounds returns the bounds of the buffer.
The origin is always at (0, 0) and the maximum coordinates are determined by
the width and height of the buffer. CellAt returns the cell at the given position. It returns nil if the
position is out of bounds. Clear clears the buffer with space cells and marks all lines as touched. ClearArea clears the buffer with space cells within the specified rectangle
and marks the affected lines as touched. Clone clones the entire buffer into a new buffer. CloneArea clones the area of the buffer within the specified rectangle. If
the area is out of bounds, it returns nil. DeleteCell deletes cells at the given position, with the given optional
cell, within the specified rectangles. If no rectangles are specified, it
deletes cells in the entire buffer. This follows terminal [ansi.DCH]
behavior. DeleteCellArea deletes cells at the given position, with the given
optional cell, within the rectangle bounds. Only cells within the
rectangle's bounds are affected, following terminal [ansi.DCH] behavior. DeleteLine deletes n lines at the given line position, with the given
optional cell, within the specified rectangles. If no rectangles are
specified, it deletes lines in the entire buffer. DeleteLineArea deletes lines at the given line position, with the given
optional cell, within the rectangle bounds. Only cells within the
rectangle's bounds are affected. Lines are shifted up within the bounds and
new blank lines are created at the bottom. This follows terminal [ansi.DL]
behavior. Draw draws the buffer to the given screen at the specified area.
It implements the [Drawable] interface. Fill fills the buffer with the given cell and marks all lines as touched. FillArea fills the buffer with the given cell within the specified rectangle
and marks the affected lines as touched. Height implements Screen. InsertCell inserts new cells at the given position, with the given optional
cell, within the specified rectangles. If no rectangles are specified, it
inserts cells in the entire buffer. This follows terminal [ansi.ICH]
behavior. InsertCellArea inserts new cells at the given position, with the given
optional cell, within the rectangle bounds. Only cells within the
rectangle's bounds are affected, following terminal [ansi.ICH] behavior. InsertLine inserts n lines at the given line position, with the given
optional cell, within the specified rectangles. If no rectangles are
specified, it inserts lines in the entire buffer. Only cells within the
rectangle's horizontal bounds are affected. Lines are pushed out of the
rectangle bounds and lost. This follows terminal [ansi.IL] behavior. InsertLineArea inserts new lines at the given line position, with the given
optional cell, within the rectangle bounds. Only cells within the
rectangle's horizontal bounds are affected. Lines are pushed out of the
rectangle bounds and lost. This follows terminal [ansi.IL] behavior. Line returns a pointer to the line at the given y position.
If the line does not exist, it returns nil. Render renders the buffer to a styled string with all the required
attributes and styles. Resize resizes the buffer to the given width and height. SetCell sets the cell at the given x, y position and marks the line as
touched. String returns the string representation of the buffer. Touch marks the cell at the given x, y position as touched. TouchLine marks a line n times starting at the given x position as touched. TouchedLines returns the number of touched lines in the buffer. Width implements Screen.
RenderBuffer : Drawable
RenderBuffer : expvar.Var
RenderBuffer : fmt.Stringer
RenderBuffer : context.stringer
RenderBuffer : os/signal.stringer
RenderBuffer : runtime.stringer
func NewRenderBuffer(width, height int) *RenderBuffer
func (*TerminalRenderer).PrependString(newbuf *RenderBuffer, str string)
func (*TerminalRenderer).Redraw(newbuf *RenderBuffer)
func (*TerminalRenderer).Render(newbuf *RenderBuffer)
func moveCursor(s *TerminalRenderer, newbuf *RenderBuffer, x, y int, overwrite bool) (seq string)
func relativeCursorMove(s *TerminalRenderer, newbuf *RenderBuffer, fx, fy, tx, ty int, overwrite, useTabs, useBackspace bool) string
func (*TerminalRenderer).clearBelow(newbuf *RenderBuffer, blank *Cell, row int)
func (*TerminalRenderer).clearBottom(newbuf *RenderBuffer, total int) (top int)
func (*TerminalRenderer).clearToEnd(newbuf *RenderBuffer, blank *Cell, force bool)
func (*TerminalRenderer).clearUpdate(newbuf *RenderBuffer)
func (*TerminalRenderer).costEffective(newbuf *RenderBuffer, from, to int, blank bool) bool
func (*TerminalRenderer).emitRange(newbuf *RenderBuffer, line Line, n int) (eoi bool)
func (*TerminalRenderer).growHunks(newbuf *RenderBuffer)
func (*TerminalRenderer).insertCells(newbuf *RenderBuffer, line Line, count int)
func (*TerminalRenderer).move(newbuf *RenderBuffer, x, y int)
func (*TerminalRenderer).moveCursor(newbuf *RenderBuffer, x, y int, overwrite bool)
func (*TerminalRenderer).putAttrCell(newbuf *RenderBuffer, cell *Cell)
func (*TerminalRenderer).putCell(newbuf *RenderBuffer, cell *Cell)
func (*TerminalRenderer).putCellLR(newbuf *RenderBuffer, cell *Cell)
func (*TerminalRenderer).putRange(newbuf *RenderBuffer, oldLine, newLine Line, y, start, end int) (eoi bool)
func (*TerminalRenderer).reanchorWideLine(newbuf *RenderBuffer)
func (*TerminalRenderer).repaintLine(newbuf *RenderBuffer, y int)
func (*TerminalRenderer).scrollBuffer(b *RenderBuffer, n, top, bot int, blank *Cell)
func (*TerminalRenderer).scrollDown(newbuf *RenderBuffer, n, top, bot, minY, maxY int, blank *Cell) bool
func (*TerminalRenderer).scrollIdl(newbuf *RenderBuffer, n, del, ins int, blank *Cell) bool
func (*TerminalRenderer).scrolln(newbuf *RenderBuffer, n, top, bot, maxY int) (v bool)
func (*TerminalRenderer).scrollOptimize(newbuf *RenderBuffer)
func (*TerminalRenderer).scrollUp(newbuf *RenderBuffer, n, top, bot, minY, maxY int, blank *Cell) bool
func (*TerminalRenderer).touchLine(newbuf *RenderBuffer, y, n int, changed bool)
func (*TerminalRenderer).transformLine(newbuf *RenderBuffer, y int)
func (*TerminalRenderer).updateCost(_ *RenderBuffer, from, to Line) (cost int)
func (*TerminalRenderer).updateCostBlank(_ *RenderBuffer, to Line) (cost int)
func (*TerminalRenderer).updateHashmap(newbuf *RenderBuffer)
Screen represents a screen that can be drawn to. Bounds returns the bounds of the screen. This is the rectangle that
includes the start and end points of the screen. CellAt returns the cell at the given position. If the position is out of
bounds, it returns nil. Otherwise, it always returns a cell, even if it
is empty (i.e., a cell with a space character and a width of 1). SetCell sets the cell at the given position. A nil cell is treated as an
empty cell with a space character and a width of 1. WidthMethod returns the width method used by the screen.ScreenBuffer
*TerminalScreen
*Window
*charm.land/lipgloss/v2.Canvas
func (*Border).Draw(scr Screen, area Rectangle)
func (*Buffer).Draw(scr Screen, area Rectangle)
func Drawable.Draw(scr Screen, area Rectangle)
func DrawableFunc.Draw(scr Screen, rect Rectangle)
func (*StyledString).Draw(buf Screen, area Rectangle)
func charm.land/lipgloss/v2.(*Canvas).Draw(scr Screen, area Rectangle)
func charm.land/lipgloss/v2.(*Compositor).Draw(scr Screen, area image.Rectangle)
func charm.land/lipgloss/v2.(*Layer).Draw(scr Screen, area Rectangle)
func borderCell(scr Screen, b *Side) *Cell
func printString[T](s Screen, m WidthMethod, x, y int, bounds Rectangle, str T, truncate bool, tail string) (lines []Line)
ScreenBuffer is a buffer that can be used as a [Screen].Methodansi.MethodRenderBuffer*RenderBufferRenderBuffer.Buffer*Buffer Lines is a slice of lines that make up the cells of the buffer.RenderBuffer.Touched[]*LineData Bounds returns the bounds of the buffer.
The origin is always at (0, 0) and the maximum coordinates are determined by
the width and height of the buffer. CellAt returns the cell at the given position. It returns nil if the
position is out of bounds. Clear clears the buffer with space cells and marks all lines as touched. ClearArea clears the buffer with space cells within the specified rectangle
and marks the affected lines as touched. Clone clones the entire buffer into a new buffer. CloneArea clones the area of the buffer within the specified rectangle. If
the area is out of bounds, it returns nil. DeleteCell deletes cells at the given position, with the given optional
cell, within the specified rectangles. If no rectangles are specified, it
deletes cells in the entire buffer. This follows terminal [ansi.DCH]
behavior. DeleteCellArea deletes cells at the given position, with the given
optional cell, within the rectangle bounds. Only cells within the
rectangle's bounds are affected, following terminal [ansi.DCH] behavior. DeleteLine deletes n lines at the given line position, with the given
optional cell, within the specified rectangles. If no rectangles are
specified, it deletes lines in the entire buffer. DeleteLineArea deletes lines at the given line position, with the given
optional cell, within the rectangle bounds. Only cells within the
rectangle's bounds are affected. Lines are shifted up within the bounds and
new blank lines are created at the bottom. This follows terminal [ansi.DL]
behavior. Draw draws the buffer to the given screen at the specified area.
It implements the [Drawable] interface. Fill fills the buffer with the given cell and marks all lines as touched. FillArea fills the buffer with the given cell within the specified rectangle
and marks the affected lines as touched. Height implements Screen. InsertCell inserts new cells at the given position, with the given optional
cell, within the specified rectangles. If no rectangles are specified, it
inserts cells in the entire buffer. This follows terminal [ansi.ICH]
behavior. InsertCellArea inserts new cells at the given position, with the given
optional cell, within the rectangle bounds. Only cells within the
rectangle's bounds are affected, following terminal [ansi.ICH] behavior. InsertLine inserts n lines at the given line position, with the given
optional cell, within the specified rectangles. If no rectangles are
specified, it inserts lines in the entire buffer. Only cells within the
rectangle's horizontal bounds are affected. Lines are pushed out of the
rectangle bounds and lost. This follows terminal [ansi.IL] behavior. InsertLineArea inserts new lines at the given line position, with the given
optional cell, within the rectangle bounds. Only cells within the
rectangle's horizontal bounds are affected. Lines are pushed out of the
rectangle bounds and lost. This follows terminal [ansi.IL] behavior. Line returns a pointer to the line at the given y position.
If the line does not exist, it returns nil. Render renders the buffer to a styled string with all the required
attributes and styles. Resize resizes the buffer to the given width and height. SetCell sets the cell at the given x, y position and marks the line as
touched. String returns the string representation of the buffer. Touch marks the cell at the given x, y position as touched. TouchLine marks a line n times starting at the given x position as touched. TouchedLines returns the number of touched lines in the buffer. Width implements Screen. WidthMethod returns the width method used by the screen.
It defaults to [ansi.WcWidth].
ScreenBuffer : Drawable
ScreenBuffer : Screen
ScreenBuffer : expvar.Var
ScreenBuffer : fmt.Stringer
ScreenBuffer : context.stringer
ScreenBuffer : os/signal.stringer
ScreenBuffer : runtime.stringer
func NewScreenBuffer(width, height int) ScreenBuffer
SecondaryDeviceAttributesEvent is an event that represents the terminal
secondary device attributes.
See [ansi.SecondaryDeviceAttributes] for more details.
SizeNotifier represents a notifier that listens for window size
changes using the SIGWINCH signal and notifies the given channel. Channel that receives terminal size change notifications.fterm.Filemsync.Mutexsigchan os.Signal GetSize returns the current cell size of the terminal window. GetWindowSize returns the current size of the terminal window. Start starts listening for window size changes and notifies [SizeNotifier.C]
about any changes. Stop stops the notifier and cleans up resources.(*SizeNotifier) getWindowSize() (cells Size, pixels Size, err error)(*SizeNotifier) start() error(*SizeNotifier) stop() error
func NewSizeNotifier(f term.File) *SizeNotifier
StyledString is a string that can be decomposed into a series of styled
lines and cells. It is used to disassemble a rendered string with ANSI
escape codes into a series of cells that can be used in a [Buffer].
A StyledString supports reading [ansi.SGR] and [ansi.Hyperlink] escape
codes. Tail is the string that will be appended to the end of the line when the
string is truncated i.e. when [StyledString.Wrap] is false. Text is the original string that was used to create the styled string. Wrap determines whether the styled string should wrap to the next line. Bounds returns the minimum area that can contain the whole styled string. Draw renders the styled string to the given buffer at the
specified area. Height returns the number of lines in the styled string. This is the number
of lines that the styled string will occupy when rendered to the screen. Lines returns the styled string decomposed into a slice of [Line]s. String returns the text of the styled string.
It implements the [fmt.Stringer] interface. UnicodeWidth returns the cells width of the widest line in the styled string
using the [ansi.GraphemeWidth] method. WcWidth returns the cells width of the widest line in the styled string
using the [ansi.WcWidth] method.(*StyledString) widthHeight(m ansi.Method) (w, h int)
*StyledString : Drawable
*StyledString : expvar.Var
*StyledString : fmt.Stringer
*StyledString : context.stringer
*StyledString : os/signal.stringer
*StyledString : runtime.stringer
func NewStyledString(str string) *StyledString
TabStops represents horizontal line tab stops.intervalintstops[]intwidthint Clear removes all tab stops. Find returns the prev/next tab stop before/after the given column and delta.
If delta is positive, it returns the next tab stop after the given column.
If delta is negative, it returns the previous tab stop before the given column.
If delta is zero, it returns the given column. IsStop returns true if the given column is a tab stop. Next returns the next tab stop after the given column. Prev returns the previous tab stop before the given column. Reset removes the tab stop at the given column. Resize resizes the tab stops to the given width. Set adds a tab stop at the given column. Width returns the width of the screen that the tab stops are set for. init initializes the tab stops starting from col until width. mask returns the mask for the given column.
func DefaultTabStops(cols int) *TabStops
func NewTabStops(width, interval int) *TabStops
Terminal represents an interactive terminal application.buf[]byteconConsoledonecchan struct{}errgerrgroup.Groupevcchan Eventopts*OptionsprpollReaderscr*TerminalScreenwinchchan os.Signal Events returns the terminal's event channel. GetSize returns the current size of the terminal in characters and pixels. GetWinsize returns the current size of the terminal as a [Winsize] struct.
This includes both character dimensions (columns and rows) and pixel
dimensions (xpixel and ypixel).
Note that this only returns the pixel dimensions on Unix-like systems that
support the TIOCGWINSZ ioctl. On other platforms, the pixel dimensions may
be zero or not available. Read reads data from the terminal's console input.
This is a low-level operation that bypasses the terminal event processing
and reads directly from the console input handler, usually [os.Stdin] or the
controlling TTY. Use this method with caution, as it may interfere with the
terminal's event loop and screen management. Screen returns the terminal's screen. SendEvent sends an event to the terminal's event channel.
This can be used to inject custom events into the terminal's event loop,
such as timer events, signals, or application-specific events. Start starts the terminal application event loop. This is a non-blocking
call. Use [Terminal.Wait] to wait for the terminal to exit. Stop stops the terminal event loop. It is safe to call Stop without a
prior [Terminal.Start], and safe to call Stop multiple times in a row.
After Stop returns, [Terminal.Start] may be called again to resume. Wait waits for the terminal event loop to exit and returns any error that
occurred. Write writes data directly to the terminal's console output.
This is a low-level operation that bypasses the terminal screen buffering
and writes directly to the console output handler, usually [os.Stdout] or
the controlling TTY. handleEvent reacts to internal events before they are forwarded to the
application. It negotiates Unicode core mode (DEC mode 2027): when the
terminal reports the mode is in a settable or active state, it enables
grapheme-cluster width so wide-glyph measurement matches the terminal. The
event is still forwarded to the application.
The mode is only enabled for settable/active states (mode set, reset but
settable, or permanently set). It is explicitly not enabled when the mode is
not recognized or permanently reset, since those terminals cannot honor it.
Enabling goes through the screen's locked write path so it cannot race with
the application's Render/Flush.
*Terminal : internal/bisect.Writer
*Terminal : io.Reader
*Terminal : io.ReadWriter
*Terminal : io.Writer
*Terminal : crypto/tls.transcriptHash
func ControllingTerminal() (*Terminal, error)
func DefaultTerminal() *Terminal
func NewTerminal(con Console, opts *Options) *Terminal
TerminalReader represents an input event loop that reads input events from
a reader and parses them into human-readable events. It supports
reading escape sequences, mouse events, and bracketed paste mode. EscTimeout is the escape character timeout duration. Most escape
sequences start with an escape character [ansi.ESC] and are followed by
one or more characters. If the next character is not received within
this timeout, the reader will assume that the escape sequence is
complete and will process the received characters as a complete escape
sequence.
By default, this is set to [DefaultEscTimeout] (50 milliseconds).EventDecoderEventDecoder Legacy is the legacy key encoding flags. These flags control the
behavior of legacy terminal key encodings. See [LegacyKeyEncoding] for
more details. UseTerminfo is a flag that controls whether to use the terminal type
Terminfo database to map escape sequences to key events. This will
override the default key sequences handled by the parser. MouseMode determines whether mouse events are enabled or not. This is a
platform-specific feature and is only available on Windows. When this is
true, the reader will be initialized to read mouse events using the
Windows Console API. // the last control key state for the previous key event record.eventScanner*eventScanner // 0 key up, 1 key down // the last mouse button state for the previous event // the last window size for the previous event to prevent multiple size events from firing // the last window size for the previous event to prevent multiple size events from firing // The logger to use for debugging. // lookup indicates whether to use the lookup table for key sequences. paste is the bracketed paste mode buffer.
When nil, bracketed paste mode is disabled.rio.Reader // table is a lookup table for key sequences. // term is the terminal name $TERM. // 0 key up, 1 key down We use these buffers to decode UTF-16 sequences and graphemes from the
Windows Console API and Win32-Input-Mode events. // 0 key up, 1 key down vtInput indicates whether we're using Windows Console API VT input mode. Decode finds the first recognized event sequence and returns it along
with its length.
It will return zero and nil no sequence is recognized or when the buffer is
empty. If a sequence is not supported, an [UnknownEvent] is returned.
Example:
```go
var decoder EventDecoder
var events []Event
buf := []byte("\x00" + // Ctrl+Space
"\x1b[A" + // Up arrow
"Hello") // Text input
for len(buf) > 0 {
n, ev := decoder.Decode(buf)
if ev != nil {
events = append(events, ev)
}
buf = buf[n:]
}
``` SetLogger sets the logger to use for debugging. If nil, no logging will be
performed. StreamEvents sends events to the provided channel. It stops when the context
is closed or when an error occurs.(*TerminalReader) logf(format string, v ...interface{})(*TerminalReader) parseApc(b []byte) (int, Event)(*TerminalReader) parseControl(b byte) Event(*TerminalReader) parseCsi(b []byte) (int, Event)(*TerminalReader) parseDcs(b []byte) (int, Event)(*TerminalReader) parseOsc(b []byte) (int, Event) parseSs3 parses a SS3 sequence.
See https://vt100.net/docs/vt220-rm/chapter4.html#S4.4.4.2 parseStTerminated parses a control sequence that gets terminated by a ST character.(*TerminalReader) parseUtf8(b []byte) (int, Event) parseWin32InputKeyEvent converts a Windows Input Record Key Event into a
KeyPressEvent, KeyReleaseEvent, or MultiEvent including multiple of the
former type.
A special case is when the key is either part of VtInputMode which produces
vkc == 0, or when a key is a UTF-16 surrogate pair. In both of these cases,
we need to handle key encoding and properly parse the key event. sendBytes reads data from the reader and sends it to the provided channel.
It stops when an error occurs or when the context is closed.(*TerminalReader) sendEvents(eventc chan<- Event, buf []byte, expired bool) int streamData sends data from the input stream to the event channel.
*TerminalReader : EventStreamer
func NewTerminalReader(r io.Reader, termType string) *TerminalReader
TerminalRenderer is a terminal screen render and lazy writer that buffers
the output until it is flushed. It handles rendering a screen from a
[Buffer] to the terminal with the minimal necessary escape sequences to
transition the terminal to the new buffer state. It uses various escape
sequence optimizations to reduce the number of bytes sent to the terminal.
It's designed to be lazy and only flush the output when necessary by calling
the [TerminalRenderer.Flush] method.
The renderer handles the terminal's alternate screen and cursor visibility
via the [TerminalRenderer.EnterAltScreen], [TerminalRenderer.ExitAltScreen],
[TerminalRenderer.ShowCursor] and [TerminalRenderer.HideCursor] methods.
Using these methods will queue the appropriate escape sequences to enter or
exit the alternate screen and show or hide the cursor respectively to be
flushed to the terminal.
Use the [io.Writer] and [io.StringWriter] interfaces to queue custom
commands the renderer.
The renderer is not thread-safe, the caller must protect the renderer when
using it from multiple goroutines. // whether the cursor is out of bounds and at a phantom cell // buffer for writing to the screen // terminal control sequence capabilities // whether to force clear the screen // the current and saved cursors // the current buffer // terminal writer flags.hashermaphash.Hash // the hashmap table // whether the line currently being transformed contained a wide cell // The logger used for debugging. // the width method used to measure cell width // the old and new hash values for each line // the old and new hash values for each line // old indices from previous hash profile is the color profile to use when downsampling colors. This is
used to determine the appropriate color the terminal can display. // the current and saved cursorstabs*TabStops // the terminal typewio.Writer Buffered returns the number of bytes buffered for the next flush. EnterAltScreen is a helper that queues the [ansi.ModeAltScreenSaveCursor]
escape sequence to enter the alternate screen buffer and save cursor mode.
It saves the current cursor properties, enables
[TerminalRenderer.SetFullscreen] flag, and disables
[TerminalRenderer.SetRelativeCursor] flag. On the next call to
[TerminalRenderer.Render], it will move the cursor home and clear the screen
to prepare for rendering the new buffer.
Note: you might want to reapply the cursor visibility state after calling
this method, as some terminals reset the cursor visibility when switching to
the alternate screen. Erase marks the screen to be fully erased on the next render. ExitAltScreen is a helper that queues the [ansi.ModeAltScreenSaveCursor]
escape sequence to exit the alternate screen buffer and restore cursor mode.
It restores the saved cursor properties, disables
[TerminalRenderer.SetFullscreen] flag, and enables
[TerminalRenderer.SetRelativeCursor] flag. On the next call to
[TerminalRenderer.Render], it will move the cursor to the first line and
clear everything below the cursor to prepare for rendering the new buffer.
Note: you might want to reapply the cursor visibility state after calling
this method, as some terminals reset the cursor visibility when switching to
the alternate screen. Flush flushes the buffer to the screen. Fullscreen returns whether whole screen is being used. This is usually
paired with the alternate screen mode, and used to control cursor movements
and optimizations when the terminal is occupying the whole screen. MoveTo calculates and writes the shortest sequence to move the cursor to the
given position. It uses the current cursor position and the new position to
calculate the shortest amount of sequences to move the cursor. Position returns the cursor position in the screen buffer after applying any
pending transformations from the underlying buffer. PrependString adds the lines of the given string to the top of the terminal
screen. The lines prepended are not managed by the renderer and will not be
cleared or updated by the renderer.
Using this when the terminal is using the alternate screen or when occupying
the whole screen may not produce any visible effects. This is because
once the terminal writes the prepended lines, they will get overwritten
by the next frame. Redraw forces a full redraw of the screen. It's equivalent to calling
[TerminalRenderer.Erase] and [TerminalRenderer.Render]. Render renders changes of the screen to the internal buffer. Call
[terminalWriter.Flush] to flush pending changes to the screen. Resize updates the terminal screen tab stops. This is used to calculate
terminal tab stops for hard tab optimizations.
Resize also invalidates the cursor model when the renderer can recover
from it: a terminal may move the cursor on any resize, so the remembered
position no longer matches reality, and the next move will be absolute.
In relative cursor mode there is no absolute move to fall back on, and
-1 there means "first move, assume the origin" rather than "unknown", so
invalidating would assert a position instead of forgetting one. Keep the
old model in that mode and let the next render diff against it. RestoreCursor restores the saved cursor position and styles. This can be
used when a program exits the alternate screen buffer mode using DECRST 1049
[ansi.ModeAltScreenSaveCursor] and wants to restore the cursor position and
styles saved earlier. SaveCursor saves the current cursor position and styles. This can be used
when a program enters the alternate screen buffer mode using DECSET 1049
[ansi.ModeAltScreenSaveCursor] and wants to restore the cursor position and
styles later. SetBackspace sets whether to use backspace as a movement optimization. SetColorProfile sets the color profile to use for downsampling colors. This
is used to determine the appropriate color the terminal can display. SetFullscreen sets whether whole screen is being used. This is usually
paired with the alternate screen mode, and used to control cursor movements
and optimizations when the terminal is occupying the whole screen. SetGraphemeWidth sets whether the terminal measures cell width using Unicode
grapheme clustering (DEC mode 2027 / Unicode core). When enabled, the
renderer measures string width using [ansi.GraphemeWidth]; otherwise it
falls back to [ansi.WcWidth]. SetLogger sets the logger to use for debugging. If nil, no logging will be
performed. SetMapNewline sets whether the terminal is currently mapping newlines to
CRLF or carriage return and line feed. This is used to correctly determine
how to move the cursor when writing to the screen. SetPosition changes the logical cursor position. This can be used when we
change the cursor position outside of the screen and need to update the
screen cursor position.
This changes the cursor position for both normal and alternate screen
buffers. SetRelativeCursor sets whether to use relative cursor movements. SetScrollOptim sets whether to use hard scroll optimizations. SetTabStops sets the tab stops for the terminal and enables hard tabs
movement optimizations. Use -1 to disable hard tabs. This option is ignored
when the terminal type is "linux" as it does not support hard tabs. SetWidthMethod sets the width method the renderer uses to measure the
display width of strings. This should match the width method configured on
the screen so that the renderer doesn't disagree with the cell widths it is
asked to draw. Write writes the given bytes to the underlying buffer. WriteString writes the given string to the underlying buffer. clearBelow clears everything below and including the row. clearBlank returns a blank cell based on the current cursor background color. clearBottom tests if clearing the end of the screen would satisfy part of
the screen update. Scan backwards through lines in the screen checking if
each is blank and one or more are changed.
It returns the top line. clearScreen clears the screen and put cursor at home. clearToBottom clears the screen from the current cursor position to the end
of the screen. clearToEnd clears the screen from the current cursor position to the end of
line. clearUpdate forces a screen redraw. costEffective returns true if the cost of moving line 'from' to line 'to' seems to be
cost effective. 'blank' indicates whether the line 'to' would become blank. deleteCells deletes the count cells at the current cursor position and moves
the rest of the line to the left. This is equivalent to [ansi.DCH]. el0Cost returns the cost of using [ansi.EL] 0 i.e. [ansi.EraseLineRight]. If
this terminal supports background color erase, it can be cheaper to use
[ansi.EL] 0 i.e. [ansi.EraseLineRight] to clear
trailing spaces. emitRange emits a range of cells to the buffer. It it equivalent to calling
tscreen.putCell] for each cell in the range. This is optimized to use
[ansi.ECH] and [ansi.REP].
Returns whether the cursor is at the end of interval or somewhere in the
middle.(*TerminalRenderer) growHunks(newbuf *RenderBuffer) insertCells inserts the count cells pointed by the given line at the current
cursor position.(*TerminalRenderer) logf(format string, args ...any) move moves the cursor to the specified position in the buffer.
It is safe to call this function with a nil [Buffer], in that case, it won't
be using any optimizations that depend on the buffer. moveCursor moves the cursor to the specified position.
It is safe to call this function with a nil [Buffer], in that case, it won't
be using any optimizations that depend on the buffer.(*TerminalRenderer) putAttrCell(newbuf *RenderBuffer, cell *Cell) putCell draws a cell at the current cursor position. putCellLR draws a cell at the lower right corner of the screen. putRange puts a range of cells from the old line to the new line.
Returns whether the cursor is at the end of interval or somewhere in the
middle. reanchorWideLine re-anchors the cursor with a single absolute horizontal
move after a line that contained a wide cell. This is a best-effort fallback
that bounds cursor desync to one line on terminals whose width model
disagrees with ours. When the terminal negotiated Unicode grapheme width
(mode 2027) the models agree, so no re-anchor is needed. repaintLine repaints a line from scratch. Unlike
[TerminalRenderer.transformLine] it does not diff against the previous
frame: it erases the whole line from column 0 with [ansi.EraseLineRight]
and then writes the new frame's cells. Erasing from column 0 removes the
entire line including any wide cells the terminal painted at a different
width than the model measured, whose real extent the model cannot know.
The repaint then starts from a known-empty line and an absolute cursor
position, so the result does not depend on where the previous frame left
the cursor. scrollBuffer scrolls the buffer by n lines. scrollDown scrolls the screen down by n lines. scrollIdl scrolls the screen n lines by using [ansi.DL] at del and using
[ansi.IL] at ins. scrollOldhash scrolls the oldhash slice by 'n' lines between 'top' and 'bot'. scrollOptimize optimizes the screen to transform the old buffer into the new
buffer. scrollUp scrolls the screen up by n lines. scrolln scrolls the screen up by n lines. touchLine marks the line as touched. transformLine transforms the given line in the current window to the
corresponding line in the new window. It uses [ansi.ICH] and [ansi.DCH] to
insert or delete characters.(*TerminalRenderer) updateCost(_ *RenderBuffer, from, to Line) (cost int)(*TerminalRenderer) updateCostBlank(_ *RenderBuffer, to Line) (cost int) updateHashmap updates the hashmap with the new hash value. updatePen updates the cursor pen styles. wrapCursor wraps the cursor to the next line.
*TerminalRenderer : internal/bisect.Writer
*TerminalRenderer : io.StringWriter
*TerminalRenderer : io.Writer
*TerminalRenderer : crypto/tls.transcriptHash
*TerminalRenderer : golang.org/x/net/http2.stringWriter
*TerminalRenderer : testing.stringWriter
func NewTerminalRenderer(w io.Writer, env []string) (s *TerminalRenderer)
func moveCursor(s *TerminalRenderer, newbuf *RenderBuffer, x, y int, overwrite bool) (seq string)
func relativeCursorMove(s *TerminalRenderer, newbuf *RenderBuffer, fx, fy, tx, ty int, overwrite, useTabs, useBackspace bool) string
TerminalScreen represents a terminal screen, providing methods for managing
the screen state and rendering content. Terminal statebackgroundColorcolor.ColorbracketedPasteboolbuf*bytes.Buffer // initial state is cursor hiddenenvEnvironforegroundColorcolor.ColorkeyboardEnhancements*KeyboardEnhancementsmouseEncodingMouseEncodingmouseModeMouseMode mu serializes access to the render buffer, output buffer, and
width-method state so the terminal event loop (which negotiates
grapheme-cluster width) cannot race with the application's own
Render/Flush goroutine.profilecolorprofile.ProfileprogressBar*ProgressBarrbuf*RenderBufferrend*TerminalRenderer // DECST8C - reset terminal tabs on start // mode 2026wio.Writer widthMethodOverride is set when the application explicitly calls
[TerminalScreen.SetWidthMethod]. An explicit override suppresses the
automatic mode-2027 width-method negotiation.win*WindowwindowTitlestring AltScreen returns whether the terminal is currently in the alternate screen
buffer. BackgroundColor returns the current background color of the terminal.
A nil color indicates that the background color is the default terminal
background color. Bounds returns the bounds of the terminal screen as a rectangle. BracketedPaste returns whether bracketed paste mode is currently enabled. CellAt returns the cell at the specified x and y coordinates. CursorColor returns the current color of the terminal cursor.
A nil color indicates that the cursor color is the default terminal cursor
color. CursorPosition returns the last set cursor position of the terminal. If the
cursor position is not set, it returns (-1, -1).
This can be affected by [TerminalScreen.Render] and
[TerminalScreen.SetCursorPosition] calls. CursorStyle returns the current style of the terminal cursor. CursorVisible returns whether the terminal cursor is currently visible. DisableBracketedPaste disables bracketed paste mode.
The changes can be committed to the underlying writer by calling the
[TerminalScreen.Flush] method. Display clears the screen and draws the given [Drawable] onto the terminal
screen and flushes the changes to the underlying writer.
This is a convenience method that combines [TerminalScreen.Render] and
[TerminalScreen.Flush]. EnableBracketedPaste enables bracketed paste mode, allowing the terminal to
distinguish between pasted content and user input.
The changes can be committed to the underlying writer by calling the
[TerminalScreen.Flush] method. EnterAltScreen switches the terminal to the alternate screen buffer, allowing
applications to use a separate screen for their output without affecting the
main screen.
The changes can be committed to the underlying writer by calling the
[TerminalScreen.Flush] method. ExitAltScreen switches the terminal back to the main screen buffer, restoring
the previous screen state.
The changes can be committed to the underlying writer by calling the
[TerminalScreen.Flush] method. Flush writes any pending output to the underlying writer. ForegroundColor returns the current foreground color of the terminal.
A nil color indicates that the foreground color is the default terminal
foreground color. Height returns the height of the terminal screen.
Note that this is not the actual height of the terminal window, but rather
the height of the screen we're managing. The actual height of the terminal
window can be obtained using [Terminal.GetSize] or by reading the "LINES"
environment variable. HideCursor hides the terminal cursor.
The changes can be committed to the underlying writer by calling the
[TerminalScreen.Flush] method. InsertAbove inserts content above the screen pushing the current content
down.
This is useful for inserting content above the current screen content
without affecting the current cursor position or screen state.
Note that this won't have any visible effect if the screen is in alt screen
mode, as the content will be inserted above the alt screen buffer, which is
not visible. However, if the screen is in inline mode, the content will be
inserted above and will not be managed by the renderer.
Unlike other methods that modify the screen state, this method writes
directly to the underlying writer, so there is no need to call
[TerminalScreen.Flush] after calling this method. KeyboardEnhancements returns the current keyboard enhancements of the terminal.
A nil value indicates that no keyboard enhancements are currently enabled. MouseEncoding returns the current mouse encoding of the terminal. MouseMode returns the current mouse tracking mode of the terminal. ProgressBar returns the current progress bar of the terminal.
A nil value indicates that no progress bar is currently set. Render renders changes that transform the screen from its current state to
the state represented by the [TerminalScreen].
The changes can be committed to the underlying writer by calling the
[TerminalScreen.Flush] method. Reset resets the terminal screen to its default state, clearing the screen,
switching back to the main screen buffer if necessary, and resetting all
terminal settings to their defaults.
The changes can be committed to the underlying writer by calling the
[TerminalScreen.Flush] method. Resize resizes the terminal screen to the specified width and height,
updating the render buffer and renderer accordingly. Restore restores the terminal screen to its previous state, applying any
previous settings and state that were reset by the [TerminalScreen.Reset] method.
The changes can be committed to the underlying writer by calling the
[TerminalScreen.Flush] method. SetBackgroundColor sets the background color of the terminal.
The changes can be committed to the underlying writer by calling the
[TerminalScreen.Flush] method. SetCell sets the cell at the specified x and y coordinates. SetColorProfile sets the color profile for the terminal screen.
This is automatically detected when creating the terminal screen. However,
you can override it using this method. SetCursorColor sets the color of the terminal cursor.
The changes can be committed to the underlying writer by calling the
[TerminalScreen.Flush] method. SetCursorPosition sets the position of the terminal cursor to the specified
coordinates.
The changes can be committed to the underlying writer by calling the
[TerminalScreen.Flush] method. SetCursorStyle sets the style of the terminal cursor.
The changes can be committed to the underlying writer by calling the
[TerminalScreen.Flush] method. SetForegroundColor sets the foreground color of the terminal.
The changes can be committed to the underlying writer by calling the
[TerminalScreen.Flush] method. SetKeyboardEnhancements sets the keyboard enhancements for the terminal,
allowing applications to receive enhanced keyboard input.
The changes can be committed to the underlying writer by calling the
[TerminalScreen.Flush] method. SetMouseEncoding sets the mouse encoding for the terminal.
The encoding determines how mouse coordinates and buttons are reported.
This is only meaningful when mouse tracking is enabled via [TerminalScreen.SetMouseMode].
The changes can be committed to the underlying writer by calling the
[TerminalScreen.Flush] method. SetMouseMode sets the mouse tracking mode for the terminal, allowing
applications to receive mouse events.
The changes can be committed to the underlying writer by calling the
[TerminalScreen.Flush] method. SetProgressBar sets the progress bar for the terminal, allowing applications
to display progress information.
The changes can be committed to the underlying writer by calling the
[TerminalScreen.Flush] method. SetSynchronizedUpdates sets whether to use synchronized updates (mode 2026),
which allows applications to batch updates to the terminal screen and flush
them all at once for improved performance.
The changes can be committed to the underlying writer by calling the
[TerminalScreen.Flush] method. SetWidthMethod sets the width method for the terminal screen. This is an
override that propagates to the window/buffer and the renderer so that all
width measurements use the same method. Calling this marks the width method
as explicitly overridden, which disables automatic mode-2027 negotiation. SetWindowTitle sets the title of the terminal window.
The changes can be committed to the underlying writer by calling the
[TerminalScreen.Flush] method. ShowCursor shows the terminal cursor.
The changes can be committed to the underlying writer by calling the
[TerminalScreen.Flush] method. StringWidth returns the cell width of the given string using the terminal
screen's width method. This accounts for the configured [WidthMethod]
(e.g. wcwidth vs grapheme width) so callers don't need to import ansi
directly. SynchronizedUpdates returns whether synchronized updates (mode 2026) are
currently enabled. Width returns the width of the terminal screen.
Note that this is not the actual width of the terminal window, but rather
the width of the screen we're managing. The actual width of the terminal
window can be obtained using [Terminal.GetSize] or by reading the "COLUMNS"
environment variable. WidthMethod returns the width method used by the terminal screen. WindowTitle returns the current title of the terminal window. Write writes data to the underlying buffer queuing it for output.
The changes can be committed to the underlying writer by calling the
[TerminalScreen.Flush] method. WriteString writes a string to the underlying buffer queuing it for output.
The changes can be committed to the underlying writer by calling the
[TerminalScreen.Flush] method. enableGraphemeWidth enables Unicode core mode (DEC mode 2027) on the terminal
and switches the screen's width method to [ansi.GraphemeWidth] so wide-glyph
measurement matches the terminal. The change propagates to the
window/buffer and renderer.
If the application has explicitly set a width method via
[TerminalScreen.SetWidthMethod], the explicit choice is preserved and this is
a no-op. The change is committed to the underlying writer through the
screen's normal locked write path so it cannot race with Render/Flush. requestGraphemeWidth queues a DECRQM request for Unicode core mode (DEC mode
2027) so the terminal reports whether it measures cell width using grapheme
clustering. The response arrives as a [ModeReportEvent]. setWidthMethod propagates the width method to the window/buffer and the
renderer. Callers must hold s.mu.
*TerminalScreen : Screen
*TerminalScreen : WidthMethod
*TerminalScreen : internal/bisect.Writer
*TerminalScreen : io.StringWriter
*TerminalScreen : io.Writer
*TerminalScreen : crypto/tls.transcriptHash
*TerminalScreen : golang.org/x/net/http2.stringWriter
*TerminalScreen : testing.stringWriter
func NewTerminalScreen(w io.Writer, env Environ) *TerminalScreen
func (*Terminal).Screen() *TerminalScreen
TerminalVersionEvent is a message that represents the terminal version.Namestring String returns the terminal version as a string.
TerminalVersionEvent : expvar.Var
TerminalVersionEvent : fmt.Stringer
TerminalVersionEvent : context.stringer
TerminalVersionEvent : os/signal.stringer
TerminalVersionEvent : runtime.stringer
TertiaryDeviceAttributesEvent is an event that represents the terminal
tertiary device attributes.
See [ansi.TertiaryDeviceAttributes] for more details.
TTY represents a Unix TTY device. It implements the [Console] interface.console*consoleconsole.environEnvironconsole.inputFileconsole.inputState*term.Stateconsole.outputFileconsole.outputState*term.State Close restores the console to its previous state and releases resources. Environ returns the console's environment variables. GetSize returns the current size of the console. GetWinsize returns the current size of the console in cells and pixels. Getenv retrieves the value of the environment variable named by the key. LookupEnv retrieves the value of the environment variable named by the key
and a boolean indicating whether the variable is present. MakeRaw puts the console input side into raw mode. Read reads data from the console's input. Reader returns the input reader of the console. Restore restores the console to its previous state. Write writes data to the console's output. Writer returns the output writer of the console.
TTY : Console
TTY : internal/bisect.Writer
TTY : io.Closer
TTY : io.ReadCloser
TTY : io.Reader
TTY : io.ReadWriteCloser
TTY : io.ReadWriter
TTY : io.WriteCloser
TTY : io.Writer
TTY : crypto/tls.transcriptHash
func newConsole(in File, out File, env Environ) *TTY
Underline is the style of underline to use for text.
UnderlineStyle is the style of underline to use for text.
Deprecated: Use [Underline] instead.
UnknownApcEvent represents an unknown APC (Application Program Command) event. String returns a string representation of the unknown APC event.
UnknownApcEvent : expvar.Var
UnknownApcEvent : fmt.Stringer
UnknownApcEvent : context.stringer
UnknownApcEvent : os/signal.stringer
UnknownApcEvent : runtime.stringer
UnknownCsiEvent represents an unknown CSI (Control Sequence Introducer) event. String returns a string representation of the unknown CSI event.
UnknownCsiEvent : expvar.Var
UnknownCsiEvent : fmt.Stringer
UnknownCsiEvent : context.stringer
UnknownCsiEvent : os/signal.stringer
UnknownCsiEvent : runtime.stringer
UnknownDcsEvent represents an unknown DCS (Device Control String) event. String returns a string representation of the unknown DCS event.
UnknownDcsEvent : expvar.Var
UnknownDcsEvent : fmt.Stringer
UnknownDcsEvent : context.stringer
UnknownDcsEvent : os/signal.stringer
UnknownDcsEvent : runtime.stringer
UnknownEvent represents an unknown event. String returns a string representation of the unknown event.
UnknownEvent : expvar.Var
UnknownEvent : fmt.Stringer
UnknownEvent : context.stringer
UnknownEvent : os/signal.stringer
UnknownEvent : runtime.stringer
UnknownOscEvent represents an unknown OSC (Operating System Command) event. String returns a string representation of the unknown OSC event.
UnknownOscEvent : expvar.Var
UnknownOscEvent : fmt.Stringer
UnknownOscEvent : context.stringer
UnknownOscEvent : os/signal.stringer
UnknownOscEvent : runtime.stringer
UnknownPmEvent represents an unknown PM (Privacy Message) event. String returns a string representation of the unknown PM event.
UnknownPmEvent : expvar.Var
UnknownPmEvent : fmt.Stringer
UnknownPmEvent : context.stringer
UnknownPmEvent : os/signal.stringer
UnknownPmEvent : runtime.stringer
UnknownSosEvent represents an unknown SOS (Start of String) event. String returns a string representation of the unknown SOS event.
UnknownSosEvent : expvar.Var
UnknownSosEvent : fmt.Stringer
UnknownSosEvent : context.stringer
UnknownSosEvent : os/signal.stringer
UnknownSosEvent : runtime.stringer
UnknownSs3Event represents an unknown SS3 (Single Shift 3) event. String returns a string representation of the unknown SS3 event.
UnknownSs3Event : expvar.Var
UnknownSs3Event : fmt.Stringer
UnknownSs3Event : context.stringer
UnknownSs3Event : os/signal.stringer
UnknownSs3Event : runtime.stringer
WinCon represents a Windows Console. It implements the [Console] interface.console*consoleconsole.environEnvironconsole.inputFileconsole.inputState*term.Stateconsole.outputFileconsole.outputState*term.State Close restores the console to its previous state and releases resources. Environ returns the console's environment variables. GetSize returns the current size of the console. GetWinsize returns the current size of the console in cells and pixels. Getenv retrieves the value of the environment variable named by the key. LookupEnv retrieves the value of the environment variable named by the key
and a boolean indicating whether the variable is present. MakeRaw puts the console input side into raw mode. Read reads data from the console's input. Reader returns the input reader of the console. Restore restores the console to its previous state. Write writes data to the console's output. Writer returns the output writer of the console.
WinCon : Console
WinCon : internal/bisect.Writer
WinCon : io.Closer
WinCon : io.ReadCloser
WinCon : io.Reader
WinCon : io.ReadWriteCloser
WinCon : io.ReadWriter
WinCon : io.WriteCloser
WinCon : io.Writer
WinCon : crypto/tls.transcriptHash
Window represents a rectangular area on the screen. It can be a root window
with no parent, or a sub-window with a parent window. A window can have its
own buffer or share the buffer of its parent window (view).Buffer*Buffer Lines is a slice of lines that make up the cells of the buffer.boundsRectanglemethod*WidthMethodparent*Window Bounds returns the bounds of the window as a rectangle. CellAt returns the cell at the given position. It returns nil if the
position is out of bounds. Clear clears the buffer with space cells and rectangle. ClearArea clears the buffer with space cells within the specified
rectangles. Only cells within the rectangle's bounds are affected. Clone creates an exact copy of the window, including its buffer and values.
The cloned window will have the same parent and method as the original
window. CloneArea creates an exact copy of the window, including its buffer and
values, but only within the specified area. The cloned window will have the
same parent and method as the original window, but its bounds will be
limited to the specified area. DeleteCell deletes cells at the given position, with the given optional
cell, within the specified rectangles. If no rectangles are specified, it
deletes cells in the entire buffer. This follows terminal [ansi.DCH]
behavior. DeleteCellArea deletes cells at the given position, with the given
optional cell, within the rectangle bounds. Only cells within the
rectangle's bounds are affected, following terminal [ansi.DCH] behavior. DeleteLine deletes n lines at the given line position, with the given
optional cell, within the specified rectangles. If no rectangles are
specified, it deletes lines in the entire buffer. DeleteLineArea deletes lines at the given line position, with the given
optional cell, within the rectangle bounds. Only cells within the
rectangle's bounds are affected. Lines are shifted up within the bounds and
new blank lines are created at the bottom. This follows terminal [ansi.DL]
behavior. Draw draws the buffer to the given screen at the specified area.
It implements the [Drawable] interface. Fill fills the buffer with the given cell and rectangle. FillArea fills the buffer with the given cell and rectangle. HasParent returns whether the window has a parent window. This can be used
to determine if the window is a root window or a sub-window. Height implements Screen. InsertCell inserts new cells at the given position, with the given optional
cell, within the specified rectangles. If no rectangles are specified, it
inserts cells in the entire buffer. This follows terminal [ansi.ICH]
behavior. InsertCellArea inserts new cells at the given position, with the given
optional cell, within the rectangle bounds. Only cells within the
rectangle's bounds are affected, following terminal [ansi.ICH] behavior. InsertLine inserts n lines at the given line position, with the given
optional cell, within the specified rectangles. If no rectangles are
specified, it inserts lines in the entire buffer. Only cells within the
rectangle's horizontal bounds are affected. Lines are pushed out of the
rectangle bounds and lost. This follows terminal [ansi.IL] behavior.
It returns the pushed out lines. InsertLineArea inserts new lines at the given line position, with the
given optional cell, within the rectangle bounds. Only cells within the
rectangle's horizontal bounds are affected. Lines are pushed out of the
rectangle bounds and lost. This follows terminal [ansi.IL] behavior. Line returns a pointer to the line at the given y position.
If the line does not exist, it returns nil. MoveBy moves the window by the specified delta x and delta y. MoveTo moves the window to the specified x and y coordinates. NewView creates a new view into the parent window at the specified position
and size. Unlike [Window.NewWindow], this view shares the same buffer as the
parent window. NewWindow creates a new window with its own buffer relative to the parent
window at the specified position and size.
This will panic if width or height is negative. Parent returns the parent window of the current window.
If the window does not have a parent, it returns nil. Render renders the buffer to a styled string with all the required
attributes and styles. Resize resizes the window to the specified width and height. SetCell sets the cell at the given x, y position. SetWidthMethod sets the width method for the window. String returns the string representation of the buffer. Width implements Screen. WidthMethod returns the method used to calculate the width of characters in
the window.
Window : Drawable
*Window : Screen
Window : expvar.Var
Window : fmt.Stringer
Window : context.stringer
Window : os/signal.stringer
Window : runtime.stringer
func NewWindow(width, height int, method WidthMethod) *Window
func (*Window).Clone() *Window
func (*Window).CloneArea(area Rectangle) *Window
func (*Window).NewView(x, y, width, height int) *Window
func (*Window).NewWindow(x, y, width, height int) *Window
func (*Window).Parent() *Window
func newWindow(parent *Window, x, y, width, height int, method *WidthMethod, view bool) *Window
func newWindow(parent *Window, x, y, width, height int, method *WidthMethod, view bool) *Window
WindowOpEvent is a window operation (XTWINOPS) report event. This is used to
report various window operations such as reporting the window size or cell
size.Args[]intOpint
WindowSizeEvent represents the window size in cells.HeightintWidthint Bounds returns the bounds corresponding to the size.
capabilities represents a mask of supported ANSI escape sequences. Contains returns whether the capabilities contains the given capability. Reset resets the given capabilities. Set sets the given capabilities.
func xtermCaps(termtype string) (v capabilities)
const allCaps
const capBS
const capCBT
const capCHA
const capCHT
const capECH
const capHPA
const capHT
const capICH
const capREP
const capSD
const capSU
const capVPA
const noCaps
Console is a cross-platform console I/O.environEnvironinputFileinputState*term.StateoutputFileoutputState*term.State Close restores the console to its previous state and releases resources. Environ returns the console's environment variables. GetSize returns the current size of the console. GetWinsize returns the current size of the console in cells and pixels. Getenv retrieves the value of the environment variable named by the key. LookupEnv retrieves the value of the environment variable named by the key
and a boolean indicating whether the variable is present. MakeRaw puts the console input side into raw mode. Read reads data from the console's input. Reader returns the input reader of the console. Restore restores the console to its previous state. Write writes data to the console's output. Writer returns the output writer of the console.
*console : Console
*console : internal/bisect.Writer
*console : io.Closer
*console : io.ReadCloser
*console : io.Reader
*console : io.ReadWriteCloser
*console : io.ReadWriter
*console : io.WriteCloser
*console : io.Writer
*console : crypto/tls.transcriptHash
cursor represents a terminal cursor.CellCell Content is the [Cell]'s content, which consists of a single grapheme
cluster. Most of the time, this will be a single rune as well, but it
can also be a combination of runes that form a grapheme cluster. Link is the hyperlink of the cell. The style of the cell. Nil style means no style. Zero value prints a
reset sequence. Width is the mono-spaced width of the grapheme cluster.PositionPositionPosition.XintPosition.Yint Add returns the vector p+q. Clone returns a copy of the cell. Div returns the vector p/k. Empty makes the cell an empty cell by setting its content to a single space
and width to 1. Eq reports whether p and q are equal. Equal returns whether the cell is equal to the other cell. In reports whether p is in r. IsZero returns whether the cell is an empty cell. Mod returns the point q in r such that p.X-q.X is a multiple of r's width
and p.Y-q.Y is a multiple of r's height. Mul returns the vector p*k. Sub returns the vector p-q. isWidePlaceholder reports whether the cell is the continuation column of a
wide cell, marked with a zero display width.
*cursor : encoding/json/v2.isZeroer
eventScanner scans the buffer for events and sends them to the event channel.EventDecoderEventDecoder Legacy is the legacy key encoding flags. These flags control the
behavior of legacy terminal key encodings. See [LegacyKeyEncoding] for
more details. UseTerminfo is a flag that controls whether to use the terminal type
Terminfo database to map escape sequences to key events. This will
override the default key sequences handled by the parser. // the last control key state for the previous key event record. // 0 key up, 1 key downloggerLoggerlookupboolpaste[]bytetablemap[string]Key // 0 key up, 1 key down // 0 key up, 1 key down 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:]
}
``` deserializeWin32Input deserializes the Win32 input events converting
KeyEventRecrods to bytes. Before returning the bytes, it will also try to
decode any UTF-16 pairs that might be present in the input buffer.(*eventScanner) encodeGraphemeBufs() []byte(*eventScanner) logf(format string, v ...interface{})(*eventScanner) parseApc(b []byte) (int, Event)(*eventScanner) parseControl(b byte) Event(*eventScanner) parseCsi(b []byte) (int, Event)(*eventScanner) parseDcs(b []byte) (int, Event)(*eventScanner) parseOsc(b []byte) (int, Event) parseSs3 parses a SS3 sequence.
See https://vt100.net/docs/vt220-rm/chapter4.html#S4.4.4.2 parseStTerminated parses a control sequence that gets terminated by a ST character.(*eventScanner) parseUtf8(b []byte) (int, Event) parseWin32InputKeyEvent converts a Windows Input Record Key Event into a
KeyPressEvent, KeyReleaseEvent, or MultiEvent including multiple of the
former type.
A special case is when the key is either part of VtInputMode which produces
vkc == 0, or when a key is a UTF-16 surrogate pair. In both of these cases,
we need to handle key encoding and properly parse the key event.(*eventScanner) scanEvents(buf []byte, expired bool) (total int, events []Event) setLogger sets the logger to use for debugging. If nil, no logging will be
performed.(*eventScanner) storeGraphemeRune(kd int, r rune)
func newEventScanner() *eventScanner
fallbackReader implements pollReader using goroutines and buffered I/O.
This is a fallback implementation that works on all platforms.cancelChanchan struct{}canceledbooldataChanchan struct{}musync.Mutexreader*bufio.Readerstartedbool Cancel cancels any ongoing poll or read operations. Close closes the reader and releases any resources. Poll waits for data to be available to read with the given timeout.
This implementation starts a background goroutine to check for buffered
data availability. Read reads data from the underlying reader. checkBuffered runs in a background goroutine to signal when data is available.
*fallbackReader : github.com/muesli/cancelreader.CancelReader
*fallbackReader : io.Closer
*fallbackReader : io.ReadCloser
*fallbackReader : io.Reader
*fallbackReader : pollReader
ignoredEvent represents a sequence event that is ignored by the terminal
reader. This is used to ignore certain sequences that can be canceled.
pollReader reads data from an [io.Reader] using different native poll APIs
depending on the operating system.
On Linux, it uses the epoll API.
On Windows, it uses The Windows I/O and Console APIs.
On macOS and other BSD-based systems, it will try to use the kqueue API and
fall back to Unix select if kqueue is not available (e.g., on TTY).
On other Unix-like systems, it uses the select API.
On all other systems, it falls back to a simple read loop with a timeout. Cancel cancels any ongoing poll or read operations. It returns true if
an operation was canceled, false otherwise. Close closes the reader and releases any resources associated with it. Poll notifies when data is available to read with the given timeout. Use
a negative duration to wait indefinitely. Read reads data from the underlying [io.Reader]. It blocks until data is
available or an error occurs.
Use [pollReader] to check for data availability before calling Read to
avoid blocking.
*epollReader
*fallbackReader
pollReader : github.com/muesli/cancelreader.CancelReader
pollReader : io.Closer
pollReader : io.ReadCloser
pollReader : io.Reader
func newFallbackReader(reader io.Reader) (pollReader, error)
func newPollReader(reader io.Reader) (pollReader, error)
tFlag is a bitmask of terminal flags. Contains returns whether the terminal flags contains the given flags. Reset resets the given flags. Set sets the given flags.
const tFullscreen
const tGraphemeWidth
const tMapNewline
const tRelativeCursor
const tScrollOptim
Package-Level Functions (total 113, in which 58 are exported)
ASCIIBorder returns a table border with ASCII characters.
BlockBorder returns a border that takes the whole block.
ControllingConsole returns a new console instance that uses the current
controlling terminal's input and output file descriptors.
ControllingTerminal creates a new [Terminal] instance using the controlling
terminal's input and output file descriptors.
Options can be nil to use the default options.
This is a convenience function for creating a terminal that uses the
controlling TTY of the current process.
ConvertLink converts a hyperlink to respect the given color profile.
ConvertStyle converts a style to respect the given color profile.
DefaultConsole returns a new default console instance that uses standard I/O
[os.Stdin], [os.Stdout], and [os.Environ].
To use [os.Stderr] as the output, you can create a new console with
[NewConsole] and pass [os.Stderr] as the output parameter.
DefaultOptions returns the default [Terminal] options.
DefaultTabStops creates a new set of tab stops with the default interval.
DefaultTerminal creates a new [Terminal] instance using the default standard
console and the given options. Options can be nil to use the default
options.
This is a convenience function for creating a terminal that uses the
standard input and output file descriptors.
DoubleBorder returns a border comprised of two thin strokes.
EncodeBackgroundColor encodes the background color to the given writer. Use
nil to reset the background color to the default.
EncodeBracketedPaste encodes the bracketed paste mode to the given writer.
EncodeCursorColor encodes the cursor color to the given writer. Use nil to
reset the cursor color to the default.
EncodeCursorStyle encodes the cursor style to the given writer.
EncodeForegroundColor encodes the foreground color to the given writer. Use
nil to reset the foreground color to the default.
EncodeKeyboardEnhancements encodes the keyboard enhancements to the given
writer.
EncodeMouseEncoding encodes the mouse encoding mode to the given writer.
When enc is [MouseEncodingLegacy], all extended encodings are reset.
EncodeMouseMode encodes the mouse tracking mode to the given writer.
EncodeProgressBar encodes the progress bar to the given writer.
EncodeWindowTitle encodes the window title to the given writer.
HiddenBorder returns a border that renders as a series of single-cell
spaces. It's useful for cases when you want to remove a standard border but
maintain layout positioning. This said, you can still apply a background
color to a hidden border.
InnerHalfBlockBorder returns a half-block border that sits inside the frame.
MarkdownBorder return a table border in markdown style.
MousePixelToCell converts a mouse event with pixel coordinates to cell
coordinates.
This is only meaningful when using [MouseEncodingSGRPixel] encoding, which
reports mouse coordinates in pixels rather than cell units. The conversion
is based on the terminal's reported pixel dimensions and cell dimensions.
On Windows, or other platforms where [Terminal.GetWinsize] doesn't report
pixel dimensions, you can query for the terminal window pixel dimensions via
[ansi.WindowOp](4) and get back a [PixelSizeEvent] with the pixel
dimensions. You can then construct a [Winsize] struct with the pixel
dimensions and the cell dimensions from [Terminal.GetWinsize] and pass it to
this function.
NewBuffer creates a new buffer with the given width and height.
This is a convenience function that initializes a new buffer and resizes it.
NewCancelReader creates a new [cancelreader.CancelReader] that provides a
cancelable reader interface that can be used to cancel reads.
NewCell creates a new cell from the given string grapheme. It will only use
the first grapheme in the string and ignore the rest. The width of the cell
is determined using the given width method.
NewConsole creates a new [Console] with the given input, output, and
environment variables.
You can use [OpenTTY] to open the current controlling console files and pass
them to this function. Use [ControllingConsole] for a convenience function
that does this for you.
Use this to create a new terminal for PTY processes by passing the PTY slave
file as the input and output and any environment variables the process
needs.
NewCursor returns a new cursor with the default settings and the given
position.
NewKeyboardEnhancements returns a new [KeyboardEnhancements] with the given
options as flags.
A zero, or negative, flags value is treated as no enhancements.
See [ansi.KittyKeyboard] for more details on the supported keyboard enhancements.
NewLine creates a new line with the given width, filled with empty cells.
NewLink creates a new hyperlink with the given URL and parameters.
NewProgressBar returns a new progress bar with the given state and value.
The value is ignored if the state is [ProgressBarNone] or
[ProgressBarIndeterminate].
NewRenderBuffer creates a new [RenderBuffer] with the given width and height.
NewScreenBuffer creates a new ScreenBuffer with the given width and height.
NewSizeNotifier creates a new [SizeNotifier] that listens for window size
changes on the given TTY file through SIGWINCH signals.
NewStyledString creates a new [StyledString] for the given method and styled
string. The method is used to calculate the width of each line.
NewTabStops creates a new set of tab stops from a number of columns and an
interval.
NewTerminal creates a new [Terminal] instance with the given console and
options.
Options can be nil to use the default options.
NewTerminalReader returns a new input event reader. The reader streams input
events from the terminal and parses escape sequences into human-readable
events. It supports reading Terminfo databases.
Use [TerminalReader.UseTerminfo] to use Terminfo defined key sequences.
Use [TerminalReader.Legacy] to control legacy key encoding behavior.
Example:
```go
var cr cancelreader.CancelReader
var evc chan Event
sc := NewTerminalReader(cr, os.Getenv("TERM"))
go sc.StreamEvents(ctx, evc)
```
NewTerminalRenderer returns a new [TerminalRenderer] that uses the given
writer, terminal type, and initializes the width of the terminal. The
terminal type is used to determine the capabilities of the terminal and
should be set to the value of the TERM environment variable.
The renderer will try to detect the color profile from the output and the
given environment variables. Use [TerminalRenderer.SetColorProfile] method
to set a specific color profile for downsampling.
See [TerminalRenderer] for more information on how to use the renderer.
NewTerminalScreen creates a new [TerminalScreen] with the given writer and environment.
NewWindow creates a new root [Window] with the given size and width method.
If the method is nil, it defaults to [ansi.WcWidth].
The [WidthMethod] is used to calculate the width of characters in the
window, which is important for correctly rendering text, especially when
dealing with wide characters, combining characters, emojis, and other
Unicode characters that may have varying widths.
Use [ansi.WcWidth] as the default width method, which is a common
implementation that handles a wide range of Unicode characters according to
the Unicode Standard. Use [ansi.GraphemeWidth] if you know that your
terminal supports grapheme clusters and proper rendering of combining
characters and emojis, and you want to ensure that the width calculations
are based on grapheme clusters rather than individual code points.
This will panic if width or height is negative.
NormalBorder returns a standard-type border with a normal weight and 90
degree corners.
NotifyWinch sets up a channel to receive window size change signals and any
other signals needed. This is a drop-in replacement for os/signal.Notify to
ensure that SIGWINCH is included.
On Windows, this will be a no-op for SIGWINCH, but other signals may still
be handled.
NotifyWinchContext sets up a channel to receive window size change signals
and any other signals needed, with context cancellation support. This is a
drop-in replacement for os/signal.NotifyContext to ensure that SIGWINCH is
included.
On Windows, this will be a no-op for SIGWINCH, but other signals may still
be handled.
OpenTTY opens the terminal's input and output file descriptors.
It returns the input and output files, or an error if the terminal is not
available.
This is useful for applications that need to interact with the terminal
directly while piping or redirecting input/output.
OuterHalfBlockBorder returns a half-block border that sits outside the frame.
Pos is a shorthand for creating a new [Position].
ReadLink reads a hyperlink escape sequence from a data buffer into link.
ReadStyle reads a Select Graphic Rendition (SGR) escape sequences from a
list of parameters into pen.
Rect is a shorthand for creating a new [Rectangle].
RoundedBorder returns a border with rounded corners.
StyleDiff returns the SGR ANSI sequence necessary to transition from the
"from" style to the "to" style.
Suspend suspends the current process group.
ThickBorder returns a border that's thicker than the one returned by
NormalBorder.
TrimSpace trims trailing spaces from the end of each line in the given
string.
canClearWith checks whether the given cell can be used by clearing commands
like [ansi.EL] to clear the screen. It tests if a cell is empty i.e. space
or blank and doesn't include any bad style attributes such as [AttrReverse].
cellEqual returns whether the two cells are equal. A nil cell is considered
a [EmptyCell].
This returns a map of terminfo keys to key events. It's a mix of ncurses
terminfo default and user-defined key capabilities.
Upper-case caps that are defined in the default terminfo database are
- kNXT
- kPRV
- kHOM
- kEND
- kDC
- kIC
- kLFT
- kRIT
See https://man7.org/linux/man-pages/man5/terminfo.5.html
See https://github.com/mirror/ncurses/blob/master/include/Caps-ncurses
ensureKeyCase ensures that the key's text is in the correct case based on the
control key state.
lineHasDrift reports whether the line contains a cell that a cell-level
diff cannot safely reposition across: a wide cell (width > 1), or a cell
whose width the terminal may measure differently than the model. Wide cells
occupy several columns, so a diff that lands on a continuation column splits
the character; and a width disagreement means the model cannot know which
column each glyph landed on.
moveCursor moves and returns the cursor movement sequence to move the cursor
to the specified position.
When overwrite is true, this will try to optimize the sequence by using the
screen cells values to move the cursor instead of using escape sequences.
It is safe to call this function with a nil [Buffer]. In that case, it won't
use any optimizations that require the new buffer such as overwrite.
notLocal returns whether the coordinates are not considered local movement
using the defined thresholds.
This takes the number of columns, and the coordinates of the current and
target positions.
parseKittyKeyboard parses a Kitty Keyboard Protocol sequence.
In `CSI u`, this is parsed as:
CSI codepoint ; modifiers u
codepoint: ASCII Dec value
The Kitty Keyboard Protocol extends this with optional components that can be
enabled progressively. The full sequence is parsed as:
CSI unicode-key-code:alternate-key-codes ; modifiers:event-type ; text-as-codepoints u
See https://sw.kovidgoyal.net/kitty/keyboard-protocol/
parseKittyKeyboardExt parses a Kitty Keyboard Protocol sequence extensions
for non CSI u sequences. This includes things like CSI A, SS3 A and others,
and CSI ~.
Parse SGR-encoded mouse events; SGR extended mouse events. SGR mouse events
look like:
ESC [ < Cb ; Cx ; Cy (M or m)
where:
Cb is the encoded button code
Cx is the x-coordinate of the mouse
Cy is the y-coordinate of the mouse
M is for button press, m is for button release
https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Extended-coordinates
Parse X10-encoded mouse events; the simplest kind. The last release of X10
was December 1986, by the way. The original X10 mouse protocol limits the Cx
and Cy coordinates to 223 (=255-032).
X10 mouse events look like:
ESC [M Cb Cx Cy
See: http://www.xfree86.org/current/ctlseqs.html#Mouse%20Tracking
Type Parameters:
T: []byte | string printString draws a string starting at the given position. If s is nil, it
will build and return a slice of [Line]s instead (unwrapped, ignoring bounds).
relativeCursorMove returns the relative cursor movement sequence using one or two
of the following sequences [ansi.CUU], [ansi.CUD], [ansi.CUF], [ansi.CUB],
[ansi.VPA], [ansi.HPA].
When overwrite is true, this will try to optimize the sequence by using the
screen cells values to move the cursor instead of using escape sequences.
It is safe to call this function with a nil [Buffer]. In that case, it won't
use any optimizations that require the new buffer such as overwrite.
translateControlKeyState translates the control key state from the Windows
Console API into a Mod bitmask.
xtermCaps returns whether the terminal is xterm-like. This means that the
terminal supports ECMA-48 and ANSI X3.64 escape sequences.
xtermCaps returns a list of control sequence capabilities for the given
terminal type. This only supports a subset of sequences that can
be different among terminals.
NOTE: A hybrid approach would be to support Terminfo databases for a full
set of capabilities.
Package-Level Variables (total 10, in which 6 are exported)
EmptyCell is a cell with a single space, width of 1, and no style or link.
ErrCanceled is returned when a poll or read operation is canceled.
ErrInvalidDimensions is returned when the dimensions of a window are invalid
for the operation.
ErrNotTerminal is an error that indicates that the file is not a terminal.
ErrPlatformNotSupported is an error that indicates that the platform is not supported.
ErrReaderNotStarted is returned when the reader has not been started yet.
Package-Level Constants (total 250, in which 212 are exported)
These are the available text attributes that can be combined to create
different styles.
These are the available text attributes that can be combined to create
different styles.
These are the available text attributes that can be combined to create
different styles.
These are the available text attributes that can be combined to create
different styles.
These are the available text attributes that can be combined to create
different styles.
These are the available text attributes that can be combined to create
different styles.
These are the available text attributes that can be combined to create
different styles.
These are the available text attributes that can be combined to create
different styles.
AttrSlowBlink is an alias for AttrBlink.
Deprecated: Use [AttrBlink] instead.
These are the available text attributes that can be combined to create
different styles.
Cursor shapes.
Cursor shapes.
Cursor shapes.
DefaultBufferSize is the default size of the input buffer used for reading
terminal events.
DefaultEscTimeout is the default timeout at which the [TerminalReader] will
process ESC sequences. It is set to 50 milliseconds.
DefaultEventTimeout is the default duration to wait for input events before
timing out.
DefaultTabInterval is the default tab interval.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
KeyExtended is a special key code used to signify that a key event
contains multiple runes.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Special key symbols.
Modifier keys.
Modifier keys.
Modifier keys.
Modifier keys.
Modifier keys.
Modifier keys.
Modifier keys.
Modifier keys.
Modifier keys.
Mouse event buttons
This is based on X11 mouse button codes.
1 = left button
2 = middle button (pressing the scroll wheel)
3 = right button
4 = turn scroll wheel up
5 = turn scroll wheel down
6 = push scroll wheel left
7 = push scroll wheel right
8 = 4th button (aka browser backward button)
9 = 5th button (aka browser forward button)
10
11
Other buttons are not supported.
Mouse event buttons
This is based on X11 mouse button codes.
1 = left button
2 = middle button (pressing the scroll wheel)
3 = right button
4 = turn scroll wheel up
5 = turn scroll wheel down
6 = push scroll wheel left
7 = push scroll wheel right
8 = 4th button (aka browser backward button)
9 = 5th button (aka browser forward button)
10
11
Other buttons are not supported.
Mouse event buttons
This is based on X11 mouse button codes.
1 = left button
2 = middle button (pressing the scroll wheel)
3 = right button
4 = turn scroll wheel up
5 = turn scroll wheel down
6 = push scroll wheel left
7 = push scroll wheel right
8 = 4th button (aka browser backward button)
9 = 5th button (aka browser forward button)
10
11
Other buttons are not supported.
Mouse encodings.
These determine how mouse coordinates and buttons are encoded in the
terminal's escape sequences. The encoding is only meaningful when mouse
tracking is enabled via [MouseMode].
Mouse encodings.
These determine how mouse coordinates and buttons are encoded in the
terminal's escape sequences. The encoding is only meaningful when mouse
tracking is enabled via [MouseMode].
Mouse encodings.
These determine how mouse coordinates and buttons are encoded in the
terminal's escape sequences. The encoding is only meaningful when mouse
tracking is enabled via [MouseMode].
Mouse event buttons
This is based on X11 mouse button codes.
1 = left button
2 = middle button (pressing the scroll wheel)
3 = right button
4 = turn scroll wheel up
5 = turn scroll wheel down
6 = push scroll wheel left
7 = push scroll wheel right
8 = 4th button (aka browser backward button)
9 = 5th button (aka browser forward button)
10
11
Other buttons are not supported.
Mouse event buttons
This is based on X11 mouse button codes.
1 = left button
2 = middle button (pressing the scroll wheel)
3 = right button
4 = turn scroll wheel up
5 = turn scroll wheel down
6 = push scroll wheel left
7 = push scroll wheel right
8 = 4th button (aka browser backward button)
9 = 5th button (aka browser forward button)
10
11
Other buttons are not supported.
Mouse event buttons
This is based on X11 mouse button codes.
1 = left button
2 = middle button (pressing the scroll wheel)
3 = right button
4 = turn scroll wheel up
5 = turn scroll wheel down
6 = push scroll wheel left
7 = push scroll wheel right
8 = 4th button (aka browser backward button)
9 = 5th button (aka browser forward button)
10
11
Other buttons are not supported.
Mouse tracking modes.
These determine which mouse events the terminal reports.
Mouse tracking modes.
These determine which mouse events the terminal reports.
Mouse tracking modes.
These determine which mouse events the terminal reports.
Mouse tracking modes.
These determine which mouse events the terminal reports.
Mouse tracking modes.
These determine which mouse events the terminal reports.
Mouse event buttons
This is based on X11 mouse button codes.
1 = left button
2 = middle button (pressing the scroll wheel)
3 = right button
4 = turn scroll wheel up
5 = turn scroll wheel down
6 = push scroll wheel left
7 = push scroll wheel right
8 = 4th button (aka browser backward button)
9 = 5th button (aka browser forward button)
10
11
Other buttons are not supported.
Mouse event buttons
This is based on X11 mouse button codes.
1 = left button
2 = middle button (pressing the scroll wheel)
3 = right button
4 = turn scroll wheel up
5 = turn scroll wheel down
6 = push scroll wheel left
7 = push scroll wheel right
8 = 4th button (aka browser backward button)
9 = 5th button (aka browser forward button)
10
11
Other buttons are not supported.
Mouse event buttons
This is based on X11 mouse button codes.
1 = left button
2 = middle button (pressing the scroll wheel)
3 = right button
4 = turn scroll wheel up
5 = turn scroll wheel down
6 = push scroll wheel left
7 = push scroll wheel right
8 = 4th button (aka browser backward button)
9 = 5th button (aka browser forward button)
10
11
Other buttons are not supported.
Mouse event buttons
This is based on X11 mouse button codes.
1 = left button
2 = middle button (pressing the scroll wheel)
3 = right button
4 = turn scroll wheel up
5 = turn scroll wheel down
6 = push scroll wheel left
7 = push scroll wheel right
8 = 4th button (aka browser backward button)
9 = 5th button (aka browser forward button)
10
11
Other buttons are not supported.
Mouse event buttons
This is based on X11 mouse button codes.
1 = left button
2 = middle button (pressing the scroll wheel)
3 = right button
4 = turn scroll wheel up
5 = turn scroll wheel down
6 = push scroll wheel left
7 = push scroll wheel right
8 = 4th button (aka browser backward button)
9 = 5th button (aka browser forward button)
10
11
Other buttons are not supported.
Mouse event buttons
This is based on X11 mouse button codes.
1 = left button
2 = middle button (pressing the scroll wheel)
3 = right button
4 = turn scroll wheel up
5 = turn scroll wheel down
6 = push scroll wheel left
7 = push scroll wheel right
8 = 4th button (aka browser backward button)
9 = 5th button (aka browser forward button)
10
11
Other buttons are not supported.
Clipboard selections.
Progress bar states.
Progress bar states.
Progress bar states.
Progress bar states.
Progress bar states.
Clipboard selections.
These are the available underline styles.
These are the available underline styles.
These are the available underline styles.
These are the available underline styles.
These are the available underline styles.
These are the available underline styles.
These are the available underline styles.
Deprecated: Use the constants from [Underline] instead.
These are the available underline styles.
Deprecated: Use the constants from [Underline] instead.
These are the available underline styles.
Deprecated: Use the constants from [Underline] instead.
These are the available underline styles.
Deprecated: Use the constants from [Underline] instead.
These are the available underline styles.
Deprecated: Use the constants from [Underline] instead.
These are the available underline styles.
Deprecated: Use the constants from [Underline] instead.
These capabilities depend on the tty termios settings and are not
enabled by default.
Tabulation [ansi.HT].
Insert Character [ansi.ICH].
Repeat Previous Character [ansi.REP].
Scroll Down [ansi.SD].
Scroll Up [ansi.SU].
Vertical Position Absolute [ansi.VPA].
When this flag is set, the driver will send a BS (0x08 byte) character
instead of a DEL (0x7F byte) character when the Backspace key is
pressed.
The VT100 terminal has both a Backspace and a Delete key. The VT220
terminal dropped the Backspace key and replaced it with the Delete key.
Both terminals send a DEL character when the Delete key is pressed.
Modern terminals and PCs later readded the Delete key but used a
different key sequence, and the Backspace key was standardized to send a
DEL character.
When this flag is set, the driver will treat both Ctrl+Space and Ctrl+@
as the same key sequence.
Historically, the ANSI specs generate NUL (0x00) on both the Ctrl+Space
and Ctrl+@ key sequences. This flag allows the driver to treat both as
the same key sequence.
When this flag is set, the driver will treat the Tab key and Ctrl+I as
the same key sequence.
Historically, the ANSI specs generate HT (0x09) on both the Tab key and
Ctrl+I. This flag allows the driver to treat both as the same key
sequence.
When this flag is set, the driver will treat the Enter key and Ctrl+M as
the same key sequence.
Historically, the ANSI specs generate CR (0x0D) on both the Enter key
and Ctrl+M. This flag allows the driver to treat both as the same key.
When this flag is set, the driver will treat Escape and Ctrl+[ as
the same key sequence.
Historically, the ANSI specs generate ESC (0x1B) on both the Escape key
and Ctrl+[. This flag allows the driver to treat both as the same key
sequence.
When this flag is set, the driver will recognize the Find key instead of
treating it as a Home key.
The Find key was part of the VT220 keyboard, and is no longer used in
modern day PCs.
When this flag is set, the driver will preserve function keys (F13-F63)
as symbols.
Since these keys are not part of today's standard 20th century keyboard,
we treat them as F1-F12 modifier keys i.e. ctrl/shift/alt + Fn combos.
Key definitions come from Terminfo, this flag is only useful when
FlagTerminfo is not set.
When this flag is set, the driver will recognize the Select key instead
of treating it as a End key.
The Symbol key was part of the VT220 keyboard, and is no longer used in
modern day PCs.