Documentation ¶
Overview ¶
Package transform provides reader and writer wrappers that transform the bytes passing through as well as various transformations. Example transformations provided by other packages include normalization and conversion between character sets.
Index ¶
- Constants
- Variables
- func AddTerminfo(t *Terminfo)
- func Append(t Transformer, dst, src []byte) (result []byte, n int, err error)
- func Bytes(t Transformer, b []byte) (result []byte, n int, err error)
- func String(t Transformer, s string) (result string, n int, err error)
- type AttrMask
- type CellBuffer
- func (cb *CellBuffer) Dirty(x, y int) bool
- func (cb *CellBuffer) Fill(r rune, style Style)
- func (cb *CellBuffer) GetContent(x, y int) (rune, []rune, Style, int)
- func (cb *CellBuffer) Invalidate()
- func (cb *CellBuffer) Resize(w, h int)
- func (cb *CellBuffer) SetContent(x int, y int, mainc rune, combc []rune, style Style)
- func (cb *CellBuffer) SetDirty(x, y int, dirty bool)
- func (cb *CellBuffer) Size() (int, int)
- type Decoder
- type Encoder
- type Encoding
- type Event
- type EventError
- type EventHandler
- type EventInterrupt
- type EventKey
- type EventPaste
- type EventResize
- type EventTime
- type Key
- type ModMask
- type NopResetter
- type Reader
- type Screen
- type SpanningTransformer
- type Style
- type Terminfo
- type Transformer
- type Writer
Constants ¶
const ( KeyBackspace = KeyBS KeyTab = KeyTAB KeyEsc = KeyESC KeyEscape = KeyESC KeyEnter = KeyCR KeyBackspace2 = KeyDEL )
These keys are aliases for other names.
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.
Variables ¶
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 = errors.New("terminal entry not found") // 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") )
var ( // ErrShortDst means that the destination buffer was too short to // receive all of the transformed bytes. ErrShortDst = errors.New("transform: short destination buffer") // ErrShortSrc means that the source buffer has insufficient data to // complete the transformation. ErrShortSrc = errors.New("transform: short source buffer") // ErrEndOfSpan means that the input and output (the transformed input) // are not identical. ErrEndOfSpan = errors.New("transform: input and output are not identical") // ErrInvalidUTF8 means that a transformer encountered invalid UTF-8. ErrInvalidUTF8 = errors.New("encoding: invalid UTF-8") //UTF8Validator is a transformer that returns ErrInvalidUTF8 on the first UTF8Validator Transformer = utf8Validator{} )
var ( // Discard is a Transformer for which all Transform calls succeed // by consuming all bytes and writing nothing. Discard Transformer = discard{} // Nop is a SpanningTransformer that copies src to dst. Nop SpanningTransformer = nop{} )
var KeyNames = map[Key]string{}/* 140 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.
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 AddTerminfo ¶
func AddTerminfo(t *Terminfo)
AddTerminfo can be called to register a new Terminfo entry.
func Append ¶
func Append(t Transformer, dst, src []byte) (result []byte, n int, err error)
Append appends the result of converting src[:n] using t to dst, where n <= len(src), If err == nil, n will be len(src). It calls Reset on t.
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.
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.
func (*CellBuffer) GetContent ¶
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 ¶
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 Decoder ¶
type Decoder struct { Transformer // contains filtered or unexported fields }
A Decoder converts bytes to UTF-8. It implements transform.Transformer.
Transforming source bytes that are not of that encoding will not result in an error per se. Each byte that cannot be transcoded will be represented in the output by the UTF-8 encoding of '\uFFFD', the replacement rune.
func (*Decoder) Bytes ¶
Bytes converts the given encoded bytes to UTF-8. It returns the converted bytes or nil, err if any error occurred.
type Encoder ¶
type Encoder struct { Transformer // contains filtered or unexported fields }
An Encoder converts bytes from UTF-8. It implements transform.Transformer.
Each rune that cannot be transcoded will result in an error. In this case, the transform will consume all source byte up to, not including the offending rune. Transforming source bytes that are not valid UTF-8 will be replaced by `\uFFFD`. To return early with an error instead, use transform.Chain to preprocess the data with a UTF8Validator.
func (*Encoder) Bytes ¶
Bytes converts bytes from UTF-8. It returns the converted bytes or nil, err if any error occurred.
type Encoding ¶
type Encoding interface { // NewDecoder returns a Decoder. NewDecoder() *Decoder // NewEncoder returns an Encoder. NewEncoder() *Encoder }
var Nop_ Encoding = nop_{}
Nop is the nop encoding. Its transformed bytes are the same as the source bytes; it does not replace invalid UTF-8 sequences.
var UTF8 Encoding = validUtf8{}
UTF8 is an encoding for UTF-8. All it does is verify that the UTF-8 in is valid. The main reason for its existence is that it will detect and report ErrSrcShort or ErrDstShort, whereas the Nop encoding just passes every byte, blithely.
func GetEncoding ¶
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) When ¶
func (ev *EventError) When() time.Time
When returns the time when the event was created.
type EventHandler ¶
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 ¶
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 ¶
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 ¶
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 ¶
Name returns a printable value or the key stroke. This can be used when printing the event, for example.
type EventPaste ¶
type EventPaste struct {
// contains filtered or unexported fields
}
EventPaste represents a bracketed paste event.
func NewEventPaste ¶
func NewEventPaste(text string) *EventPaste
NewEventPaste creates a new paste event from the given text
func (*EventPaste) When ¶
func (e *EventPaste) When() time.Time
When returns the time when this Event was created, which should closely match the time when the paste was made.
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 ¶
SetEventTime sets the time of occurrence for the event.
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 KeyAltUp KeyAltDown KeyAltLeft KeyAltRight KeyCtrlUp KeyCtrlDown KeyCtrlLeft KeyCtrlRight KeyShiftUp KeyShiftDown KeyShiftLeft KeyShiftRight KeyAltShiftUp KeyAltShiftDown KeyAltShiftLeft KeyAltShiftRight KeyCtrlShiftUp KeyCtrlShiftDown KeyCtrlShiftLeft KeyCtrlShiftRight KeyCenter KeyPgUp KeyPgDn KeyCtrlPgUp KeyCtrlPgDn 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.
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 NopResetter ¶
type NopResetter struct{}
NopResetter can be embedded by implementations of Transformer to add a nop Reset method.
func (NopResetter) Reset ¶
func (NopResetter) Reset()
Reset implements the Reset method of the Transformer interface.
type Reader ¶
type Reader struct {
// contains filtered or unexported fields
}
Reader wraps another io.Reader by transforming the bytes read.
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) (mainc rune, combc []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 displayd 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, mainc rune, combc []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. Its an alias for // ShowCursor(-1, -1). HideCursor() // Size returns the screen size as width, height. This changes in // response to a call to Clear or Flush. Size() (int, int) // 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 // 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 // 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) // 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 // 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 its 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 SetTitle(string) }
Screen represents the physical (or emulated) screen. This can be a terminal window or a physical console. Platforms implement this differerently.
func NewConsoleScreen ¶
NewConsoleScreen returns a console based screen. This platform doesn't have support for any, so it returns nil and a suitable error.
func NewTerminfoScreen ¶
NewTerminfoScreen returns a Screen that uses the stock TTY interface and POSIX termios, 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.
type SpanningTransformer ¶
type SpanningTransformer interface { Transformer // Span returns a position in src such that transforming src[:n] results in // identical output src[:n] for these bytes. It does not necessarily return // the largest such n. The atEOF argument tells whether src represents the // last bytes of the input. // // Callers should always account for the n bytes consumed before // considering the error err. // // A nil error means that all input bytes are known to be identical to the // output produced by the Transformer. A nil error can be be returned // regardless of whether atEOF is true. If err is nil, then then n must // equal len(src); the converse is not necessarily true. // // ErrEndOfSpan means that the Transformer output may differ from the // input after n bytes. Note that n may be len(src), meaning that the output // would contain additional bytes after otherwise identical output. // ErrShortSrc means that src had insufficient data to determine whether the // remaining bytes would change. Other than the error conditions listed // here, implementations are free to report other errors that arise. // // Calling Span can modify the Transformer state as a side effect. In // effect, it does the transformation just as calling Transform would, only // without copying to a destination buffer and only up to a point it can // determine the input and output bytes are the same. This is obviously more // limited than calling Transform, but can be more efficient in terms of // copying and allocating buffers. Calls to Span and Transform may be // interleaved. Span(src []byte, atEOF bool) (n int, err error) }
SpanningTransformer extends the Transformer interface with a Span method that determines how much of the input already conforms to the Transformer.
type Style ¶
type Style int64
Style represents a complete text style, including both foreground and background color. We encode it in a 64-bit int for efficiency. The coding is (MSB): <7b flags><1b><24b fgcolor><7b attr><1b><24b bgcolor>. The <1b> is set true to indicate that the color is an RGB color, rather than a named index.
This gives 24bit color options, if it ever becomes truly necessary. However, applications must not rely on this encoding.
Note that not all terminals can display all colors or attributes, and many might have specific incompatibilities between specific attributes and color combinations.
The intention is to extend styles to support paletting, in which case some flag bit(s) would be set, and the foreground and background colors would be replaced with a palette number and palette index.
To use Style, just declare a variable of its type.
const StyleDefault Style = 0
StyleDefault represents a default style, based upon the context. It is the zero value.
func (Style) Blink ¶
Blink returns a new style based on s, with the blink attribute set as requested.
func (Style) Decompose ¶
// styleFlags -- used internally for now. const (
styleBgSet = 1 << (iota + 57) styleFgSet stylePalette
)
// 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 (s Style) Foreground(c Color) Style { if c == ColorDefault { return (s &^ (0x1ffffff00000000 | styleFgSet)) } return (s &^ Style(0x1ffffff00000000)) | ((Style(c) & 0x1ffffff) << 32) | styleFgSet }
// 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) Background(c Color) Style { if c == ColorDefault { return (s &^ (0x1ffffff | styleBgSet)) } return (s &^ (0x1ffffff)) | (Style(c) & 0x1ffffff) | styleBgSet }
Decompose breaks a style up, returning the foreground, background, and other attributes.
type Terminfo ¶
type Terminfo struct { Name string `json:"name"` Aliases []string `json:"aliases,omitempty"` Columns int `json:"cols,omitempty"` // cols Lines int `json:"lines,omitempty"` // lines Colors int `json:"colors,omitempty"` // colors Bell string `json:"bell,omitempty"` // bell Clear string `json:"clear,omitempty"` // clear EnterCA string `json:"smcup,omitempty"` // smcup ExitCA string `json:"rmcup,omitempty"` // rmcup ShowCursor string `json:"cnorm,omitempty"` // cnorm HideCursor string `json:"civis,omitempty"` // civis AttrOff string `json:"sgr0,omitempty"` // sgr0 Underline string `json:"smul,omitempty"` // smul Bold string `json:"bold,omitempty"` // bold Blink string `json:"blink,omitempty"` // blink Reverse string `json:"rev,omitempty"` // rev Dim string `json:"dim,omitempty"` // dim EnterKeypad string `json:"smkx,omitempty"` // smkx ExitKeypad string `json:"rmkx,omitempty"` // rmkx SetFg string `json:"setaf,omitempty"` // setaf SetBg string `json:"setbg,omitempty"` // setab SetCursor string `json:"cup,omitempty"` // cup CursorBack1 string `json:"cub1,omitempty"` // cub1 CursorUp1 string `json:"cuu1,omitempty"` // cuu1 PadChar string `json:"pad,omitempty"` // pad KeyBackspace string `json:"kbs,omitempty"` // kbs KeyF1 string `json:"kf1,omitempty"` // kf1 KeyF2 string `json:"kf2,omitempty"` // kf2 KeyF3 string `json:"kf3,omitempty"` // kf3 KeyF4 string `json:"kf4,omitempty"` // kf4 KeyF5 string `json:"kf5,omitempty"` // kf5 KeyF6 string `json:"kf6,omitempty"` // kf6 KeyF7 string `json:"kf7,omitempty"` // kf7 KeyF8 string `json:"kf8,omitempty"` // kf8 KeyF9 string `json:"kf9,omitempty"` // kf9 KeyF10 string `json:"kf10,omitempty"` // kf10 KeyF11 string `json:"kf11,omitempty"` // kf11 KeyF12 string `json:"kf12,omitempty"` // kf12 KeyF13 string `json:"kf13,omitempty"` // kf13 KeyF14 string `json:"kf14,omitempty"` // kf14 KeyF15 string `json:"kf15,omitempty"` // kf15 KeyF16 string `json:"kf16,omitempty"` // kf16 KeyF17 string `json:"kf17,omitempty"` // kf17 KeyF18 string `json:"kf18,omitempty"` // kf18 KeyF19 string `json:"kf19,omitempty"` // kf19 KeyF20 string `json:"kf20,omitempty"` // kf20 KeyF21 string `json:"kf21,omitempty"` // kf21 KeyF22 string `json:"kf22,omitempty"` // kf22 KeyF23 string `json:"kf23,omitempty"` // kf23 KeyF24 string `json:"kf24,omitempty"` // kf24 KeyF25 string `json:"kf25,omitempty"` // kf25 KeyF26 string `json:"kf26,omitempty"` // kf26 KeyF27 string `json:"kf27,omitempty"` // kf27 KeyF28 string `json:"kf28,omitempty"` // kf28 KeyF29 string `json:"kf29,omitempty"` // kf29 KeyF30 string `json:"kf30,omitempty"` // kf30 KeyF31 string `json:"kf31,omitempty"` // kf31 KeyF32 string `json:"kf32,omitempty"` // kf32 KeyF33 string `json:"kf33,omitempty"` // kf33 KeyF34 string `json:"kf34,omitempty"` // kf34 KeyF35 string `json:"kf35,omitempty"` // kf35 KeyF36 string `json:"kf36,omitempty"` // kf36 KeyF37 string `json:"kf37,omitempty"` // kf37 KeyF38 string `json:"kf38,omitempty"` // kf38 KeyF39 string `json:"kf39,omitempty"` // kf39 KeyF40 string `json:"kf40,omitempty"` // kf40 KeyF41 string `json:"kf41,omitempty"` // kf41 KeyF42 string `json:"kf42,omitempty"` // kf42 KeyF43 string `json:"kf43,omitempty"` // kf43 KeyF44 string `json:"kf44,omitempty"` // kf44 KeyF45 string `json:"kf45,omitempty"` // kf45 KeyF46 string `json:"kf46,omitempty"` // kf46 KeyF47 string `json:"kf47,omitempty"` // kf47 KeyF48 string `json:"kf48,omitempty"` // kf48 KeyF49 string `json:"kf49,omitempty"` // kf49 KeyF50 string `json:"kf50,omitempty"` // kf50 KeyF51 string `json:"kf51,omitempty"` // kf51 KeyF52 string `json:"kf52,omitempty"` // kf52 KeyF53 string `json:"kf53,omitempty"` // kf53 KeyF54 string `json:"kf54,omitempty"` // kf54 KeyF55 string `json:"kf55,omitempty"` // kf55 KeyF56 string `json:"kf56,omitempty"` // kf56 KeyF57 string `json:"kf57,omitempty"` // kf57 KeyF58 string `json:"kf58,omitempty"` // kf58 KeyF59 string `json:"kf59,omitempty"` // kf59 KeyF60 string `json:"kf60,omitempty"` // kf60 KeyF61 string `json:"kf61,omitempty"` // kf61 KeyF62 string `json:"kf62,omitempty"` // kf62 KeyF63 string `json:"kf63,omitempty"` // kf63 KeyF64 string `json:"kf64,omitempty"` // kf64 KeyInsert string `json:"kich,omitempty"` // kich1 KeyDelete string `json:"kdch,omitempty"` // kdch1 KeyHome string `json:"khome,omitempty"` // khome KeyEnd string `json:"kend,omitempty"` // kend KeyHelp string `json:"khlp,omitempty"` // khlp KeyPgUp string `json:"kpp,omitempty"` // kpp KeyPgDn string `json:"knp,omitempty"` // knp KeyUp string `json:"kcuu1,omitempty"` // kcuu1 KeyDown string `json:"kcud1,omitempty"` // kcud1 KeyLeft string `json:"kcub1,omitempty"` // kcub1 KeyRight string `json:"kcuf1,omitempty"` // kcuf1 KeyBacktab string `json:"kcbt,omitempty"` // kcbt KeyExit string `json:"kext,omitempty"` // kext KeyClear string `json:"kclr,omitempty"` // kclr KeyPrint string `json:"kprt,omitempty"` // kprt KeyCancel string `json:"kcan,omitempty"` // kcan Mouse string `json:"kmous,omitempty"` // kmous MouseMode string `json:"XM,omitempty"` // XM AltChars string `json:"acsc,omitempty"` // acsc EnterAcs string `json:"smacs,omitempty"` // smacs ExitAcs string `json:"rmacs,omitempty"` // rmacs EnableAcs string `json:"enacs,omitempty"` // enacs KeyShfRight string `json:"kRIT,omitempty"` // kRIT KeyShfLeft string `json:"kLFT,omitempty"` // kLFT KeyShfHome string `json:"kHOM,omitempty"` // kHOM KeyShfEnd string `json:"kEND,omitempty"` // kEND SetFgBg string `json:"_setfgbg,omitempty"` // setfgbg SetFgBgRGB string `json:"_setfgbgrgb,omitempty"` // setfgbgrgb SetFgRGB string `json:"_setfrgb,omitempty"` // setfrgb SetBgRGB string `json:"_setbrgb,omitempty"` // setbrgb KeyShfUp string `json:"_kscu1,omitempty"` // shift-up KeyShfDown string `json:"_kscud1,omitempty"` // shift-down KeyCtrlUp string `json:"_kccu1,omitempty"` // ctrl-up KeyCtrlDown string `json:"_kccud1,omitempty"` // ctrl-left KeyCtrlRight string `json:"_kccuf1,omitempty"` // ctrl-right KeyCtrlLeft string `json:"_kccub1,omitempty"` // ctrl-left KeyMetaUp string `json:"_kmcu1,omitempty"` // meta-up KeyMetaDown string `json:"_kmcud1,omitempty"` // meta-left KeyMetaRight string `json:"_kmcuf1,omitempty"` // meta-right KeyMetaLeft string `json:"_kmcub1,omitempty"` // meta-left KeyAltUp string `json:"_kacu1,omitempty"` // alt-up KeyAltDown string `json:"_kacud1,omitempty"` // alt-left KeyAltRight string `json:"_kacuf1,omitempty"` // alt-right KeyAltLeft string `json:"_kacub1,omitempty"` // alt-left KeyCtrlHome string `json:"_kchome,omitempty"` KeyCtrlEnd string `json:"_kcend,omitempty"` KeyMetaHome string `json:"_kmhome,omitempty"` KeyMetaEnd string `json:"_kmend,omitempty"` KeyAltHome string `json:"_kahome,omitempty"` KeyAltEnd string `json:"_kaend,omitempty"` KeyAltShfUp string `json:"_kascu1,omitempty"` KeyAltShfDown string `json:"_kascud1,omitempty"` KeyAltShfLeft string `json:"_kascub1,omitempty"` KeyAltShfRight string `json:"_kascuf1,omitempty"` KeyMetaShfUp string `json:"_kmscu1,omitempty"` KeyMetaShfDown string `json:"_kmscud1,omitempty"` KeyMetaShfLeft string `json:"_kmscub1,omitempty"` KeyMetaShfRight string `json:"_kmscuf1,omitempty"` KeyCtrlShfUp string `json:"_kcscu1,omitempty"` KeyCtrlShfDown string `json:"_kcscud1,omitempty"` KeyCtrlShfLeft string `json:"_kcscub1,omitempty"` KeyCtrlShfRight string `json:"_kcscuf1,omitempty"` KeyCtrlShfHome string `json:"_kcHOME,omitempty"` KeyCtrlShfEnd string `json:"_kcEND,omitempty"` KeyAltShfHome string `json:"_kaHOME,omitempty"` KeyAltShfEnd string `json:"_kaEND,omitempty"` KeyMetaShfHome string `json:"_kmHOME,omitempty"` KeyMetaShfEnd string `json:"_kmEND,omitempty"` KeyCtrlPgUp string KeyCtrlPgDn string }
Terminfo represents a terminfo entry. Note that we use friendly names in Go, but when we write out JSON, we use the same names as terminfo. The name, aliases and smous, rmous fields do not come from terminfo directly.
func LookupTerminfo ¶
LookupTerminfo attempts to find a definition for the named $TERM. It first looks in the builtin database, which should cover just about everyone. If it can't find one there, then it will attempt to read one from the JSON file located in either $TCELLDB, $HOME/.tcelldb or in this package's source directory as database.json).
func (*Terminfo) TGoto ¶
TGoto returns a string suitable for addressing the cursor at the given row and column. The origin 0, 0 is in the upper left corner of the screen.
func (*Terminfo) TParm ¶
TParm takes a terminfo parameterized string, such as setaf or cup, and evaluates the string, and returns the result with the parameter applied.
func (*Terminfo) TPuts ¶
TPuts emits the string to the writer, but expands inline padding indications (of the form $<[delay]> where [delay] is msec) to a suitable number of padding characters (usually null bytes) based upon the supplied baud. At high baud rates, more padding characters will be inserted. All Terminfo based strings should be emitted using this function.
type Transformer ¶
type Transformer interface { // Transform writes to dst the transformed bytes read from src, and // returns the number of dst bytes written and src bytes read. The // atEOF argument tells whether src represents the last bytes of the // input. // // Callers should always process the nDst bytes produced and account // for the nSrc bytes consumed before considering the error err. // // A nil error means that all of the transformed bytes (whether freshly // transformed from src or left over from previous Transform calls) // were written to dst. A nil error can be returned regardless of // whether atEOF is true. If err is nil then nSrc must equal len(src); // the converse is not necessarily true. // // ErrShortDst means that dst was too short to receive all of the // transformed bytes. ErrShortSrc means that src had insufficient data // to complete the transformation. If both conditions apply, then // either error may be returned. Other than the error conditions listed // here, implementations are free to report other errors that arise. Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) // Reset resets the state and allows a Transformer to be reused. Reset() }
Transformer transforms bytes.
func Chain ¶
func Chain(t ...Transformer) Transformer
Chain returns a Transformer that applies t in sequence.
func RemoveFunc
deprecated
func RemoveFunc(f func(r rune) bool) Transformer
Deprecated: use runes.Remove instead.
type Writer ¶
type Writer struct {
// contains filtered or unexported fields
}
Writer wraps another io.Writer by transforming the bytes read. The user needs to call Close to flush unwritten bytes that may be buffered.