ansicode

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2024 License: MIT Imports: 9 Imported by: 0

README

go-ansicode

Go Report Card License MIT Go Doc

go-ansicode is a package that interprets ANSI codes and allows you to register a handler to deal with the operations.

Supported Sequences

C0
Operation Description
NUL Null (NUL) character.
SOH Start of Heading (SOH).
STX Start of Text (STX).
ETX End of Text (ETX).
EOT End of Transmission (EOT).
ENQ Enquiry (ENQ).
ACK Acknowledge (ACK).
BEL Bell (BEL).
BS Backspace (BS).
HT Horizontal Tab (HT).
LF Line Feed (LF).
VT Vertical Tab (VT).
FF Form Feed (FF).
CR Carriage Return (CR).
SO Shift Out (SO).
SI Shift In (SI).
DLE Data Link Escape (DLE).
XON Device Control 1 (XON).
DC2 Device Control 2 (DC2).
XOFF Device Control 3 (XOFF).
DC4 Device Control 4 (DC4).
NAK Negative Acknowledge (NAK).
SYN Synchronous Idle (SYN).
ETB End of Transmission Block (ETB).
CAN Cancel (CAN).
EM End of Medium (EM).
SUB Substitute (SUB).
ESC Escape (ESC).
FS File Separator (FS).
GS Group Separator (GS).
RS Record Separator (RS).
C1
Operation Description
IND Index - Move to the next line (Line Feed)
NEL Next Line - Line Feed followed by Carriage Return
HTS Horizontal Tab Set
RI Reverse Index - Move to the previous line
DECID Identify Terminal - Request for terminal identification
RIS Reset to Initial State - Reset all settings to defaults
DECSC Save Cursor - Save current cursor position and attributes
DECRC Restore Cursor - Restore cursor position and attributes
DECALN Alignment Test - Perform an alignment test
DECKPAM Keypad Application Mode - Enable Keypad Application Mode
DECKPNM Numeric Mode - Disable Keypad Application Mode
CSI
CSI Sequence Description
CSI Ps ' Single-character tabulation set (HTS)
CSI Ps @ Character tabulation with justification (CHA)
CSI Ps A Line tabulation set (VTS)
CSI Ps B Partial line forward (incomplete)
CSI Ps b Repeat character (REP)
CSI Ps C Cursor forward (CUF)
CSI Ps c Send device attributes (DA)
CSI Ps a Character position forward (CHA)
CSI Ps D Cursor backward (CUB)
CSI Ps d Vertical position absolute (VPA)
CSI Ps E Next line (NEL)
CSI Ps e Vertical position relative (VPR)
CSI Ps F Previous line (RI)
CSI Ps G Horizontal tab set (HTS)
CSI Ps g Tab clear (TBC)
CSI Ps ; Ps H Cursor position (CUP)
CSI Ps ; Ps f Horizontal and vertical position (HVP)
CSI Ps I Forward tabulation (HT)
CSI Ps J Erase in display (ED)
CSI Ps K Erase in line (EL)
CSI Ps L Insert line (IL)
CSI Ps l Reset mode (DEC)
CSI ? Ps l DEC private mode reset
CSI Ps M Delete line (DL)
CSI Pm m Character attribute (SGR)
CSI > Pp ; Pv m Select character protection attribute (DECSCPP)
CSI ? Pp m Select media character set and invoke macro (DECSEL)
CSI Ps n Device status report (DSR)
CSI Ps P Delete character (DCH)
CSI Ps SP q Select modifier and use bit combination (SMRM)
CSI Ps ; Ps r Set top and bottom margins (DECSTBM)
CSI Ps S Scroll up (SU)
CSI s Save cursor position (SCP)
CSI Ps T Scroll down (SD)
CSI Ps t Window manipulation (DECSWT)
CSI u Restore cursor position (RCP)
CSI ? u DEC private mode reset
CSI = Ps ; Ps u Set conformance level (DECSCL)
CSI > Ps u Set ANSI conformance level (DECSASD)
CSI < Ps u Set conformance level (DECSCL)
CSI Ps X Erase character (ECH)
CSI Ps Z Cursor back tabulation (CBT)
OSC
OSC Sequence Description
OSC 0 ; Pt BEL Set icon name and window title
OSC 2 ; Pt BEL Set window title
OSC 4 ; c ; spec BEL Change color in palette (8/16 colors)
OSC 8 ; params ; uri BEL Set hyperlinks
OSC 10 ; Ps BEL Set foreground text color
OSC 11 ; Ps BEL Set background text color
OSC 12 ; Ps BEL Set cursor text color
OSC 104 ; c BEL Reset color in palette (8/16 colors)
OSC 110 BEL Reset icon name and window title
OSC 111 BEL Reset window title
OSC 112 BEL Reset color in palette (24-bit)

Install

go get -u github.com/danielgatis/go-ansicode

And then import the package in your code:

import "github.com/danielgatis/go-ansicode"
Example

Please look at: examples/ansilog/main.go

❯ echo -ne "\033[31;42mThis text is red on a green background\033[0m\nbye" | go run ./examples/ansilog/main.go
SetTerminalCharAttribute {22 0x14000112018 <nil> <nil>}
SetTerminalCharAttribute {23 0x14000112020 <nil> <nil>}
Input 84
Input 104
Input 105
Input 115
Input 32
Input 116
Input 101
Input 120
Input 116
Input 32
Input 105
Input 115
Input 32
Input 114
Input 101
Input 100
Input 32
Input 111
Input 110
Input 32
Input 97
Input 32
Input 103
Input 114
Input 101
Input 101
Input 110
Input 32
Input 98
Input 97
Input 99
Input 107
Input 103
Input 114
Input 111
Input 117
Input 110
Input 100
SetTerminalCharAttribute {0 <nil> <nil> <nil>}
LineFeed
Input 98
Input 121
Input 101

License

Copyright (c) 2023-present Daniel Gatis

Licensed under MIT License

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CharAttribute

type CharAttribute int

CharAttribute is the character attribute.

const (
	CharAttributeReset CharAttribute = iota
	CharAttributeBold
	CharAttributeDim
	CharAttributeItalic
	CharAttributeUnderline
	CharAttributeDoubleUnderline
	CharAttributeCurlyUnderline
	CharAttributeDottedUnderline
	CharAttributeDashedUnderline
	CharAttributeBlinkSlow
	CharAttributeBlinkFast
	CharAttributeReverse
	CharAttributeHidden
	CharAttributeStrike
	CharAttributeCancelBold
	CharAttributeCancelBoldDim
	CharAttributeCancelItalic
	CharAttributeCancelUnderline
	CharAttributeCancelBlink
	CharAttributeCancelReverse
	CharAttributeCancelHidden
	CharAttributeCancelStrike
	CharAttributeForeground
	CharAttributeBackground
	CharAttributeUnderlineColor
)

CharAttribute values.

type CharsetIndex

type CharsetIndex int

CharsetIndex is used to index into the charset table.

const (
	CharsetIndexG0 CharsetIndex = iota
	CharsetIndexG1
	CharsetIndexG2
	CharsetIndexG3
)

CharsetIndex values.

type ClearMode

type ClearMode int

ClearMode is the clear mode.

const (
	ClearModeBelow ClearMode = iota
	ClearModeAbove
	ClearModeAll
	ClearModeSaved
)

ClearMode values.

type CursorStyle

type CursorStyle int

CursorStyle is the cursor style.

const (
	CursorStyleBlinkingBlock CursorStyle = iota
	CursorStyleSteadyBlock
	CursorStyleBlinkingUnderline
	CursorStyleSteadyUnderline
	CursorStyleBlinkingBar
	CursorStyleSteadyBar
)

CursorStyle values.

type Decoder

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

Decoder is a byte writer that decodes ANSI escape sequences.

func NewDecoder

func NewDecoder(handler Handler) *Decoder

NewDecoder creates a new Decoder.

func (*Decoder) Write

func (p *Decoder) Write(b []byte) (int, error)

Write writes a byte slice to the decoder.

func (*Decoder) WriteByte

func (p *Decoder) WriteByte(c byte) error

WriteByte writes a byte to the decoder.

type Handler

type Handler interface {
	// Backspace moves the cursor one position to the left.
	Backspace()

	// Bell rings the bell.
	Bell()

	// CarriageReturn moves the cursor to the beginning of the line.
	CarriageReturn()

	// ClearLine clears the line.
	ClearLine(mode LineClearMode)

	// ClearScreen clears the screen.
	ClearScreen(mode ClearMode)

	// ClearTabs clears the tab stops.
	ClearTabs(mode TabulationClearMode)

	// ClipboardLoad loads data from the clipboard.
	ClipboardLoad(clipboard byte, terminator string)

	// ClipboardStore stores data in the clipboard.
	ClipboardStore(clipboard byte, data []byte)

	// ConfigureCharset configures the charset.
	ConfigureCharset(index CharsetIndex, charset StandardCharset)

	// Dcaln runs the DECALN command.
	Decaln()

	// DeleteChars deletes n characters.
	DeleteChars(n int)

	// DeleteLines deletes n lines.
	DeleteLines(n int)

	// DeviceStatus reports the device status.
	DeviceStatus(n int)

	// EraseChars erases n characters.
	// erase means reset to the default state. (default colors, no content, no flags)
	EraseChars(n int)

	// Goto moves the cursor to the specified position.
	Goto(y int, x int)

	// GotoCol moves the cursor to the specified column.
	GotoCol(n int)

	// GotoLine moves the cursor to the specified line.
	GotoLine(n int)

	// HorizontalTab sets the current position as a tab stop.
	HorizontalTabSet()

	// IdentifyTerminal identifies the terminal.
	IdentifyTerminal(b byte)

	// Input inputs a rune to be displayed.
	Input(r rune)

	// InsertBlank inserts n blank characters.
	InsertBlank(n int)

	// InsertBlankLines inserts n blank lines.
	InsertBlankLines(n int)

	// LineFeed moves the cursor to the next line.
	LineFeed()

	// MoveBackward moves the cursor backward n columns.
	MoveBackward(n int)

	// MoveBackwardTabs moves the cursor backward n tab stops.
	MoveBackwardTabs(n int)

	// MoveDown moves the cursor down n lines.
	MoveDown(n int)

	// MoveDownCr moves the cursor down n lines and to the beginning of the line.
	MoveDownCr(n int)

	// MoveForward moves the cursor forward n columns.
	MoveForward(n int)

	// MoveForwardTabs moves the cursor forward n tab stops.
	MoveForwardTabs(n int)

	// MoveUp moves the cursor up n lines.
	MoveUp(n int)

	// MoveUpCr moves the cursor up n lines and to the beginning of the line.
	MoveUpCr(n int)

	// PopKeyboardMode pops the given amount n of keyboard modes from the stack.
	PopKeyboardMode(n int)

	// PopTitle pops the title from the stack.
	PopTitle()

	// PushKeyboardMode pushes the given keyboard mode to the stack.
	PushKeyboardMode(mode KeyboardMode)

	// PushTitle pushes the given title to the stack.
	PushTitle()

	// ReportKeyboardMode reports the keyboard mode.
	ReportKeyboardMode()

	// ReportModifyOtherKeys reports the modify other keys mode. (XTERM)
	ReportModifyOtherKeys()

	// ResetColor resets the color at the given index.
	ResetColor(i int)

	// ResetState resets the termnial state.
	ResetState()

	// RestoreCursorPosition restores the cursor position.
	RestoreCursorPosition()

	// ReverseIndex moves the active position to the same horizontal position on the preceding line.
	// If the active position is at the top margin, a scroll down is performed.
	ReverseIndex()

	// SaveCursorPosition saves the cursor position.
	SaveCursorPosition()

	// ScrollDown scrolls the screen down n lines.
	ScrollDown(n int)

	// ScrollUp scrolls the screen up n lines.
	ScrollUp(n int)

	// SetActiveCharset sets the active charset.
	SetActiveCharset(n int)

	// SetColor sets the color at the given index.
	SetColor(index int, color color.Color)

	// SetCursorStyle sets the cursor style.
	SetCursorStyle(style CursorStyle)

	// SetDynamicColor sets the dynamic color at the given index.
	SetDynamicColor(prefix string, index int, terminator string)

	// SetHyperlink sets the hyperlink.
	SetHyperlink(hyperlink *Hyperlink)

	// SetKeyboardMode sets the keyboard mode.
	SetKeyboardMode(mode KeyboardMode, behavior KeyboardModeBehavior)

	// SetKeypadApplicationMode sets keypad to applications mode.
	SetKeypadApplicationMode()

	// SetModifyOtherKeys sets the modify other keys mode. (XTERM)
	SetModifyOtherKeys(modify ModifyOtherKeys)

	// SetScrollingRegion sets the scrolling region.
	SetScrollingRegion(top int, bottom int)

	// SetTerminalCharAttribute sets the terminal char attribute.
	SetTerminalCharAttribute(attr TerminalCharAttribute)

	// SetTitle sets the window title.
	SetTitle(title string)

	// Substitue replaces the character under the cursor.
	Substitute()

	// Tab moves the cursor to the next tab stop.
	Tab(n int)

	// TextAreaSizeChars reports the text area size in characters.
	TextAreaSizeChars()

	// TextAreaSizePixels reports the text area size in pixels.
	TextAreaSizePixels()

	// UnsetKeypadApplicationMode sets the keypad to numeric mode.
	UnsetKeypadApplicationMode()

	// UnsetMode unsets the given mode.
	UnsetMode(mode TerminalMode)
}

Handler is the interface that handles ANSI escape sequences.

type Hyperlink struct {
	// ID is the hyperlink ID.
	ID string

	// URI is the hyperlink URI.
	URI string
}

Hyperlink is used to represent a hyperlink.

type IndexedColor

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

IndexedColor is a color that can be represented by an index.

type KeyboardMode

type KeyboardMode byte

KeyboardMode is the keyboard mode.

const (
	KeyboardModeNoMode               KeyboardMode = 0b0000_0000
	KeyboardModeDisambiguateEscCodes KeyboardMode = 0b0000_0001
	KeyboardModeReportEventTypes     KeyboardMode = 0b0000_0010
	KeyboardModeReportAlternateKeys  KeyboardMode = 0b0000_0100
	KeyboardModeReportAllKeysAsEsc   KeyboardMode = 0b0000_1000
	KeyboardModeReportAssociatedText KeyboardMode = 0b0001_0000
)

KeyboardMode values.

type KeyboardModeBehavior

type KeyboardModeBehavior int

KeyboardModeBehavior is the keyboard mode behavior.

const (
	KeyboardModeBehaviorReplace KeyboardModeBehavior = iota
	KeyboardModeBehaviorUnion
	KeyboardModeBehaviorDifference
)

KeyboardModeBehavior values.

type LineClearMode

type LineClearMode int

LineClearMode is the line clear mode.

const (
	LineClearModeRight LineClearMode = iota
	LineClearModeLeft
	LineClearModeAll
)

LineClearMode values.

type Logger

type Logger struct{}

Logger wraps the slog.

func (*Logger) Debugf added in v1.0.2

func (l *Logger) Debugf(msg string, args ...interface{})

Debugf logs a message at Debug level.

type ModifyOtherKeys

type ModifyOtherKeys int

ModifyOtherKeys is the XTerm modify other keys mode.

const (
	ModifyOtherKeysReset ModifyOtherKeys = iota
	ModifyOtherKeysEnableExceptWellDefined
	ModifyOtherKeysResetEnableAll
)

ModifyOtherKeys values.

type NamedColor

type NamedColor int

NamedColor is a color that can be referenced by name.

const (
	NamedColorBlack         NamedColor = 0
	NamedColorRed           NamedColor = 1
	NamedColorGreen         NamedColor = 2
	NamedColorYellow        NamedColor = 3
	NamedColorBlue          NamedColor = 4
	NamedColorMagenta       NamedColor = 5
	NamedColorCyan          NamedColor = 6
	NamedColorWhite         NamedColor = 7
	NamedColorBrightBlack   NamedColor = 8
	NamedColorBrightRed     NamedColor = 9
	NamedColorBrightGreen   NamedColor = 10
	NamedColorBrightYellow  NamedColor = 11
	NamedColorBrightBlue    NamedColor = 12
	NamedColorBrightMagenta NamedColor = 13
	NamedColorBrightCyan    NamedColor = 14
	NamedColorBrightWhite   NamedColor = 15

	NamedColorCubeStart NamedColor = 16
	NamedColorCubeEnd   NamedColor = 232

	NamedColorGrayscaleStart NamedColor = 233
	NamedColorGrayscaleEnd   NamedColor = 255

	NamedColorForeground NamedColor = 256
	NamedColorBackground NamedColor = 257
	NamedColorCursor     NamedColor = 258

	NamedColorDimBlack   NamedColor = 259
	NamedColorDimRed     NamedColor = 260
	NamedColorDimGreen   NamedColor = 261
	NamedColorDimYellow  NamedColor = 262
	NamedColorDimBlue    NamedColor = 263
	NamedColorDimMagenta NamedColor = 264
	NamedColorDimCyan    NamedColor = 265
	NamedColorDimWhite   NamedColor = 266

	NamedColorBrightForeground NamedColor = 267
	NamedColorDimForeground    NamedColor = 268
)

NamedColor values.

func (NamedColor) ToBright

func (c NamedColor) ToBright() NamedColor

ToBright returns the bright version of the color.

func (NamedColor) ToDim

func (c NamedColor) ToDim() NamedColor

ToDim returns the dim version of the color.

type Performer

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

Performer is a interface for handling ANSI escape sequences.

func NewPerformer

func NewPerformer(handler Handler) *Performer

newPerformer creates a new Performer.

func (*Performer) CsiDispatch

func (p *Performer) CsiDispatch(params [][]uint16, intermediates []byte, ignore bool, action rune)

CsiDispatch is used to handle csi operations.

func (*Performer) EscDispatch

func (p *Performer) EscDispatch(intermediates []byte, ignore bool, b byte)

EscDispatch is used to handle esc operations.

func (*Performer) Execute

func (p *Performer) Execute(b byte)

Execute is used to handle execute operations.

func (*Performer) Hook

func (p *Performer) Hook(params [][]uint16, intermediates []byte, ignore bool, r rune)

Hook is used to handle hook operations.

func (*Performer) OscDispatch

func (p *Performer) OscDispatch(params [][]byte, bellTerminated bool)

OscDispatch is used to handle osc operations.

func (*Performer) Print

func (p *Performer) Print(r rune)

Print is used to handle print operations.

func (*Performer) Put

func (p *Performer) Put(b byte)

Put is used to handle put operations.

func (*Performer) Unhook

func (p *Performer) Unhook()

Unhook is used to handle unhook operations.

type RGBColor

type RGBColor struct {
	R, G, B uint8
}

RGBColor is a color that can be represented by RGB values.

func (RGBColor) RGBA

func (c RGBColor) RGBA() (r, g, b, a uint32)

RGBA returns the RGBA value of the color.

type StandardCharset

type StandardCharset int

StandardCharset is used to select a standard charset.

const (
	StandardCharsetASCII StandardCharset = iota
	StandardCharsetSpecialCharacterAndLineDrawing
)

StandardCharset values.

func (StandardCharset) Char

func (sc StandardCharset) Char(c rune) rune

Char returns the rune for the given rune in the given charset.

type TabulationClearMode

type TabulationClearMode int

TabulationClearMode is the tabulation clear mode.

const (
	TabulationClearModeCurrent TabulationClearMode = iota
	TabulationClearModeAll
)

TabulationClearMode values.

type TerminalCharAttribute

type TerminalCharAttribute struct {
	Attr         CharAttribute
	NamedColor   *NamedColor
	RGBColor     *RGBColor
	IndexedColor *IndexedColor
}

TerminalCharAttribute is the terminal character attribute.

type TerminalMode

type TerminalMode int

TerminalMode is the terminal mode.

const (
	TerminalModeCursorKeys                    TerminalMode = 1
	TerminalModeColumnMode                    TerminalMode = 3
	TerminalModeInsert                        TerminalMode = 4
	TerminalModeOrigin                        TerminalMode = 6
	TerminalModeLineWrap                      TerminalMode = 7
	TerminalModeBlinkingCursor                TerminalMode = 12
	TerminalModeLineFeedNewLine               TerminalMode = 20
	TerminalModeShowCursor                    TerminalMode = 25
	TerminalModeReportMouseClicks             TerminalMode = 1000
	TerminalModeReportCellMouseMotion         TerminalMode = 1002
	TerminalModeReportAllMouseMotion          TerminalMode = 1003
	TerminalModeReportFocusInOut              TerminalMode = 1004
	TerminalModeUTF8Mouse                     TerminalMode = 1005
	TerminalModeSGRMouse                      TerminalMode = 1006
	TerminalModeAlternateScroll               TerminalMode = 1007
	TerminalModeUrgencyHints                  TerminalMode = 1042
	TerminalModeSwapScreenAndSetRestoreCursor TerminalMode = 1049
	TerminalModeBracketedPaste                TerminalMode = 2004
)

TerminalMode values.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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