ansi

package
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Jul 12, 2026 License: MIT Imports: 10 Imported by: 0

README

ansi

import "github.com/gechr/x/ansi"

Package ansi provides ANSI-aware text wrapping, hyperlinks, and TTY fallback.

Index

Constants

Erase constants (delegated).

const (
    EraseLineRight    = xansi.EraseLineRight
    EraseLineLeft     = xansi.EraseLineLeft
    EraseEntireLine   = xansi.EraseEntireLine
    EraseScreenBelow  = xansi.EraseScreenBelow
    EraseScreenAbove  = xansi.EraseScreenAbove
    EraseEntireScreen = xansi.EraseEntireScreen
)

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 (
    CursorUp1    = xansi.CUU1
    CursorDown1  = xansi.CUD1
    CursorRight1 = xansi.CUF1
    CursorLeft1  = xansi.CUB1
)

Cursor visibility (DECTCEM).

const (
    ShowCursor = xansi.ShowCursor
    HideCursor = xansi.HideCursor
)

Cursor save/restore (SCOSC / SCORC).

const (
    SaveCursorPosition    = xansi.SaveCurrentCursorPosition
    RestoreCursorPosition = xansi.RestoreCurrentCursorPosition
)

Focus reporting events (terminal → app, when focus events are enabled).

const (
    Focus = xansi.Focus
    Blur  = xansi.Blur
)

Alt-screen buffer (DEC 1049: also saves/restores cursor).

const (
    EnterAltScreen = xansi.SetModeAltScreenSaveCursor
    ExitAltScreen  = xansi.ResetModeAltScreenSaveCursor
)

Bracketed paste mode (DEC 2004).

const (
    EnableBracketedPaste  = xansi.SetModeBracketedPaste
    DisableBracketedPaste = xansi.ResetModeBracketedPaste
)

Focus event reporting mode (DEC 1004).

const (
    EnableFocusEvents  = xansi.SetModeFocusEvent
    DisableFocusEvents = xansi.ResetModeFocusEvent
)

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 (
    EnableSyncOutput  = xansi.SetModeSynchronizedOutput
    DisableSyncOutput = xansi.ResetModeSynchronizedOutput
)

Terminal queries - the terminal replies with a corresponding report.

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
)

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 (
    KeypadApplicationMode = xansi.KeypadApplicationMode
    KeypadNumericMode     = xansi.KeypadNumericMode
)

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 (
    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
)

Display width methods.

const (
    WcWidth       = xansi.WcWidth
    GraphemeWidth = xansi.GraphemeWidth
)

CSI is the Control Sequence Introducer prefix (ESC + [). Exported for callers that parse or construct their own CSI-family sequences.

const CSI = "\x1b["

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 ClearLine = xansi.EraseEntireLine + "\r"

CursorHomePosition moves the cursor to row 1, column 1 ("\x1b[H").

const CursorHomePosition = xansi.CursorHomePosition

RequestNameVersion is the XTVERSION query ("\x1b[>q"): asks the terminal for its name and version. Complements the DA1 query.

const RequestNameVersion = xansi.RequestNameVersion

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.

const ResetStyle = xansi.ResetStyle

func CursorBackward

func CursorBackward(n int) string

CursorBackward returns the CUB sequence: move cursor left n columns.

func CursorDown

func CursorDown(n int) string

CursorDown returns the CUD sequence: move cursor down n lines.

func CursorForward

func CursorForward(n int) string

CursorForward returns the CUF sequence: move cursor right n columns.

func CursorHorizontalAbsolute

func CursorHorizontalAbsolute(col int) string

CursorHorizontalAbsolute returns the CHA sequence: move to column col on the current line.

func CursorNextLine

func CursorNextLine(n int) string

CursorNextLine returns the CNL sequence: move down n lines and to column 1.

func CursorPosition

func CursorPosition(col, row int) string

CursorPosition returns the CUP sequence: move to (col, row). Coordinates are 1-based.

func CursorPreviousLine

func CursorPreviousLine(n int) string

CursorPreviousLine returns the CPL sequence: move up n lines and to column 1.

func CursorUp

func CursorUp(n int) string

CursorUp returns the CUU sequence: move cursor up n lines.

Example
fmt.Printf("%q\n", ansi.CursorUp(3))

Output:

"\x1b[3A"

func DeleteCharacter

func DeleteCharacter(n int) string

DeleteCharacter returns the DCH sequence: delete n characters at the cursor, pulling subsequent characters left.

func DeleteLine

func DeleteLine(n int) string

DeleteLine returns the DL sequence: delete n lines starting at the cursor, pulling subsequent lines up.

func EraseCharacter

func EraseCharacter(n int) string

EraseCharacter returns the ECH sequence: erase n characters from the cursor position (no cursor movement).

func EraseDisplay

func EraseDisplay(n int) string

EraseDisplay returns the ED sequence. n selects the variant: 0 = below cursor, 1 = above cursor, 2 = entire screen.

func EraseLine

func EraseLine(n int) string

EraseLine returns the EL sequence. n selects the variant: 0 = right of cursor, 1 = left of cursor, 2 = entire line.

func InsertCharacter

func InsertCharacter(n int) string

InsertCharacter returns the ICH sequence: insert n blank characters at the cursor, shifting existing characters right.

func InsertLine

func InsertLine(n int) string

InsertLine returns the IL sequence: insert n blank lines at the cursor, pushing existing lines down.

func ScrollDown

func ScrollDown(n int) string

ScrollDown returns the SD sequence: scroll viewport down n lines (content moves down; new blank lines appear at the top).

func ScrollUp

func ScrollUp(n int) string

ScrollUp returns the SU sequence: scroll viewport up n lines (content moves up; new blank lines appear at the bottom).

func SetCursorStyle

func SetCursorStyle(style int) string

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

func SetIconName(s string) string

SetIconName sets the icon/tab name only (OSC 1).

func SetIconNameWindowTitle

func SetIconNameWindowTitle(s string) string

SetIconNameWindowTitle sets both the icon name and window title in a single sequence (OSC 0).

func SetWindowTitle

func SetWindowTitle(s string) string

SetWindowTitle sets the terminal window title only (OSC 2).

func StringWidth

func StringWidth(s string) int

StringWidth returns the display width of a string in cells, ignoring ANSI escape codes and accounting for wide characters. Uses grapheme clustering.

Example
fmt.Println(ansi.StringWidth("\x1b[31mred\x1b[m"))
fmt.Println(ansi.StringWidth("こんにちは"))

Output:

3
10

func Strip

func Strip(s string) string

Strip removes ANSI escape codes from a string.

Example
fmt.Println(ansi.Strip("\x1b[1mbold\x1b[m and plain"))

Output:

bold and plain

func Truncate

func Truncate(s string, length int, tail string) string

Truncate truncates a string to a given cell width, appending tail if the string was truncated. ANSI escape codes are preserved.

Example
fmt.Println(ansi.Truncate("Hello, World!", 8, "…"))

Output:

Hello, …

func WrapHard

func WrapHard(s string, width int) string

WrapHard wraps s at exactly width columns, breaking mid-word if needed. ANSI styles are preserved.

Example
fmt.Println(ansi.WrapHard("the quick brown fox", 6))

Output:

the qu
ick br
own fo
x

func WrapSoft

func WrapSoft(s string, width int) string

WrapSoft wraps s to fit within width columns, breaking at space boundaries. Words longer than width are hard-wrapped. ANSI styles are preserved.

Example
fmt.Println(ansi.WrapSoft("the quick brown fox jumps over the lazy dog", 12))

Output:

the quick
brown fox
jumps over
the lazy dog

type ANSI

ANSI produces ANSI-aware output, falling back to plain text when the output is not a terminal.

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

func Auto
func Auto(files ...*os.File) *ANSI

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 Force
func Force() *ANSI

Force creates an ANSI with ANSI output unconditionally enabled.

func Never
func Never() *ANSI

Never creates an ANSI with ANSI output unconditionally disabled.

func New
func New(opts ...Option) *ANSI

New creates an ANSI with the given options.

func (w *ANSI) Hyperlink(url, text string) string

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.

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)

func (*ANSI) Terminal
func (w *ANSI) Terminal() bool

Terminal reports whether the output target is a terminal.

type HyperlinkFallback

HyperlinkFallback controls how hyperlinks render when the output is not a terminal.

type HyperlinkFallback int

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 Method

Method controls how display width is calculated.

type Method = xansi.Method

type Option

Option configures an ANSI.

type Option func(*ANSI)

func WithHyperlinkFallback
func WithHyperlinkFallback(fallback HyperlinkFallback) Option

WithHyperlinkFallback sets how hyperlinks render when the output is not a terminal.

func WithTerminal
func WithTerminal(v bool) Option

WithTerminal sets whether the output target is a terminal.

type WrapOption

WrapOption configures a Wrapper.

type WrapOption func(*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

Wrapper wraps text to a configured width, preserving ANSI escape sequences.

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

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.

w := ansi.NewWrapper(ansi.WithWidth(10), ansi.WithBreakpoints("-"))
fmt.Println(w.Wrap("a-very-long-flag-name"))

Output:

a-very-
long-flag-
name

func (*Wrapper) Wrap
func (w *Wrapper) Wrap(s string) string

Wrap wraps s according to the configured mode and width. Returns s unchanged if the effective width is < 1.

Documentation

Overview

Package ansi provides ANSI-aware text wrapping, hyperlinks, and TTY fallback.

Index

Examples

Constants

View Source
const (
	EraseLineRight    = xansi.EraseLineRight
	EraseLineLeft     = xansi.EraseLineLeft
	EraseEntireLine   = xansi.EraseEntireLine
	EraseScreenBelow  = xansi.EraseScreenBelow
	EraseScreenAbove  = xansi.EraseScreenAbove
	EraseEntireScreen = xansi.EraseEntireScreen
)

Erase constants (delegated).

View Source
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.

View Source
const (
	ShowCursor = xansi.ShowCursor
	HideCursor = xansi.HideCursor
)

Cursor visibility (DECTCEM).

View Source
const (
	SaveCursorPosition    = xansi.SaveCurrentCursorPosition
	RestoreCursorPosition = xansi.RestoreCurrentCursorPosition
)

Cursor save/restore (SCOSC / SCORC).

View Source
const (
	Focus = xansi.Focus
	Blur  = xansi.Blur
)

Focus reporting events (terminal → app, when focus events are enabled).

Alt-screen buffer (DEC 1049: also saves/restores cursor).

View Source
const (
	EnableBracketedPaste  = xansi.SetModeBracketedPaste
	DisableBracketedPaste = xansi.ResetModeBracketedPaste
)

Bracketed paste mode (DEC 2004).

View Source
const (
	EnableFocusEvents  = xansi.SetModeFocusEvent
	DisableFocusEvents = xansi.ResetModeFocusEvent
)

Focus event reporting mode (DEC 1004).

View Source
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.

View Source
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.

View Source
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.

View Source
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
View Source
const (
	WcWidth       = xansi.WcWidth
	GraphemeWidth = xansi.GraphemeWidth
)

Display width methods.

View Source
const CSI = "\x1b["

CSI is the Control Sequence Introducer prefix (ESC + `[`). Exported for callers that parse or construct their own CSI-family sequences.

View Source
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.

View Source
const CursorHomePosition = xansi.CursorHomePosition

CursorHomePosition moves the cursor to row 1, column 1 (`"\x1b[H"`).

View Source
const RequestNameVersion = xansi.RequestNameVersion

RequestNameVersion is the XTVERSION query (`"\x1b[>q"`): asks the terminal for its name and version. Complements the DA1 query.

View Source
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

func CursorBackward(n int) string

CursorBackward returns the CUB sequence: move cursor left `n` columns.

func CursorDown

func CursorDown(n int) string

CursorDown returns the CUD sequence: move cursor down `n` lines.

func CursorForward

func CursorForward(n int) string

CursorForward returns the CUF sequence: move cursor right `n` columns.

func CursorHorizontalAbsolute

func CursorHorizontalAbsolute(col int) string

CursorHorizontalAbsolute returns the CHA sequence: move to column `col` on the current line.

func CursorNextLine

func CursorNextLine(n int) string

CursorNextLine returns the CNL sequence: move down `n` lines and to column 1.

func CursorPosition

func CursorPosition(col, row int) string

CursorPosition returns the CUP sequence: move to (`col`, `row`). Coordinates are 1-based.

func CursorPreviousLine

func CursorPreviousLine(n int) string

CursorPreviousLine returns the CPL sequence: move up `n` lines and to column 1.

func CursorUp

func CursorUp(n int) string

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

func DeleteCharacter(n int) string

DeleteCharacter returns the DCH sequence: delete `n` characters at the cursor, pulling subsequent characters left.

func DeleteLine

func DeleteLine(n int) string

DeleteLine returns the DL sequence: delete `n` lines starting at the cursor, pulling subsequent lines up.

func EraseCharacter

func EraseCharacter(n int) string

EraseCharacter returns the ECH sequence: erase `n` characters from the cursor position (no cursor movement).

func EraseDisplay

func EraseDisplay(n int) string

EraseDisplay returns the ED sequence. `n` selects the variant: 0 = below cursor, 1 = above cursor, 2 = entire screen.

func EraseLine

func EraseLine(n int) string

EraseLine returns the EL sequence. `n` selects the variant: 0 = right of cursor, 1 = left of cursor, 2 = entire line.

func InsertCharacter

func InsertCharacter(n int) string

InsertCharacter returns the ICH sequence: insert `n` blank characters at the cursor, shifting existing characters right.

func InsertLine

func InsertLine(n int) string

InsertLine returns the IL sequence: insert `n` blank lines at the cursor, pushing existing lines down.

func ScrollDown

func ScrollDown(n int) string

ScrollDown returns the SD sequence: scroll viewport down `n` lines (content moves down; new blank lines appear at the top).

func ScrollUp

func ScrollUp(n int) string

ScrollUp returns the SU sequence: scroll viewport up `n` lines (content moves up; new blank lines appear at the bottom).

func SetCursorStyle

func SetCursorStyle(style int) string

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

func SetIconName(s string) string

SetIconName sets the icon/tab name only (OSC 1).

func SetIconNameWindowTitle

func SetIconNameWindowTitle(s string) string

SetIconNameWindowTitle sets both the icon name and window title in a single sequence (OSC 0).

func SetWindowTitle

func SetWindowTitle(s string) string

SetWindowTitle sets the terminal window title only (OSC 2).

func StringWidth

func StringWidth(s string) int

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

func Strip(s string) string

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

func Truncate(s string, length int, tail string) string

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

func WrapHard(s string, width int) string

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

func WrapSoft(s string, width int) string

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

func Auto(files ...*os.File) *ANSI

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 Force

func Force() *ANSI

Force creates an ANSI with ANSI output unconditionally enabled.

func Never

func Never() *ANSI

Never creates an ANSI with ANSI output unconditionally disabled.

func New

func New(opts ...Option) *ANSI

New creates an ANSI with the given options.

func (w *ANSI) Hyperlink(url, text string) string

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.

func (*ANSI) Terminal

func (w *ANSI) Terminal() bool

Terminal reports whether the output target is a terminal.

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 Method

type Method = xansi.Method

Method controls how display width is calculated.

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

func WithTerminal(v bool) Option

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

func (*Wrapper) Wrap

func (w *Wrapper) Wrap(s string) string

Wrap wraps `s` according to the configured mode and width. Returns `s` unchanged if the effective width is < 1.

Jump to

Keyboard shortcuts

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