Documentation
¶
Overview ¶
Package ansi provides ANSI-aware text wrapping, hyperlinks, and TTY fallback.
Index ¶
- Constants
- func CursorBackward(n int) string
- func CursorDown(n int) string
- func CursorForward(n int) string
- func CursorHorizontalAbsolute(col int) string
- func CursorNextLine(n int) string
- func CursorPosition(col, row int) string
- func CursorPreviousLine(n int) string
- func CursorUp(n int) string
- func DeleteCharacter(n int) string
- func DeleteLine(n int) string
- func EraseCharacter(n int) string
- func EraseDisplay(n int) string
- func EraseLine(n int) string
- func InsertCharacter(n int) string
- func InsertLine(n int) string
- func ScrollDown(n int) string
- func ScrollUp(n int) string
- func SetCursorStyle(style int) string
- func SetIconName(s string) string
- func SetIconNameWindowTitle(s string) string
- func SetWindowTitle(s string) string
- func StringWidth(s string) int
- func Strip(s string) string
- func Truncate(s string, length int, tail string) string
- func WrapHard(s string, width int) string
- func WrapSoft(s string, width int) string
- type ANSI
- type HyperlinkFallback
- type Method
- type Option
- type WrapOption
- type Wrapper
Examples ¶
Constants ¶
const ( EraseLineRight = xansi.EraseLineRight EraseLineLeft = xansi.EraseLineLeft EraseEntireLine = xansi.EraseEntireLine EraseScreenBelow = xansi.EraseScreenBelow EraseScreenAbove = xansi.EraseScreenAbove EraseEntireScreen = xansi.EraseEntireScreen )
Erase constants (delegated).
const ( CursorUp1 = xansi.CUU1 CursorDown1 = xansi.CUD1 CursorRight1 = xansi.CUF1 CursorLeft1 = xansi.CUB1 )
Cursor movement - single-step constants. Upstream's preferred names are the opaque CUU1/CUD1/CUF1/CUB1 spellings; we keep the readable aliases here and forward to the non-deprecated upstream symbols.
const ( ShowCursor = xansi.ShowCursor HideCursor = xansi.HideCursor )
Cursor visibility (DECTCEM).
const ( SaveCursorPosition = xansi.SaveCurrentCursorPosition RestoreCursorPosition = xansi.RestoreCurrentCursorPosition )
Cursor save/restore (SCOSC / SCORC).
const ( Focus = xansi.Focus Blur = xansi.Blur )
Focus reporting events (terminal → app, when focus events are enabled).
const ( EnterAltScreen = xansi.SetModeAltScreenSaveCursor ExitAltScreen = xansi.ResetModeAltScreenSaveCursor )
Alt-screen buffer (DEC 1049: also saves/restores cursor).
const ( EnableBracketedPaste = xansi.SetModeBracketedPaste DisableBracketedPaste = xansi.ResetModeBracketedPaste )
Bracketed paste mode (DEC 2004).
const ( EnableFocusEvents = xansi.SetModeFocusEvent DisableFocusEvents = xansi.ResetModeFocusEvent )
Focus event reporting mode (DEC 1004).
const ( EnableSyncOutput = xansi.SetModeSynchronizedOutput DisableSyncOutput = xansi.ResetModeSynchronizedOutput )
Synchronized output mode (DEC 2026). Wrap a repaint in Enable/Disable so the terminal applies the whole frame atomically; terminals without support ignore both sequences.
const ( // RequestCursorPosition asks the terminal for the current cursor // position (DSR 6). The reply is CSI <row> ; <col> R. RequestCursorPosition = xansi.RequestCursorPositionReport // RequestExtendedCursorPosition asks for the unambiguous DEC form // (DSR ?6). Preferred over [RequestCursorPosition] when the terminal // supports it, because the reply is distinguishable from key input. RequestExtendedCursorPosition = xansi.RequestExtendedCursorPositionReport // RequestPrimaryDeviceAttributes asks the terminal to identify itself // (DA1). Reply format varies by terminal. RequestPrimaryDeviceAttributes = xansi.RequestPrimaryDeviceAttributes )
Terminal queries - the terminal replies with a corresponding report.
const ( KeypadApplicationMode = xansi.KeypadApplicationMode KeypadNumericMode = xansi.KeypadNumericMode )
Keypad modes (DECKPAM / DECKPNM). Application mode makes the numeric keypad emit escape sequences rather than raw digits; relevant when the host reads keys in raw mode.
const ( EnableMouseX10 = xansi.SetModeMouseX10 DisableMouseX10 = xansi.ResetModeMouseX10 EnableMouseNormal = xansi.SetModeMouseNormal DisableMouseNormal = xansi.ResetModeMouseNormal EnableMouseButtonEvent = xansi.SetModeMouseButtonEvent DisableMouseButtonEvent = xansi.ResetModeMouseButtonEvent EnableMouseAnyEvent = xansi.SetModeMouseAnyEvent DisableMouseAnyEvent = xansi.ResetModeMouseAnyEvent EnableMouseSGR = xansi.SetModeMouseExtSgr DisableMouseSGR = xansi.ResetModeMouseExtSgr )
Mouse tracking modes. Each pair toggles a DEC private mode; the encoding mode (SGR) is usually enabled alongside one of the event modes:
X10 legacy, presses only (no release) Normal press + release ButtonEvent press + release + motion while button held AnyEvent press + release + motion at all times SGR extended coordinate encoding, required for columns > 223
const ( WcWidth = xansi.WcWidth GraphemeWidth = xansi.GraphemeWidth )
Display width methods.
const CSI = "\x1b["
CSI is the Control Sequence Introducer prefix (ESC + `[`). Exported for callers that parse or construct their own CSI-family sequences.
const ClearLine = xansi.EraseEntireLine + "\r"
ClearLine erases the entire current line (EL 2) and returns the cursor to column 0 (CR). This is a convenience composite not present in upstream; every other escape here delegates to github.com/charmbracelet/x/ansi.
const CursorHomePosition = xansi.CursorHomePosition
CursorHomePosition moves the cursor to row 1, column 1 (`"\x1b[H"`).
const RequestNameVersion = xansi.RequestNameVersion
RequestNameVersion is the XTVERSION query (`"\x1b[>q"`): asks the terminal for its name and version. Complements the DA1 query.
const ResetStyle = xansi.ResetStyle
ResetStyle is the SGR reset sequence (`"\x1b[m"`): clears all text attributes and colours. Included because writing any styled output typically requires emitting this afterwards.
Variables ¶
This section is empty.
Functions ¶
func CursorBackward ¶
CursorBackward returns the CUB sequence: move cursor left `n` columns.
func CursorDown ¶
CursorDown returns the CUD sequence: move cursor down `n` lines.
func CursorForward ¶
CursorForward returns the CUF sequence: move cursor right `n` columns.
func CursorHorizontalAbsolute ¶
CursorHorizontalAbsolute returns the CHA sequence: move to column `col` on the current line.
func CursorNextLine ¶
CursorNextLine returns the CNL sequence: move down `n` lines and to column 1.
func CursorPosition ¶
CursorPosition returns the CUP sequence: move to (`col`, `row`). Coordinates are 1-based.
func CursorPreviousLine ¶
CursorPreviousLine returns the CPL sequence: move up `n` lines and to column 1.
func CursorUp ¶
CursorUp returns the CUU sequence: move cursor up `n` lines.
Example ¶
package main
import (
"fmt"
"github.com/gechr/x/ansi"
)
func main() {
fmt.Printf("%q\n", ansi.CursorUp(3))
}
Output: "\x1b[3A"
func DeleteCharacter ¶
DeleteCharacter returns the DCH sequence: delete `n` characters at the cursor, pulling subsequent characters left.
func DeleteLine ¶
DeleteLine returns the DL sequence: delete `n` lines starting at the cursor, pulling subsequent lines up.
func EraseCharacter ¶
EraseCharacter returns the ECH sequence: erase `n` characters from the cursor position (no cursor movement).
func EraseDisplay ¶
EraseDisplay returns the ED sequence. `n` selects the variant: 0 = below cursor, 1 = above cursor, 2 = entire screen.
func EraseLine ¶
EraseLine returns the EL sequence. `n` selects the variant: 0 = right of cursor, 1 = left of cursor, 2 = entire line.
func InsertCharacter ¶
InsertCharacter returns the ICH sequence: insert `n` blank characters at the cursor, shifting existing characters right.
func InsertLine ¶
InsertLine returns the IL sequence: insert `n` blank lines at the cursor, pushing existing lines down.
func ScrollDown ¶
ScrollDown returns the SD sequence: scroll viewport down `n` lines (content moves down; new blank lines appear at the top).
func ScrollUp ¶
ScrollUp returns the SU sequence: scroll viewport up `n` lines (content moves up; new blank lines appear at the bottom).
func SetCursorStyle ¶
SetCursorStyle returns the DECSCUSR sequence. `style` selects shape and blink state:
0: default 1: blinking block 2: steady block 3: blinking under 4: steady under 5: blinking bar 6: steady bar
func SetIconName ¶
SetIconName sets the icon/tab name only (OSC 1).
func SetIconNameWindowTitle ¶
SetIconNameWindowTitle sets both the icon name and window title in a single sequence (OSC 0).
func SetWindowTitle ¶
SetWindowTitle sets the terminal window title only (OSC 2).
func StringWidth ¶
StringWidth returns the display width of a string in cells, ignoring ANSI escape codes and accounting for wide characters. Uses grapheme clustering.
Example ¶
package main
import (
"fmt"
"github.com/gechr/x/ansi"
)
func main() {
fmt.Println(ansi.StringWidth("\x1b[31mred\x1b[m"))
fmt.Println(ansi.StringWidth("こんにちは"))
}
Output: 3 10
func Strip ¶
Strip removes ANSI escape codes from a string.
Example ¶
package main
import (
"fmt"
"github.com/gechr/x/ansi"
)
func main() {
fmt.Println(ansi.Strip("\x1b[1mbold\x1b[m and plain"))
}
Output: bold and plain
func Truncate ¶
Truncate truncates a string to a given cell width, appending `tail` if the string was truncated. ANSI escape codes are preserved.
Example ¶
package main
import (
"fmt"
"github.com/gechr/x/ansi"
)
func main() {
fmt.Println(ansi.Truncate("Hello, World!", 8, "…"))
}
Output: Hello, …
func WrapHard ¶
WrapHard wraps `s` at exactly `width` columns, breaking mid-word if needed. ANSI styles are preserved.
Example ¶
package main
import (
"fmt"
"github.com/gechr/x/ansi"
)
func main() {
fmt.Println(ansi.WrapHard("the quick brown fox", 6))
}
Output: the qu ick br own fo x
func WrapSoft ¶
WrapSoft wraps `s` to fit within `width` columns, breaking at space boundaries. Words longer than `width` are hard-wrapped. ANSI styles are preserved.
Example ¶
package main
import (
"fmt"
"github.com/gechr/x/ansi"
)
func main() {
fmt.Println(ansi.WrapSoft("the quick brown fox jumps over the lazy dog", 12))
}
Output: the quick brown fox jumps over the lazy dog
Types ¶
type ANSI ¶
type ANSI struct {
// contains filtered or unexported fields
}
ANSI produces ANSI-aware output, falling back to plain text when the output is not a terminal.
func Auto ¶
Auto creates an ANSI that auto-detects whether the output is a terminal. All provided `files` must be terminals for ANSI output to be enabled. Defaults to os.Stdout if no `files` are provided.
func (*ANSI) Hyperlink ¶
Hyperlink creates an OSC 8 terminal hyperlink. When the output is not a terminal, the HyperlinkFallback mode controls how the link is rendered in plain text.
Example ¶
When output is not a terminal, hyperlinks render as plain text using the configured fallback mode.
package main
import (
"fmt"
"github.com/gechr/x/ansi"
)
func main() {
w := ansi.Never()
fmt.Println(w.Hyperlink("https://example.com", "example"))
w = ansi.New(ansi.WithHyperlinkFallback(ansi.HyperlinkFallbackMarkdown))
fmt.Println(w.Hyperlink("https://example.com", "example"))
}
Output: example (https://example.com) [example](https://example.com)
type HyperlinkFallback ¶
type HyperlinkFallback int
HyperlinkFallback controls how hyperlinks render when the output is not a terminal.
const ( // HyperlinkFallbackExpanded renders "text (url)". HyperlinkFallbackExpanded HyperlinkFallback = iota // HyperlinkFallbackMarkdown renders "[text](url)". HyperlinkFallbackMarkdown // HyperlinkFallbackText renders only the display text, discarding the URL. HyperlinkFallbackText // HyperlinkFallbackURL renders only the URL, discarding the display text. HyperlinkFallbackURL )
type Option ¶
type Option func(*ANSI)
Option configures an ANSI.
func WithHyperlinkFallback ¶
func WithHyperlinkFallback(fallback HyperlinkFallback) Option
WithHyperlinkFallback sets how hyperlinks render when the output is not a terminal.
func WithTerminal ¶
WithTerminal sets whether the output target is a terminal.
type WrapOption ¶
type WrapOption func(*Wrapper)
WrapOption configures a Wrapper.
func WithBreakpoints ¶
func WithBreakpoints(chars string) WrapOption
WithBreakpoints adds characters (beyond spaces) that are treated as word break opportunities during soft wrapping. Has no effect in hard wrap mode.
func WithPreserveStyle ¶
func WithPreserveStyle(preserve bool) WrapOption
WithPreserveStyle controls whether ANSI styles and hyperlinks are reset and reapplied across line breaks. Default: true.
func WithWidth ¶
func WithWidth(width int) WrapOption
WithWidth sets a static wrap width. A `width` < 1 disables wrapping.
func WithWidthFunc ¶
func WithWidthFunc(fn func() int) WrapOption
WithWidthFunc sets a dynamic width function, called on each Wrapper.Wrap invocation. Takes precedence over WithWidth.
func WithWrapHard ¶
func WithWrapHard() WrapOption
WithWrapHard selects hard wrapping: break at the exact column width, even mid-word.
func WithWrapSoft ¶
func WithWrapSoft() WrapOption
WithWrapSoft selects soft wrapping: break at space boundaries, with hard-wrap fallback for words longer than the width. This is the default.
type Wrapper ¶
type Wrapper struct {
// contains filtered or unexported fields
}
Wrapper wraps text to a configured width, preserving ANSI escape sequences.
func NewWrapper ¶
func NewWrapper(opts ...WrapOption) *Wrapper
NewWrapper creates a Wrapper with the given options. Defaults: soft wrap, no additional breakpoints, ANSI style preservation enabled.
Example ¶
Breakpoints add word-break opportunities beyond spaces, which is useful for wrapping paths or flags.
package main
import (
"fmt"
"github.com/gechr/x/ansi"
)
func main() {
w := ansi.NewWrapper(ansi.WithWidth(10), ansi.WithBreakpoints("-"))
fmt.Println(w.Wrap("a-very-long-flag-name"))
}
Output: a-very- long-flag- name