tcell

package module
v2.5.4-0...-0e5909b Latest Latest
Warning

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

Go to latest
Published: Sep 8, 2022 License: Apache-2.0 Imports: 25 Imported by: 0

README

Tcell

Tcell is a Go package that provides a cell based view for text terminals, like XTerm. It was inspired by termbox, but includes many additional improvements.

Stand With Ukraine Linux Windows Apache License Docs Discord Coverage Go Report Card

Please see here for an important message for the people of Russia.

NOTE: This is version 2 of Tcell. There are breaking changes relative to version 1. Version 1.x remains available using the import github.com/chrBrd/tcell.

Tutorial

A brief, and still somewhat rough, tutorial is available.

Examples

  • proxima5 - space shooter (video)
  • govisor - service management UI (screenshot)
  • mouse demo - included mouse test (screenshot)
  • gomatrix - converted from Termbox
  • micro - lightweight text editor with syntax-highlighting and themes
  • godu - utility to discover large files/folders
  • tview - rich interactive widgets
  • cview - user interface toolkit (fork of tview)
  • awsome gocui - Go Console User Interface
  • gomandelbrot - Mandelbrot!
  • WTF - personal information dashboard
  • browsh - modern web browser (video)
  • go-life - Conway's Game of Life
  • gowid - compositional widgets for terminal UIs, inspired by urwid
  • termshark - interface for tshark, inspired by Wireshark, built on gowid
  • go-tetris - Go Tetris with AI option
  • fzf - command-line fuzzy finder
  • ascii-fluid - fluid simulation controlled by webcam
  • cbind - key event encoding, decoding and handling
  • tpong - old-school Pong
  • aerc - email client
  • tblogs - development blogs reader
  • spinc - irssi inspired chat application for Cisco Spark/WebEx
  • gorss - RSS/Atom feed reader
  • memoryalike - memorization game
  • lf - file manager
  • goful - CUI file manager
  • gokeybr - deliberately practice your typing
  • gonano - editor, mimics nano
  • uchess - UCI chess client
  • min - Gemini browser
  • ov - file pager
  • tmux-wormhole - tmux plugin to transfer files
  • gruid-tcell - driver for the grid based UI and game framework
  • aretext - minimalist text editor with vim key bindings
  • sync - GitHub repo synchronization tool
  • statusbar - statusbar motivation tool for tracking periodic tasks/goals
  • todo - simple todo app
  • gosnakego - a snake game

Pure Go Terminfo Database

Tcell includes a full parser and expander for terminfo capability strings, so that it can avoid hard coding escape strings for formatting. It also favors portability, and includes support for all POSIX systems.

The database is also flexible & extensible, and can be modified by either running a program to build the entire database, or an entry for just a single terminal.

More Portable

Tcell is portable to a wide variety of systems, and is pure Go, without any need for CGO. Tcell is believed to work with mainstream systems officially supported by golang.

No Async IO

Tcell is able to operate without requiring SIGIO signals (unlike termbox), or asynchronous I/O, and can instead use standard Go file objects and Go routines. This means it should be safe, especially for use with programs that use exec, or otherwise need to manipulate the tty streams. This model is also much closer to idiomatic Go, leading to fewer surprises.

Rich Unicode & non-Unicode support

Tcell includes enhanced support for Unicode, including wide characters and combining characters, provided your terminal can support them. Note that Windows terminals generally don't support the full Unicode repertoire.

It will also convert to and from Unicode locales, so that the program can work with UTF-8 internally, and get reasonable output in other locales. Tcell tries hard to convert to native characters on both input and output. On output Tcell even makes use of the alternate character set to facilitate drawing certain characters.

More Function Keys

Tcell also has richer support for a larger number of special keys that some terminals can send.

Better Color Handling

Tcell will respect your terminal's color space as specified within your terminfo entries. For example attempts to emit color sequences on VT100 terminals won't result in unintended consequences.

In legacy Windows mode, Tcell supports 16 colors, bold, dim, and reverse, instead of just termbox's 8 colors with reverse. (Note that there is some conflation with bold/dim and colors.) Modern Windows 10 can benefit from much richer colors however.

Tcell maps 16 colors down to 8, for terminals that need it. (The upper 8 colors are just brighter versions of the lower 8.)

Better Mouse Support

Tcell supports enhanced mouse tracking mode, so your application can receive regular mouse motion events, and wheel events, if your terminal supports it.

(Note: The Windows 10 Terminal application suffers from a flaw in this regard, and does not support mouse interaction. The stock Windows 10 console host fired up with cmd.exe or PowerShell works fine however.)

Termbox Compatibility

A compatibility layer for termbox is provided in the compat directory. To use it, try importing github.com/chrBrd/tcell/termbox instead. Most termbox-go programs will probably work without further modification.

Working With Unicode

Internally Tcell uses UTF-8, just like Go. However, Tcell understands how to convert to and from other character sets, using the capabilities of the golang.org/x/text/encoding packages. Your application must supply them, as the full set of the most common ones bloats the program by about 2 MB. If you're lazy, and want them all anyway, see the encoding sub-directory.

Wide & Combining Characters

The SetContent() API takes a primary rune, and an optional list of combining runes. If any of the runes is a wide (East Asian) rune occupying two cells, then the library will skip output from the following cell. Care must be taken in the application to avoid explicitly attempting to set content in the next cell, otherwise the results are undefined. (Normally the wide character is displayed, and the other character is not; do not depend on that behavior.)

Older terminal applications (especially on systems like Windows 8) lack support for advanced Unicode, and thus may not fare well.

Colors

Tcell assumes the ANSI/XTerm color model, including the 256 color map that XTerm uses when it supports 256 colors. The terminfo guidance will be honored, with respect to the number of colors supported. Also, only terminals which expose ANSI style setaf and setab will support color; if you have a color terminal that only has setf and setb, please submit a ticket.

24-bit Color

Tcell supports 24-bit color! (That is, if your terminal can support it.)

NOTE: Technically the approach of using 24-bit RGB values for color is more accurately described as "direct color", but most people use the term "true color". We follow the (inaccurate) common convention.

There are a few ways you can enable (or disable) true color.

  • For many terminals, we can detect it automatically if your terminal includes the RGB or Tc capabilities (or rather it did when the database was updated.)

  • You can force this one by setting the COLORTERM environment variable to 24-bit, truecolor or 24bit. This is the same method used by most other terminal applications that support 24-bit color.

  • If you set your TERM environment variable to a value with the suffix -truecolor then 24-bit color compatible with XTerm and ECMA-48 will be assumed. (This feature is deprecated. It is recommended to use one of other methods listed above.)

  • You can disable 24-bit color by setting TCELL_TRUECOLOR=disable in your environment.

When using TrueColor, programs will display the colors that the programmer intended, overriding any "themes" you may have set in your terminal emulator. (For some cases, accurate color fidelity is more important than respecting themes. For other cases, such as typical text apps that only use a few colors, its more desirable to respect the themes that the user has established.)

Performance

Reasonable attempts have been made to minimize sending data to terminals, avoiding repeated sequences or drawing the same cell on refresh updates.

Terminfo

(Not relevant for Windows users.)

The Terminfo implementation operates with a built-in database. This should satisfy most users. However, it can also (on systems with ncurses installed), dynamically parse the output from infocmp for terminals it does not already know about.

See the terminfo/ directory for more information about generating new entries for the built-in database.

Tcell requires that the terminal support the cup mode of cursor addressing. Ancient terminals without the ability to position the cursor directly are not supported. This is unlikely to be a problem; such terminals have not been mass-produced since the early 1970s.

Mouse Support

Mouse support is detected via the kmous terminfo variable, however, enablement/disablement and decoding mouse events is done using hard coded sequences based on the XTerm X11 model. All popular terminals with mouse tracking support this model. (Full terminfo support is not possible as terminfo sequences are not defined.)

On Windows, the mouse works normally.

Mouse wheel buttons on various terminals are known to work, but the support in terminal emulators, as well as support for various buttons and live mouse tracking, varies widely. Modern xterm, macOS Terminal, and iTerm all work well.

Bracketed Paste

Terminals that appear to support the XTerm mouse model also can support bracketed paste, for applications that opt-in. See EnablePaste() for details.

Testability

There is a SimulationScreen, that can be used to simulate a real screen for automated testing. The supplied tests do this. The simulation contains event delivery, screen resizing support, and capabilities to inject events and examine "physical" screen contents.

Platforms

POSIX (Linux, FreeBSD, macOS, Solaris, etc.)

Everything works using pure Go on mainstream platforms. Some more esoteric platforms (e.g., AIX) may need to be added. Pull requests are welcome!

Windows

Windows console mode applications are supported.

Modern console applications like ConEmu and the Windows 10 terminal, support all the good features (resize, mouse tracking, etc.)

Plan9, WASM, and others

These platforms won't work, but compilation stubs are supplied for folks that want to include parts of this in software for those platforms. The Simulation screen works, but as Tcell doesn't know how to allocate a real screen object on those platforms, NewScreen() will fail.

If anyone has wisdom about how to improve support for these, please let me know. PRs are especially welcome.

Commercial Support

Tcell is absolutely free, but if you want to obtain commercial, professional support, there are options.

  • TideLift subscriptions include support for Tcell, as well as many other open source packages.
  • Staysail Systems Inc. offers direct support, and custom development around Tcell on an hourly basis.

Documentation

Overview

Package tcell provides a lower-level, portable API for building programs that interact with terminals or consoles. It works with both common (and many uncommon!) terminals or terminal emulators, and Windows console implementations.

It provides support for up to 256 colors, text attributes, and box drawing elements. A database of terminals built from a real terminfo database is provided, along with code to generate new database entries.

Tcell offers very rich support for mice, dependent upon the terminal of course. (Windows, XTerm, and iTerm 2 are known to work very well.)

If the environment is not Unicode by default, such as an ISO8859 based locale or GB18030, Tcell can convert input and output, so that your terminal can operate in whatever locale is most convenient, while the application program can just assume "everything is UTF-8". Reasonable defaults are used for updating characters to something suitable for display. Unicode box drawing characters will be converted to use the alternate character set of your terminal, if native conversions are not available. If no ACS is available, then some ASCII fallbacks will be used.

Note that support for non-UTF-8 locales (other than C) must be enabled by the application using RegisterEncoding() -- we don't have them all enabled by default to avoid bloating the application unnecessarily. (These days UTF-8 is good enough for almost everyone, and nobody should be using legacy locales anymore.) Also, actual glyphs for various code point will only be displayed if your terminal or emulator (or the font the emulator is using) supports them.

A rich set of keycodes is supported, with support for up to 65 function keys, and various other special keys.

Index

Constants

View Source
const (
	ColorBlack = ColorValid + iota
	ColorMaroon
	ColorGreen
	ColorOlive
	ColorNavy
	ColorPurple
	ColorTeal
	ColorSilver
	ColorGray
	ColorRed
	ColorLime
	ColorYellow
	ColorBlue
	ColorFuchsia
	ColorAqua
	ColorWhite
	Color16
	Color17
	Color18
	Color19
	Color20
	Color21
	Color22
	Color23
	Color24
	Color25
	Color26
	Color27
	Color28
	Color29
	Color30
	Color31
	Color32
	Color33
	Color34
	Color35
	Color36
	Color37
	Color38
	Color39
	Color40
	Color41
	Color42
	Color43
	Color44
	Color45
	Color46
	Color47
	Color48
	Color49
	Color50
	Color51
	Color52
	Color53
	Color54
	Color55
	Color56
	Color57
	Color58
	Color59
	Color60
	Color61
	Color62
	Color63
	Color64
	Color65
	Color66
	Color67
	Color68
	Color69
	Color70
	Color71
	Color72
	Color73
	Color74
	Color75
	Color76
	Color77
	Color78
	Color79
	Color80
	Color81
	Color82
	Color83
	Color84
	Color85
	Color86
	Color87
	Color88
	Color89
	Color90
	Color91
	Color92
	Color93
	Color94
	Color95
	Color96
	Color97
	Color98
	Color99
	Color100
	Color101
	Color102
	Color103
	Color104
	Color105
	Color106
	Color107
	Color108
	Color109
	Color110
	Color111
	Color112
	Color113
	Color114
	Color115
	Color116
	Color117
	Color118
	Color119
	Color120
	Color121
	Color122
	Color123
	Color124
	Color125
	Color126
	Color127
	Color128
	Color129
	Color130
	Color131
	Color132
	Color133
	Color134
	Color135
	Color136
	Color137
	Color138
	Color139
	Color140
	Color141
	Color142
	Color143
	Color144
	Color145
	Color146
	Color147
	Color148
	Color149
	Color150
	Color151
	Color152
	Color153
	Color154
	Color155
	Color156
	Color157
	Color158
	Color159
	Color160
	Color161
	Color162
	Color163
	Color164
	Color165
	Color166
	Color167
	Color168
	Color169
	Color170
	Color171
	Color172
	Color173
	Color174
	Color175
	Color176
	Color177
	Color178
	Color179
	Color180
	Color181
	Color182
	Color183
	Color184
	Color185
	Color186
	Color187
	Color188
	Color189
	Color190
	Color191
	Color192
	Color193
	Color194
	Color195
	Color196
	Color197
	Color198
	Color199
	Color200
	Color201
	Color202
	Color203
	Color204
	Color205
	Color206
	Color207
	Color208
	Color209
	Color210
	Color211
	Color212
	Color213
	Color214
	Color215
	Color216
	Color217
	Color218
	Color219
	Color220
	Color221
	Color222
	Color223
	Color224
	Color225
	Color226
	Color227
	Color228
	Color229
	Color230
	Color231
	Color232
	Color233
	Color234
	Color235
	Color236
	Color237
	Color238
	Color239
	Color240
	Color241
	Color242
	Color243
	Color244
	Color245
	Color246
	Color247
	Color248
	Color249
	Color250
	Color251
	Color252
	Color253
	Color254
	Color255
	ColorAliceBlue
	ColorAntiqueWhite
	ColorAquaMarine
	ColorAzure
	ColorBeige
	ColorBisque
	ColorBlanchedAlmond
	ColorBlueViolet
	ColorBrown
	ColorBurlyWood
	ColorCadetBlue
	ColorChartreuse
	ColorChocolate
	ColorCoral
	ColorCornflowerBlue
	ColorCornsilk
	ColorCrimson
	ColorDarkBlue
	ColorDarkCyan
	ColorDarkGoldenrod
	ColorDarkGray
	ColorDarkGreen
	ColorDarkKhaki
	ColorDarkMagenta
	ColorDarkOliveGreen
	ColorDarkOrange
	ColorDarkOrchid
	ColorDarkRed
	ColorDarkSalmon
	ColorDarkSeaGreen
	ColorDarkSlateBlue
	ColorDarkSlateGray
	ColorDarkTurquoise
	ColorDarkViolet
	ColorDeepPink
	ColorDeepSkyBlue
	ColorDimGray
	ColorDodgerBlue
	ColorFireBrick
	ColorFloralWhite
	ColorForestGreen
	ColorGainsboro
	ColorGhostWhite
	ColorGold
	ColorGoldenrod
	ColorGreenYellow
	ColorHoneydew
	ColorHotPink
	ColorIndianRed
	ColorIndigo
	ColorIvory
	ColorKhaki
	ColorLavender
	ColorLavenderBlush
	ColorLawnGreen
	ColorLemonChiffon
	ColorLightBlue
	ColorLightCoral
	ColorLightCyan
	ColorLightGoldenrodYellow
	ColorLightGray
	ColorLightGreen
	ColorLightPink
	ColorLightSalmon
	ColorLightSeaGreen
	ColorLightSkyBlue
	ColorLightSlateGray
	ColorLightSteelBlue
	ColorLightYellow
	ColorLimeGreen
	ColorLinen
	ColorMediumAquamarine
	ColorMediumBlue
	ColorMediumOrchid
	ColorMediumPurple
	ColorMediumSeaGreen
	ColorMediumSlateBlue
	ColorMediumSpringGreen
	ColorMediumTurquoise
	ColorMediumVioletRed
	ColorMidnightBlue
	ColorMintCream
	ColorMistyRose
	ColorMoccasin
	ColorNavajoWhite
	ColorOldLace
	ColorOliveDrab
	ColorOrange
	ColorOrangeRed
	ColorOrchid
	ColorPaleGoldenrod
	ColorPaleGreen
	ColorPaleTurquoise
	ColorPaleVioletRed
	ColorPapayaWhip
	ColorPeachPuff
	ColorPeru
	ColorPink
	ColorPlum
	ColorPowderBlue
	ColorRebeccaPurple
	ColorRosyBrown
	ColorRoyalBlue
	ColorSaddleBrown
	ColorSalmon
	ColorSandyBrown
	ColorSeaGreen
	ColorSeashell
	ColorSienna
	ColorSkyblue
	ColorSlateBlue
	ColorSlateGray
	ColorSnow
	ColorSpringGreen
	ColorSteelBlue
	ColorTan
	ColorThistle
	ColorTomato
	ColorTurquoise
	ColorViolet
	ColorWheat
	ColorWhiteSmoke
	ColorYellowGreen
)

Note that the order of these options is important -- it follows the definitions used by ECMA and XTerm. Hence any further named colors must begin at a value not less than 256.

View Source
const (
	ColorGrey           = ColorGray
	ColorDimGrey        = ColorDimGray
	ColorDarkGrey       = ColorDarkGray
	ColorDarkSlateGrey  = ColorDarkSlateGray
	ColorLightGrey      = ColorLightGray
	ColorLightSlateGrey = ColorLightSlateGray
	ColorSlateGrey      = ColorSlateGray
)

These are aliases for the color gray, because some of us spell it as grey.

View Source
const (
	// EncodingFallbackFail behavior causes GetEncoding to fail
	// when it cannot find an encoding.
	EncodingFallbackFail = iota

	// EncodingFallbackASCII behaviore causes GetEncoding to fall back
	// to a 7-bit ASCII encoding, if no other encoding can be found.
	EncodingFallbackASCII

	// EncodingFallbackUTF8 behavior causes GetEncoding to assume
	// UTF8 can pass unmodified upon failure.  Note that this behavior
	// is not recommended, unless you are sure your terminal can cope
	// with real UTF8 sequences.
	EncodingFallbackUTF8
)
View Source
const (
	KeyBackspace  = KeyBS
	KeyTab        = KeyTAB
	KeyEsc        = KeyESC
	KeyEscape     = KeyESC
	KeyEnter      = KeyCR
	KeyBackspace2 = KeyDEL
)

These keys are aliases for other names.

View Source
const (
	RuneSterling = '£'
	RuneDArrow   = '↓'
	RuneLArrow   = '←'
	RuneRArrow   = '→'
	RuneUArrow   = '↑'
	RuneBullet   = '·'
	RuneBoard    = '░'
	RuneCkBoard  = '▒'
	RuneDegree   = '°'
	RuneDiamond  = '◆'
	RuneGEqual   = '≥'
	RunePi       = 'π'
	RuneHLine    = '─'
	RuneLantern  = '§'
	RunePlus     = '┼'
	RuneLEqual   = '≤'
	RuneLLCorner = '└'
	RuneLRCorner = '┘'
	RuneNEqual   = '≠'
	RunePlMinus  = '±'
	RuneS1       = '⎺'
	RuneS3       = '⎻'
	RuneS7       = '⎼'
	RuneS9       = '⎽'
	RuneBlock    = '█'
	RuneTTee     = '┬'
	RuneRTee     = '┤'
	RuneLTee     = '├'
	RuneBTee     = '┴'
	RuneULCorner = '┌'
	RuneURCorner = '┐'
	RuneVLine    = '│'
)

The names of these constants are chosen to match Terminfo names, modulo case, and changing the prefix from ACS_ to Rune. These are the runes we provide extra special handling for, with ASCII fallbacks for terminals that lack them.

View Source
const (
	MouseButtonEvents = MouseFlags(1) // Click events only
	MouseDragEvents   = MouseFlags(2) // Click-drag events (includes button events)
	MouseMotionEvents = MouseFlags(4) // All mouse events (includes click and drag events)
)
View Source
const (
	CursorStyleDefault = CursorStyle(iota) // The default
	CursorStyleBlinkingBlock
	CursorStyleSteadyBlock
	CursorStyleBlinkingUnderline
	CursorStyleSteadyUnderline
	CursorStyleBlinkingBar
	CursorStyleSteadyBar
)
View Source
const (
	// ColorReset is used to indicate that the color should use the
	// vanilla terminal colors.  (Basically go back to the defaults.)
	ColorReset = ColorSpecial | iota
)

Special colors.

Variables

View Source
var (
	// ErrTermNotFound indicates that a suitable terminal entry could
	// not be found.  This can result from either not having TERM set,
	// or from the TERM failing to support certain minimal functionality,
	// in particular absolute cursor addressability (the cup capability)
	// is required.  For example, legacy "adm3" lacks this capability,
	// whereas the slightly newer "adm3a" supports it.  This failure
	// occurs most often with "dumb".
	ErrTermNotFound = terminfo.ErrTermNotFound

	// ErrNoScreen indicates that no suitable screen could be found.
	// This may result from attempting to run on a platform where there
	// is no support for either termios or console I/O (such as nacl),
	// or from running in an environment where there is no access to
	// a suitable console/terminal device.  (For example, running on
	// without a controlling TTY or with no /dev/tty on POSIX platforms.)
	ErrNoScreen = errors.New("no suitable screen available")

	// ErrNoCharset indicates that the locale environment the
	// program is not supported by the program, because no suitable
	// encoding was found for it.  This problem never occurs if
	// the environment is UTF-8 or UTF-16.
	ErrNoCharset = errors.New("character set not supported")

	// ErrEventQFull indicates that the event queue is full, and
	// cannot accept more events.
	ErrEventQFull = errors.New("event queue full")
)
View Source
var ColorNames = map[string]Color{}/* 146 elements not displayed */

ColorNames holds the written names of colors. Useful to present a list of recognized named colors.

View Source
var ColorValues = map[Color]int32{}/* 379 elements not displayed */

ColorValues maps color constants to their RGB values.

View Source
var KeyNames = map[Key]string{}/* 118 elements not displayed */

KeyNames holds the written names of special keys. Useful to echo back a key name, or to look up a key from a string value.

View Source
var RuneFallbacks = map[rune]string{
	RuneSterling: "f",
	RuneDArrow:   "v",
	RuneLArrow:   "<",
	RuneRArrow:   ">",
	RuneUArrow:   "^",
	RuneBullet:   "o",
	RuneBoard:    "#",
	RuneCkBoard:  ":",
	RuneDegree:   "\\",
	RuneDiamond:  "+",
	RuneGEqual:   ">",
	RunePi:       "*",
	RuneHLine:    "-",
	RuneLantern:  "#",
	RunePlus:     "+",
	RuneLEqual:   "<",
	RuneLLCorner: "+",
	RuneLRCorner: "+",
	RuneNEqual:   "!",
	RunePlMinus:  "#",
	RuneS1:       "~",
	RuneS3:       "-",
	RuneS7:       "-",
	RuneS9:       "_",
	RuneBlock:    "#",
	RuneTTee:     "+",
	RuneRTee:     "+",
	RuneLTee:     "+",
	RuneBTee:     "+",
	RuneULCorner: "+",
	RuneURCorner: "+",
	RuneVLine:    "|",
}

RuneFallbacks is the default map of fallback strings that will be used to replace a rune when no other more appropriate transformation is available, and the rune cannot be displayed directly.

New entries may be added to this map over time, as it becomes clear that such is desirable. Characters that represent either letters or numbers should not be added to this list unless it is certain that the meaning will still convey unambiguously.

As an example, it would be appropriate to add an ASCII mapping for the full width form of the letter 'A', but it would not be appropriate to do so a glyph representing the country China.

Programs that desire richer fallbacks may register additional ones, or change or even remove these mappings with Screen.RegisterRuneFallback Screen.UnregisterRuneFallback methods.

Note that Unicode is presumed to be able to display all glyphs. This is a pretty poor assumption, but there is no easy way to figure out which glyphs are supported in a given font. Hence, some care in selecting the characters you support in your application is still appropriate.

Functions

func GetEncoding

func GetEncoding(charset string) encoding.Encoding

GetEncoding is used by Screen implementors who want to locate an encoding for the given character set name. Note that this will return nil for either the Unicode (UTF-8) or ASCII encodings, since we don't use encodings for them but instead have our own native methods.

func LookupTerminfo

func LookupTerminfo(name string) (ti *terminfo.Terminfo, e error)

LookupTerminfo attempts to find a definition for the named $TERM falling back to attempting to parse the output from infocmp.

func RegisterEncoding

func RegisterEncoding(charset string, enc encoding.Encoding)

RegisterEncoding may be called by the application to register an encoding. The presence of additional encodings will facilitate application usage with terminal environments where the I/O subsystem does not support Unicode.

Windows systems use Unicode natively, and do not need any of the encoding subsystem when using Windows Console screens.

Please see the Go documentation for golang.org/x/text/encoding -- most of the common ones exist already as stock variables. For example, ISO8859-15 can be registered using the following code:

import "golang.org/x/text/encoding/charmap"

  ...
  RegisterEncoding("ISO8859-15", charmap.ISO8859_15)

Aliases can be registered as well, for example "8859-15" could be an alias for "ISO8859-15".

For POSIX systems, the tcell package will check the environment variables LC_ALL, LC_CTYPE, and LANG (in that order) to determine the character set. These are expected to have the following pattern:

$language[.$codeset[@$variant]

We extract only the $codeset part, which will usually be something like UTF-8 or ISO8859-15 or KOI8-R. Note that if the locale is either "POSIX" or "C", then we assume US-ASCII (the POSIX 'portable character set' and assume all other characters are somehow invalid.)

Modern POSIX systems and terminal emulators may use UTF-8, and for those systems, this API is also unnecessary. For example, Darwin (MacOS X) and modern Linux running modern xterm generally will out of the box without any of this. Use of UTF-8 is recommended when possible, as it saves quite a lot processing overhead.

Note that some encodings are quite large (for example GB18030 which is a superset of Unicode) and so the application size can be expected ot increase quite a bit as each encoding is added. The East Asian encodings have been seen to add 100-200K per encoding to the application size.

func SetEncodingFallback

func SetEncodingFallback(fb EncodingFallback)

SetEncodingFallback changes the behavior of GetEncoding when a suitable encoding is not found. The default is EncodingFallbackFail, which causes GetEncoding to simply return nil.

Types

type AttrMask

type AttrMask int

AttrMask represents a mask of text attributes, apart from color. Note that support for attributes may vary widely across terminals.

const (
	AttrBold AttrMask = 1 << iota
	AttrBlink
	AttrReverse
	AttrUnderline
	AttrDim
	AttrItalic
	AttrStrikeThrough
	AttrInvalid              // Mark the style or attributes invalid
	AttrNone    AttrMask = 0 // Just normal text.
)

Attributes are not colors, but affect the display of text. They can be combined.

type ButtonMask

type ButtonMask int16

ButtonMask is a mask of mouse buttons and wheel events. Mouse button presses are normally delivered as both press and release events. Mouse wheel events are normally just single impulse events. Windows supports up to eight separate buttons plus all four wheel directions, but XTerm can only support mouse buttons 1-3 and wheel up/down. Its not unheard of for terminals to support only one or two buttons (think Macs). Old terminals, and true emulations (such as vt100) won't support mice at all, of course.

const (
	Button1 ButtonMask = 1 << iota // Usually the left (primary) mouse button.
	Button2                        // Usually the right (secondary) mouse button.
	Button3                        // Usually the middle mouse button.
	Button4                        // Often a side button (thumb/next).
	Button5                        // Often a side button (thumb/prev).
	Button6
	Button7
	Button8
	WheelUp                   // Wheel motion up/away from user.
	WheelDown                 // Wheel motion down/towards user.
	WheelLeft                 // Wheel motion to left.
	WheelRight                // Wheel motion to right.
	ButtonNone ButtonMask = 0 // No button or wheel events.

	ButtonPrimary   = Button1
	ButtonSecondary = Button2
	ButtonMiddle    = Button3
)

These are the actual button values. Note that tcell version 1.x reversed buttons two and three on *nix based terminals. We use button 1 as the primary, and button 2 as the secondary, and button 3 (which is often missing) as the middle.

type CellBuffer

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

CellBuffer represents a two dimensional array of character cells. This is primarily intended for use by Screen implementors; it contains much of the common code they need. To create one, just declare a variable of its type; no explicit initialization is necessary.

CellBuffer is not thread safe.

func (*CellBuffer) Dirty

func (cb *CellBuffer) Dirty(x, y int) bool

Dirty checks if a character at the given location needs an to be refreshed on the physical display. This returns true if the cell content is different since the last time it was marked clean.

func (*CellBuffer) Fill

func (cb *CellBuffer) Fill(r rune, style Style)

Fill fills the entire cell buffer array with the specified character and style. Normally choose ' ' to clear the screen. This API doesn't support combining characters, or characters with a width larger than one.

func (*CellBuffer) GetContent

func (cb *CellBuffer) GetContent(x, y int) (rune, []rune, Style, int)

GetContent returns the contents of a character cell, including the primary rune, any combining character runes (which will usually be nil), the style, and the display width in cells. (The width can be either 1, normally, or 2 for East Asian full-width characters.)

func (*CellBuffer) Invalidate

func (cb *CellBuffer) Invalidate()

Invalidate marks all characters within the buffer as dirty.

func (*CellBuffer) Resize

func (cb *CellBuffer) Resize(w, h int)

Resize is used to resize the cells array, with different dimensions, while preserving the original contents. The cells will be invalidated so that they can be redrawn.

func (*CellBuffer) SetContent

func (cb *CellBuffer) SetContent(x int, y int,
	mainc rune, combc []rune, style Style)

SetContent sets the contents (primary rune, combining runes, and style) for a cell at a given location.

func (*CellBuffer) SetDirty

func (cb *CellBuffer) SetDirty(x, y int, dirty bool)

SetDirty is normally used to indicate that a cell has been displayed (in which case dirty is false), or to manually force a cell to be marked dirty.

func (*CellBuffer) Size

func (cb *CellBuffer) Size() (int, int)

Size returns the (width, height) in cells of the buffer.

type Color

type Color uint64

Color represents a color. The low numeric values are the same as used by ECMA-48, and beyond that XTerm. A 24-bit RGB value may be used by adding in the ColorIsRGB flag. For Color names we use the W3C approved color names.

We use a 64-bit integer to allow future expansion if we want to add an 8-bit alpha, while still leaving us some room for extra options.

Note that on various terminals colors may be approximated however, or not supported at all. If no suitable representation for a color is known, the library will simply not set any color, deferring to whatever default attributes the terminal uses.

const (
	// ColorDefault is used to leave the Color unchanged from whatever
	// system or terminal default may exist.  It's also the zero value.
	ColorDefault Color = 0

	// ColorValid is used to indicate the color value is actually
	// valid (initialized).  This is useful to permit the zero value
	// to be treated as the default.
	ColorValid Color = 1 << 32

	// ColorIsRGB is used to indicate that the numeric value is not
	// a known color constant, but rather an RGB value.  The lower
	// order 3 bytes are RGB.
	ColorIsRGB Color = 1 << 33

	// ColorSpecial is a flag used to indicate that the values have
	// special meaning, and live outside of the color space(s).
	ColorSpecial Color = 1 << 34
)

func FindColor

func FindColor(c Color, palette []Color) Color

FindColor attempts to find a given color, or the best match possible for it, from the palette given. This is an expensive operation, so results should be cached by the caller.

func FromImageColor

func FromImageColor(imageColor ic.Color) Color

FromImageColor converts an image/color.Color into tcell.Color. The alpha value is dropped, so it should be tracked separately if it is needed.

func GetColor

func GetColor(name string) Color

GetColor creates a Color from a color name (W3C name). A hex value may be supplied as a string in the format "#ffffff".

func NewHexColor

func NewHexColor(v int32) Color

NewHexColor returns a color using the given 24-bit RGB value.

func NewRGBColor

func NewRGBColor(r, g, b int32) Color

NewRGBColor returns a new color with the given red, green, and blue values. Each value must be represented in the range 0-255.

func PaletteColor

func PaletteColor(index int) Color

PaletteColor creates a color based on the palette index.

func (Color) Hex

func (c Color) Hex() int32

Hex returns the color's hexadecimal RGB 24-bit value with each component consisting of a single byte, ala R << 16 | G << 8 | B. If the color is unknown or unset, -1 is returned.

func (Color) IsRGB

func (c Color) IsRGB() bool

IsRGB is true if the color is an RGB specific value.

func (Color) RGB

func (c Color) RGB() (int32, int32, int32)

RGB returns the red, green, and blue components of the color, with each component represented as a value 0-255. In the event that the color cannot be broken up (not set usually), -1 is returned for each value.

func (Color) TrueColor

func (c Color) TrueColor() Color

TrueColor returns the true color (RGB) version of the provided color. This is useful for ensuring color accuracy when using named colors. This will override terminal theme colors.

func (Color) Valid

func (c Color) Valid() bool

Valid indicates the color is a valid value (has been set).

type CursorStyle

type CursorStyle int

CursorStyle represents a given cursor style, which can include the shape and whether the cursor blinks or is solid. Support for changing this is not universal.

type EncodingFallback

type EncodingFallback int

EncodingFallback describes how the system behavees when the locale requires a character set that we do not support. The system always supports UTF-8 and US-ASCII. On Windows consoles, UTF-16LE is also supported automatically. Other character sets must be added using the RegisterEncoding API. (A large group of nearly all of them can be added using the RegisterAll function in the encoding sub package.)

type Event

type Event interface {
	// When reports the time when the event was generated.
	When() time.Time
}

Event is a generic interface used for passing around Events. Concrete types follow.

type EventError

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

An EventError is an event representing some sort of error, and carries an error payload.

func NewEventError

func NewEventError(err error) *EventError

NewEventError creates an ErrorEvent with the given error payload.

func (*EventError) Error

func (ev *EventError) Error() string

Error implements the error.

func (*EventError) When

func (ev *EventError) When() time.Time

When returns the time when the event was created.

type EventHandler

type EventHandler interface {
	HandleEvent(Event) bool
}

EventHandler is anything that handles events. If the handler has consumed the event, it should return true. False otherwise.

type EventInterrupt

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

EventInterrupt is a generic wakeup event. Its can be used to to request a redraw. It can carry an arbitrary payload, as well.

func NewEventInterrupt

func NewEventInterrupt(data interface{}) *EventInterrupt

NewEventInterrupt creates an EventInterrupt with the given payload.

func (*EventInterrupt) Data

func (ev *EventInterrupt) Data() interface{}

Data is used to obtain the opaque event payload.

func (*EventInterrupt) When

func (ev *EventInterrupt) When() time.Time

When returns the time when this event was created.

type EventKey

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

EventKey represents a key press. Usually this is a key press followed by a key release, but since terminal programs don't have a way to report key release events, we usually get just one event. If a key is held down then the terminal may synthesize repeated key presses at some predefined rate. We have no control over that, nor visibility into it.

In some cases, we can have a modifier key, such as ModAlt, that can be generated with a key press. (This usually is represented by having the high bit set, or in some cases, by sending an ESC prior to the rune.)

If the value of Key() is KeyRune, then the actual key value will be available with the Rune() method. This will be the case for most keys. In most situations, the modifiers will not be set. For example, if the rune is 'A', this will be reported without the ModShift bit set, since really can't tell if the Shift key was pressed (it might have been CAPSLOCK, or a terminal that only can send capitals, or keyboard with separate capital letters from lower case letters).

Generally, terminal applications have far less visibility into keyboard activity than graphical applications. Hence, they should avoid depending overly much on availability of modifiers, or the availability of any specific keys.

func NewEventKey

func NewEventKey(k Key, ch rune, mod ModMask) *EventKey

NewEventKey attempts to create a suitable event. It parses the various ASCII control sequences if KeyRune is passed for Key, but if the caller has more precise information it should set that specifically. Callers that aren't sure about modifier state (most) should just pass ModNone.

func (*EventKey) Key

func (ev *EventKey) Key() Key

Key returns a virtual key code. We use this to identify specific key codes, such as KeyEnter, etc. Most control and function keys are reported with unique Key values. Normal alphanumeric and punctuation keys will generally return KeyRune here; the specific key can be further decoded using the Rune() function.

func (*EventKey) Modifiers

func (ev *EventKey) Modifiers() ModMask

Modifiers returns the modifiers that were present with the key press. Note that not all platforms and terminals support this equally well, and some cases we will not not know for sure. Hence, applications should avoid using this in most circumstances.

func (*EventKey) Name

func (ev *EventKey) Name() string

Name returns a printable value or the key stroke. This can be used when printing the event, for example.

func (*EventKey) Rune

func (ev *EventKey) Rune() rune

Rune returns the rune corresponding to the key press, if it makes sense. The result is only defined if the value of Key() is KeyRune.

func (*EventKey) When

func (ev *EventKey) When() time.Time

When returns the time when this Event was created, which should closely match the time when the key was pressed.

type EventMouse

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

EventMouse is a mouse event. It is sent on either mouse up or mouse down events. It is also sent on mouse motion events - if the terminal supports it. We make every effort to ensure that mouse release events are delivered. Hence, click drag can be identified by a motion event with the mouse down, without any intervening button release. On some terminals only the initiating press and terminating release event will be delivered.

Mouse wheel events, when reported, may appear on their own as individual impulses; that is, there will normally not be a release event delivered for mouse wheel movements.

Most terminals cannot report the state of more than one button at a time -- and some cannot report motion events unless a button is pressed.

Applications can inspect the time between events to resolve double or triple clicks.

func NewEventMouse

func NewEventMouse(x, y int, btn ButtonMask, mod ModMask) *EventMouse

NewEventMouse is used to create a new mouse event. Applications shouldn't need to use this; its mostly for screen implementors.

func (*EventMouse) Buttons

func (ev *EventMouse) Buttons() ButtonMask

Buttons returns the list of buttons that were pressed or wheel motions.

func (*EventMouse) Modifiers

func (ev *EventMouse) Modifiers() ModMask

Modifiers returns a list of keyboard modifiers that were pressed with the mouse button(s).

func (*EventMouse) Position

func (ev *EventMouse) Position() (int, int)

Position returns the mouse position in character cells. The origin 0, 0 is at the upper left corner.

func (*EventMouse) When

func (ev *EventMouse) When() time.Time

When returns the time when this EventMouse was created.

type EventPaste

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

EventPaste is used to mark the start and end of a bracketed paste. An event with .Start() true will be sent to mark the start. Then a number of keys will be sent to indicate that the content is pasted in. At the end, an event with .Start() false will be sent.

func NewEventPaste

func NewEventPaste(start bool) *EventPaste

NewEventPaste returns a new EventPaste.

func (*EventPaste) End

func (ev *EventPaste) End() bool

End returns true if this is the end of a paste.

func (*EventPaste) Start

func (ev *EventPaste) Start() bool

Start returns true if this is the start of a paste.

func (*EventPaste) When

func (ev *EventPaste) When() time.Time

When returns the time when this EventPaste was created.

type EventResize

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

EventResize is sent when the window size changes.

func NewEventResize

func NewEventResize(width, height int) *EventResize

NewEventResize creates an EventResize with the new updated window size, which is given in character cells.

func (*EventResize) Size

func (ev *EventResize) Size() (int, int)

Size returns the new window size as width, height in character cells.

func (*EventResize) When

func (ev *EventResize) When() time.Time

When returns the time when the Event was created.

type EventTime

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

EventTime is a simple base event class, suitable for easy reuse. It can be used to deliver actual timer events as well.

func (*EventTime) SetEventNow

func (e *EventTime) SetEventNow()

SetEventNow sets the time of occurrence for the event to the current time.

func (*EventTime) SetEventTime

func (e *EventTime) SetEventTime(t time.Time)

SetEventTime sets the time of occurrence for the event.

func (*EventTime) When

func (e *EventTime) When() time.Time

When returns the time stamp when the event occurred.

type Key

type Key int16

Key is a generic value for representing keys, and especially special keys (function keys, cursor movement keys, etc.) For normal keys, like ASCII letters, we use KeyRune, and then expect the application to inspect the Rune() member of the EventKey.

const (
	KeyRune Key = iota + 256
	KeyUp
	KeyDown
	KeyRight
	KeyLeft
	KeyUpLeft
	KeyUpRight
	KeyDownLeft
	KeyDownRight
	KeyCenter
	KeyPgUp
	KeyPgDn
	KeyHome
	KeyEnd
	KeyInsert
	KeyDelete
	KeyHelp
	KeyExit
	KeyClear
	KeyCancel
	KeyPrint
	KeyPause
	KeyBacktab
	KeyF1
	KeyF2
	KeyF3
	KeyF4
	KeyF5
	KeyF6
	KeyF7
	KeyF8
	KeyF9
	KeyF10
	KeyF11
	KeyF12
	KeyF13
	KeyF14
	KeyF15
	KeyF16
	KeyF17
	KeyF18
	KeyF19
	KeyF20
	KeyF21
	KeyF22
	KeyF23
	KeyF24
	KeyF25
	KeyF26
	KeyF27
	KeyF28
	KeyF29
	KeyF30
	KeyF31
	KeyF32
	KeyF33
	KeyF34
	KeyF35
	KeyF36
	KeyF37
	KeyF38
	KeyF39
	KeyF40
	KeyF41
	KeyF42
	KeyF43
	KeyF44
	KeyF45
	KeyF46
	KeyF47
	KeyF48
	KeyF49
	KeyF50
	KeyF51
	KeyF52
	KeyF53
	KeyF54
	KeyF55
	KeyF56
	KeyF57
	KeyF58
	KeyF59
	KeyF60
	KeyF61
	KeyF62
	KeyF63
	KeyF64
)

This is the list of named keys. KeyRune is special however, in that it is a place holder key indicating that a printable character was sent. The actual value of the rune will be transported in the Rune of the associated EventKey.

const (
	KeyCtrlSpace Key = iota
	KeyCtrlA
	KeyCtrlB
	KeyCtrlC
	KeyCtrlD
	KeyCtrlE
	KeyCtrlF
	KeyCtrlG
	KeyCtrlH
	KeyCtrlI
	KeyCtrlJ
	KeyCtrlK
	KeyCtrlL
	KeyCtrlM
	KeyCtrlN
	KeyCtrlO
	KeyCtrlP
	KeyCtrlQ
	KeyCtrlR
	KeyCtrlS
	KeyCtrlT
	KeyCtrlU
	KeyCtrlV
	KeyCtrlW
	KeyCtrlX
	KeyCtrlY
	KeyCtrlZ
	KeyCtrlLeftSq // Escape
	KeyCtrlBackslash
	KeyCtrlRightSq
	KeyCtrlCarat
	KeyCtrlUnderscore
)

These are the control keys. Note that they overlap with other keys, perhaps. For example, KeyCtrlH is the same as KeyBackspace.

const (
	KeyNUL Key = iota
	KeySOH
	KeySTX
	KeyETX
	KeyEOT
	KeyENQ
	KeyACK
	KeyBEL
	KeyBS
	KeyTAB
	KeyLF
	KeyVT
	KeyFF
	KeyCR
	KeySO
	KeySI
	KeyDLE
	KeyDC1
	KeyDC2
	KeyDC3
	KeyDC4
	KeyNAK
	KeySYN
	KeyETB
	KeyCAN
	KeyEM
	KeySUB
	KeyESC
	KeyFS
	KeyGS
	KeyRS
	KeyUS
	KeyDEL Key = 0x7F
)

These are the defined ASCII values for key codes. They generally match with KeyCtrl values.

type ModMask

type ModMask int16

ModMask is a mask of modifier keys. Note that it will not always be possible to report modifier keys.

const (
	ModShift ModMask = 1 << iota
	ModCtrl
	ModAlt
	ModMeta
	ModNone ModMask = 0
)

These are the modifiers keys that can be sent either with a key press, or a mouse event. Note that as of now, due to the confusion associated with Meta, and the lack of support for it on many/most platforms, the current implementations never use it. Instead, they use ModAlt, even for events that could possibly have been distinguished from ModAlt.

type MouseFlags

type MouseFlags int

MouseFlags are options to modify the handling of mouse events. Actual events can be ORed together.

type Screen

type Screen interface {
	// Init initializes the screen for use.
	Init() error

	// Fini finalizes the screen also releasing resources.
	Fini()

	// Clear erases the screen.  The contents of any screen buffers
	// will also be cleared.  This has the logical effect of
	// filling the screen with spaces, using the global default style.
	Clear()

	// Fill fills the screen with the given character and style.
	Fill(rune, Style)

	// SetCell is an older API, and will be removed.  Please use
	// SetContent instead; SetCell is implemented in terms of SetContent.
	SetCell(x int, y int, style Style, ch ...rune)

	// GetContent returns the contents at the given location.  If the
	// coordinates are out of range, then the values will be 0, nil,
	// StyleDefault.  Note that the contents returned are logical contents
	// and may not actually be what is displayed, but rather are what will
	// be displayed if Show() or Sync() is called.  The width is the width
	// in screen cells; most often this will be 1, but some East Asian
	// characters require two cells.
	GetContent(x, y int) (primary rune, combining []rune, style Style, width int)

	// SetContent sets the contents of the given cell location.  If
	// the coordinates are out of range, then the operation is ignored.
	//
	// The first rune is the primary non-zero width rune.  The array
	// that follows is a possible list of combining characters to append,
	// and will usually be nil (no combining characters.)
	//
	// The results are not displayed until Show() or Sync() is called.
	//
	// Note that wide (East Asian full width) runes occupy two cells,
	// and attempts to place character at next cell to the right will have
	// undefined effects.  Wide runes that are printed in the
	// last column will be replaced with a single width space on output.
	SetContent(x int, y int, primary rune, combining []rune, style Style)

	// SetStyle sets the default style to use when clearing the screen
	// or when StyleDefault is specified.  If it is also StyleDefault,
	// then whatever system/terminal default is relevant will be used.
	SetStyle(style Style)

	// ShowCursor is used to display the cursor at a given location.
	// If the coordinates -1, -1 are given or are otherwise outside the
	// dimensions of the screen, the cursor will be hidden.
	ShowCursor(x int, y int)

	// HideCursor is used to hide the cursor.  It's an alias for
	// ShowCursor(-1, -1).sim
	HideCursor()

	// SetCursorStyle is used to set the cursor style.  If the style
	// is not supported (or cursor styles are not supported at all),
	// then this will have no effect.
	SetCursorStyle(CursorStyle)

	// Size returns the screen size as width, height.  This changes in
	// response to a call to Clear or Flush.
	Size() (width, height int)

	// ChannelEvents is an infinite loop that waits for an event and
	// channels it into the user provided channel ch.  Closing the
	// quit channel and calling the Fini method are cancellation
	// signals.  When a cancellation signal is received the method
	// returns after closing ch.
	//
	// This method should be used as a goroutine.
	//
	// NOTE: PollEvent should not be called while this method is running.
	ChannelEvents(ch chan<- Event, quit <-chan struct{})

	// PollEvent waits for events to arrive.  Main application loops
	// must spin on this to prevent the application from stalling.
	// Furthermore, this will return nil if the Screen is finalized.
	PollEvent() Event

	// HasPendingEvent returns true if PollEvent would return an event
	// without blocking.  If the screen is stopped and PollEvent would
	// return nil, then the return value from this function is unspecified.
	// The purpose of this function is to allow multiple events to be collected
	// at once, to minimize screen redraws.
	HasPendingEvent() bool

	// PostEvent tries to post an event into the event stream.  This
	// can fail if the event queue is full.  In that case, the event
	// is dropped, and ErrEventQFull is returned.
	PostEvent(ev Event) error

	// Deprecated: PostEventWait is unsafe, and will be removed
	// in the future.
	//
	// PostEventWait is like PostEvent, but if the queue is full, it
	// blocks until there is space in the queue, making delivery
	// reliable.  However, it is VERY important that this function
	// never be called from within whatever event loop is polling
	// with PollEvent(), otherwise a deadlock may arise.
	//
	// For this reason, when using this function, the use of a
	// Goroutine is recommended to ensure no deadlock can occur.
	PostEventWait(ev Event)

	// EnableMouse enables the mouse.  (If your terminal supports it.)
	// If no flags are specified, then all events are reported, if the
	// terminal supports them.
	EnableMouse(...MouseFlags)

	// DisableMouse disables the mouse.
	DisableMouse()

	// EnablePaste enables bracketed paste mode, if supported.
	EnablePaste()

	// DisablePaste disables bracketed paste mode.
	DisablePaste()

	// HasMouse returns true if the terminal (apparently) supports a
	// mouse.  Note that the return value of true doesn't guarantee that
	// a mouse/pointing device is present; a false return definitely
	// indicates no mouse support is available.
	HasMouse() bool

	// Colors returns the number of colors.  All colors are assumed to
	// use the ANSI color map.  If a terminal is monochrome, it will
	// return 0.
	Colors() int

	// Show makes all the content changes made using SetContent() visible
	// on the display.
	//
	// It does so in the most efficient and least visually disruptive
	// manner possible.
	Show()

	// Sync works like Show(), but it updates every visible cell on the
	// physical display, assuming that it is not synchronized with any
	// internal model.  This may be both expensive and visually jarring,
	// so it should only be used when believed to actually be necessary.
	//
	// Typically, this is called as a result of a user-requested redraw
	// (e.g. to clear up on-screen corruption caused by some other program),
	// or during a resize event.
	Sync()

	// CharacterSet returns information about the character set.
	// This isn't the full locale, but it does give us the input/output
	// character set.  Note that this is just for diagnostic purposes,
	// we normally translate input/output to/from UTF-8, regardless of
	// what the user's environment is.
	CharacterSet() string

	// RegisterRuneFallback adds a fallback for runes that are not
	// part of the character set -- for example one could register
	// o as a fallback for ø.  This should be done cautiously for
	// characters that might be displayed ordinarily in language
	// specific text -- characters that could change the meaning of
	// written text would be dangerous.  The intention here is to
	// facilitate fallback characters in pseudo-graphical applications.
	//
	// If the terminal has fallbacks already in place via an alternate
	// character set, those are used in preference.  Also, standard
	// fallbacks for graphical characters in the alternate character set
	// terminfo string are registered implicitly.
	//
	// The display string should be the same width as original rune.
	// This makes it possible to register two character replacements
	// for full width East Asian characters, for example.
	//
	// It is recommended that replacement strings consist only of
	// 7-bit ASCII, since other characters may not display everywhere.
	RegisterRuneFallback(r rune, subst string)

	// UnregisterRuneFallback unmaps a replacement.  It will unmap
	// the implicit ASCII replacements for alternate characters as well.
	// When an unmapped char needs to be displayed, but no suitable
	// glyph is available, '?' is emitted instead.  It is not possible
	// to "disable" the use of alternate characters that are supported
	// by your terminal except by changing the terminal database.
	UnregisterRuneFallback(r rune)

	// CanDisplay returns true if the given rune can be displayed on
	// this screen.  Note that this is a best-guess effort -- whether
	// your fonts support the character or not may be questionable.
	// Mostly this is for folks who work outside of Unicode.
	//
	// If checkFallbacks is true, then if any (possibly imperfect)
	// fallbacks are registered, this will return true.  This will
	// also return true if the terminal can replace the glyph with
	// one that is visually indistinguishable from the one requested.
	CanDisplay(r rune, checkFallbacks bool) bool

	// Resize does nothing, since it's generally not possible to
	// ask a screen to resize, but it allows the Screen to implement
	// the View interface.
	Resize(int, int, int, int)

	// HasKey returns true if the keyboard is believed to have the
	// key.  In some cases a keyboard may have keys with this name
	// but no support for them, while in others a key may be reported
	// as supported but not actually be usable (such as some emulators
	// that hijack certain keys).  Its best not to depend to strictly
	// on this function, but it can be used for hinting when building
	// menus, displayed hot-keys, etc.  Note that KeyRune (literal
	// runes) is always true.
	HasKey(Key) bool

	// Suspend pauses input and output processing.  It also restores the
	// terminal settings to what they were when the application started.
	// This can be used to, for example, run a sub-shell.
	Suspend() error

	// Resume resumes after Suspend().
	Resume() error

	// Beep attempts to sound an OS-dependent audible alert and returns an error
	// when unsuccessful.
	Beep() error

	// SetSize attempts to resize the window.  It also invalidates the cells and
	// calls the resize function.  Note that if the window size is changed, it will
	// not be restored upon application exit.
	//
	// Many terminals cannot support this.  Perversely, the "modern" Windows Terminal
	// does not support application-initiated resizing, whereas the legacy terminal does.
	// Also, some emulators can support this but may have it disabled by default.
	SetSize(int, int)
}

Screen represents the physical (or emulated) screen. This can be a terminal window or a physical console. Platforms implement this differently.

func NewConsoleScreen

func NewConsoleScreen() (Screen, error)

NewConsoleScreen returns a console based screen. This platform doesn't have support for any, so it returns nil and a suitable error.

func NewScreen

func NewScreen() (Screen, error)

NewScreen returns a default Screen suitable for the user's terminal environment.

func NewTerminfoScreen

func NewTerminfoScreen() (Screen, error)

NewTerminfoScreen returns a Screen that uses the stock TTY interface and POSIX terminal control, combined with a terminfo description taken from the $TERM environment variable. It returns an error if the terminal is not supported for any reason.

For terminals that do not support dynamic resize events, the $LINES $COLUMNS environment variables can be set to the actual window size, otherwise defaults taken from the terminal database are used.

func NewTerminfoScreenFromTty

func NewTerminfoScreenFromTty(tty Tty) (Screen, error)

NewTerminfoScreenFromTty returns a Screen using a custom Tty implementation. If the passed in tty is nil, then a reasonable default (typically /dev/tty) is presumed, at least on UNIX hosts. (Windows hosts will typically fail this call altogether.)

func NewTerminfoScreenFromTtyTerminfo

func NewTerminfoScreenFromTtyTerminfo(tty Tty, ti *terminfo.Terminfo) (s Screen, e error)

NewTerminfoScreenFromTtyTerminfo returns a Screen using a custom Tty implementation and custom terminfo specification. If the passed in tty is nil, then a reasonable default (typically /dev/tty) is presumed, at least on UNIX hosts. (Windows hosts will typically fail this call altogether.) If passed terminfo is nil, then TERM environment variable is queried for terminal specification.

type SimCell

type SimCell struct {
	// Bytes is the actual character bytes.  Normally this is
	// rune data, but it could be be data in another encoding system.
	Bytes []byte

	// Style is the style used to display the data.
	Style Style

	// Runes is the list of runes, unadulterated, in UTF-8.
	Runes []rune
}

SimCell represents a simulated screen cell. The purpose of this is to track on screen content.

type SimulationScreen

type SimulationScreen interface {
	// InjectKeyBytes injects a stream of bytes corresponding to
	// the native encoding (see charset).  It turns true if the entire
	// set of bytes were processed and delivered as KeyEvents, false
	// if any bytes were not fully understood.  Any bytes that are not
	// fully converted are discarded.
	InjectKeyBytes(buf []byte) bool

	// InjectKey injects a key event.  The rune is a UTF-8 rune, post
	// any translation.
	InjectKey(key Key, r rune, mod ModMask)

	// InjectMouse injects a mouse event.
	InjectMouse(x, y int, buttons ButtonMask, mod ModMask)

	// GetContents returns screen contents as an array of
	// cells, along with the physical width & height.   Note that the
	// physical contents will be used until the next time SetSize()
	// is called.
	GetContents() (cells []SimCell, width int, height int)

	// GetCursor returns the cursor details.
	GetCursor() (x int, y int, visible bool)

	Screen
}

SimulationScreen represents a screen simulation. This is intended to be a superset of normal Screens, but also adds some important interfaces for testing.

func NewSimulationScreen

func NewSimulationScreen(charset string) SimulationScreen

NewSimulationScreen returns a SimulationScreen. Note that SimulationScreen is also a Screen.

type Style

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

Style represents a complete text style, including both foreground color, background color, and additional attributes such as "bold" or "underline".

Note that not all terminals can display all colors or attributes, and many might have specific incompatibilities between specific attributes and color combinations.

To use Style, just declare a variable of its type.

var StyleDefault Style

StyleDefault represents a default style, based upon the context. It is the zero value.

func (Style) Attributes

func (s Style) Attributes(attrs AttrMask) Style

Attributes returns a new style based on s, with its attributes set as specified.

func (Style) Background

func (s Style) Background(c Color) Style

Background returns a new style based on s, with the background color set as requested. ColorDefault can be used to select the global default.

func (s Style) Blink(on bool) Style

Blink returns a new style based on s, with the blink attribute set as requested.

func (Style) Bold

func (s Style) Bold(on bool) Style

Bold returns a new style based on s, with the bold attribute set as requested.

func (Style) Decompose

func (s Style) Decompose() (fg Color, bg Color, attr AttrMask)

Decompose breaks a style up, returning the foreground, background, and other attributes. The URL if set is not included.

func (Style) Dim

func (s Style) Dim(on bool) Style

Dim returns a new style based on s, with the dim attribute set as requested.

func (Style) Foreground

func (s Style) Foreground(c Color) Style

Foreground returns a new style based on s, with the foreground color set as requested. ColorDefault can be used to select the global default.

func (Style) Italic

func (s Style) Italic(on bool) Style

Italic returns a new style based on s, with the italic attribute set as requested.

func (Style) Normal

func (s Style) Normal() Style

Normal returns the style with all attributes disabled.

func (Style) Reverse

func (s Style) Reverse(on bool) Style

Reverse returns a new style based on s, with the reverse attribute set as requested. (Reverse usually changes the foreground and background colors.)

func (Style) StrikeThrough

func (s Style) StrikeThrough(on bool) Style

StrikeThrough sets strikethrough mode.

func (Style) Underline

func (s Style) Underline(on bool) Style

Underline returns a new style based on s, with the underline attribute set as requested.

func (Style) Url

func (s Style) Url(url string) Style

Url returns a style with the Url set. If the provided Url is not empty, and the terminal supports it, text will typically be marked up as a clickable link to that Url. If the Url is empty, then this mode is turned off.

type Tty

type Tty interface {
	// Start is used to activate the Tty for use.  Upon return the terminal should be
	// in raw mode, non-blocking, etc.  The implementation should take care of saving
	// any state that is required so that it may be restored when Stop is called.
	Start() error

	// Stop is used to stop using this Tty instance.  This may be a suspend, so that other
	// terminal based applications can run in the foreground.  Implementations should
	// restore any state collected at Start(), and return to ordinary blocking mode, etc.
	// Drain is called first to drain the input.  Once this is called, no more Read
	// or Write calls will be made until Start is called again.
	Stop() error

	// Drain is called before Stop, and ensures that the reader will wake up appropriately
	// if it was blocked.  This workaround is required for /dev/tty on certain UNIX systems
	// to ensure that Read() does not block forever.  This typically arranges for the tty driver
	// to send data immediately (e.g. VMIN and VTIME both set zero) and sets a deadline on input.
	// Implementations may reasonably make this a no-op.  There will still be control sequences
	// emitted between the time this is called, and when Stop is called.
	Drain() error

	// NotifyResize is used register a callback when the tty thinks the dimensions have
	// changed.  The standard UNIX implementation links this to a handler for SIGWINCH.
	// If the supplied callback is nil, then any handler should be unregistered.
	NotifyResize(cb func())

	// WindowSize is called to determine the terminal dimensions.  This might be determined
	// by an ioctl or other means.
	WindowSize() (width int, height int, err error)

	io.ReadWriteCloser
}

Tty is an abstraction of a tty (traditionally "teletype"). This allows applications to provide for alternate backends, as there are situations where the traditional /dev/tty does not work, or where more flexible handling is required. This interface is for use with the terminfo-style based API. It extends the io.ReadWriter API. It is reasonable that the implementation might choose to use different underlying files for the Reader and Writer sides of this API, as part of it's internal implementation.

func NewDevTty

func NewDevTty() (Tty, error)

NewDevTty opens a /dev/tty based Tty.

func NewDevTtyFromDev

func NewDevTtyFromDev(dev string) (Tty, error)

NewDevTtyFromDev opens a tty device given a path. This can be useful to bind to other nodes.

func NewStdIoTty

func NewStdIoTty() (Tty, error)

NewStdioTty opens a tty using standard input/output.

Directories

Path Synopsis
Package termbox is a compatibility layer to allow tcell to emulate the github.com/nsf/termbox package.
Package termbox is a compatibility layer to allow tcell to emulate the github.com/nsf/termbox package.
base
Package base contains the base terminal descriptions that are likely to be needed by any stock application.
Package base contains the base terminal descriptions that are likely to be needed by any stock application.
extended
Package extended contains an extended set of terminal descriptions.
Package extended contains an extended set of terminal descriptions.

Jump to

Keyboard shortcuts

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