Konsoru is a comprehensive, zero-dependency Go library for ANSI terminal control that provides type-safe APIs for cursor movement, color handling (4-bit, 8-bit, and 24-bit true color), text styling, screen management, input processing, and a fluent builder pattern, along with a progress bar component featuring automatic width detection and ANSI-aware string length calculation.
- Go 100%
# Previous message: ci: add GitHub Actions workflow for pull request validation |
||
|---|---|---|
| .github/workflows | ||
| ansi | ||
| bar | ||
| chain | ||
| cmd/konsoru-demo | ||
| color | ||
| cursor | ||
| input | ||
| screen | ||
| style | ||
| util | ||
| .gitignore | ||
| .golangci.yml | ||
| .pre-commit-config.yaml | ||
| .secrets.baseline | ||
| go.mod | ||
| README.md | ||
Table of Contents
- Konsoru ANSI Terminal Library
- Overview
- Core Design Principles
- Module Structure
- API Reference
- Complete Example
- Testing Strategy
- Performance Considerations
- Compatibility Notes
- Roadmap
Konsoru ANSI Terminal Library
Overview
Konsoru provides complete ANSI escape sequence functionality for terminal applications in Go. The library is designed to be: comprehensive, type‑safe, and zero‑dependency.
Core Design Principles
- Complete Coverage: Every ANSI control sequence documented in ECMA‑48 and common extensions
- Layered API: From raw codes to high‑level convenience functions
- Safety: All parameters validated, buffer overflow protection
- Performance: Zero allocations in hot paths, builder pattern support
Module Structure
konsoru/
├── ansi/ # Low‑level sequence definitions
├── cursor/ # Cursor movement and positioning
├── color/ # Color utilities (4‑bit, 8‑bit, 24‑bit)
├── style/ # Text attributes (bold, italic, etc.)
├── screen/ # Screen control (clear, scroll, alternative buffers)
├── input/ # Terminal input handling (keyboard, mouse)
├── util/ # Utilities (OS detection, terminal capabilities, etc)
├── chain/ # Fluent API builder pattern
└── bar/ # Progress bar rendering
API Reference
Core ANSI Sequences ansi/ansi.go
// Control Sequence Introducer - all sequences start with this
const CSI = "\033["
// Operating System Command
const OSC = "\033]"
// Device Control String
const DCS = "\033P"
// Single character controls
const (
BEL = "\a" // Bell
BS = "\b" // Backspace
HT = "\t" // Horizontal Tab
LF = "\n" // Line Feed
VT = "\v" // Vertical Tab
FF = "\f" // Form Feed
CR = "\r" // Carriage Return
)
// C0 and C1 control codes
type ControlCode byte
const (
NUL ControlCode = 0x00
ESC ControlCode = 0x1B
DEL ControlCode = 0x7F
// ... all 32 C0 and C1 codes
)
Cursor Control cursor/cursor.go
package cursor
// Absolute positioning
func MoveTo(row, col int) string
func MoveToHome() string
// Relative movement
func Up(n int) string
func Down(n int) string
func Forward(n int) string
func Backward(n int) string
// Save/Restore
func SavePosition() string // DECSC
func RestorePosition() string // DECRC
// Visibility
func Show() string
func Hide() string
// Shape control (xterm extensions)
func SetShape(shape CursorShape) string
type CursorShape int
const (
ShapeDefault CursorShape = iota
ShapeBlock
ShapeUnderline
ShapeBar
)
// Query functions (require input parsing)
func RequestPosition() string // DSR 6
func RequestSize() string // DSR 18
Colors color/color.go
package color
// 4‑bit colors (ANSI 16 colors)
type Color4 int
const (
Black Color4 = iota
Red
Green
Yellow
Blue
Magenta
Cyan
White
BrightBlack
// ... etc
)
// 8‑bit colors (256 colors)
type Color8 uint8
// 24‑bit colors (true color)
type RGB struct {
R, G, B uint8
}
// Foreground color setters
func Fg4(color Color4) string
func Fg8(index Color8) string
func Fg24(rgb RGB) string
func FgHex(hex string) (string, error)
// Background color setters (same pattern)
func Bg4(color Color4) string
func Bg8(index Color8) string
func Bg24(rgb RGB) string
// Color reset
func ResetFg() string
func ResetBg() string
// Resets foreground, background, and text attributes
func ResetAll() string
// Palette management (xterm OSC sequences)
func SetPaletteColor(index int, rgb RGB) string
func GetPaletteColor(index int) string // Query sequence
// Color conversion utilities
func RGBTo256(rgb RGB) Color8
func Color8ToRGB(c Color8) RGB
func HexToRGB(hex string) (RGB, error)
Text Attributes style/style.go
package style
// SGR (Select Graphic Rendition) parameters
type Attribute int
const (
ResetAll Attribute = 0
Bold Attribute = 1
Faint Attribute = 2
Italic Attribute = 3
Underline Attribute = 4
BlinkSlow Attribute = 5
BlinkFast Attribute = 6
Inverse Attribute = 7
Conceal Attribute = 8
Strike Attribute = 9
// Font selection (10‑20)
// Fraktur, double underline, etc.
)
// Basic setters
func Set(attr Attribute) string
func SetMultiple(attrs ...Attribute) string
// Convenience functions
func BoldText(text string) string
func UnderlineText(text string) string
func ErrorText(text string) string // Red + bold
func SuccessText(text string) string // Green + bold
// Style reset
func ResetAttribute(attr Attribute) string
// Font selection (rarely used but complete)
func SetFont(n int) string // n: 0‑9 for alternative fonts
Screen Control screen/screen.go
package screen
// Clearing operations
func ClearScreen() string
func ClearLine() string
func ClearToEndOfScreen() string
func ClearToEndOfLine() string
func ClearToBeginningOfScreen() string
func ClearToBeginningOfLine() string
// Scrolling
func ScrollUp(n int) string
func ScrollDown(n int) string
func SetScrollRegion(top, bottom int) string
func ResetScrollRegion() string
// Screen buffers (xterm alternative buffers)
func UseAlternateBuffer() string
func UseMainBuffer() string
// Title setting (OSC sequences)
func SetTitle(title string) string
func SetIconName(name string) string
// Screen size queries
func RequestScreenSize() string
// Cursor position reporting enable/disable
EnableCursorPositionReport() string
DisableCursorPositionReport() string
Input Handling input/input.go
package input
// Input modes
func EnableMouse(mode MouseMode) string
func DisableMouse() string
type MouseMode int
const (
MouseOff MouseMode = iota
MouseClick
MouseDrag
MouseMotion
)
// Keyboard modes
func EnableApplicationKeys() string
func EnableNormalKeys() string
// Bracketed paste mode
func EnableBracketedPaste() string
func DisableBracketedPaste() string
// Focus tracking
func EnableFocusTracking() string
func DisableFocusTracking() string
// Input parsing (for responses)
type Event interface{}
type KeyEvent struct {
Char rune
Code KeyCode
Mod Modifier
Alt bool
Ctrl bool
Shift bool
}
type MouseEvent struct {
X, Y int
Button MouseButton
Down bool
Mod Modifier
}
// Parser for terminal responses
func ParseSequence(data []byte) (Event, int, error)
Progress Bar bar/bar.go
package bar
// Bar is the main progress‑bar struct.
type Bar struct {
// Total is the total amount of work (e.g., total bytes, total items).
Total int64
// Current is the current progress (0 <= Current <= Total).
Current int64
// Width is the desired display width in characters. If <=0, the width is
// automatically determined from the terminal size (respecting any margins).
Width int
// Template defines the bar layout. It may contain placeholders:
// {{.Bar}} – the actual progress bar (filled/unfilled characters)
// {{.Percent}} – percentage (formatted as "xx.x%")
// {{.Current}} – current value (formatted with HumanSize/HumanTime)
// {{.Total}} – total value (formatted with HumanSize/HumanTime)
// {{.Speed}} – rate per second (formatted appropriately)
// {{.Elapsed}} – elapsed time (formatted with HumanTime)
// {{.Remain}} – estimated remaining time (formatted with HumanTime)
// {{.ETA}} – estimated time of completion (formatted as time.Time)
Template string
// FilledChar is the character(s) used for the filled portion of the bar.
// May contain ANSI sequences (color, style). The visible width counted.
FilledChar string
// EmptyChar is the character(s) used for the unfilled portion.
// May contain ANSI sequences.
EmptyChar string
// LeftEnd, RightEnd are optional delimiters for the bar ends.
LeftEnd string
RightEnd string
// ShowPercent, ShowCounts, ShowSpeed, ShowTime control visibility of components.
ShowPercent bool
ShowCounts bool
ShowSpeed bool
ShowTime bool
// StartTime records when the bar was first advanced; used for speed/ETA.
StartTime time.Time
// AutoTrim ensures the rendered line does not exceed terminal width.
// If true, the bar will shorten components (or omit them) to fit.
AutoTrim bool
}
// New creates a Bar with sensible defaults.
func New(total int64) *Bar
// SetTemplate sets a custom template string.
func (b *Bar) SetTemplate(
tmpl string) *Bar
// SetWidth sets the desired bar width.
// Use 0 for auto‑detection.
func (b *Bar) SetWidth(
w int) *Bar
// SetChars sets the characters used for filled and empty portions.
func (b *Bar) SetChars(filled, empty string) *Bar
// SetEnds sets the left and right end delimiters.
func (b *Bar) SetEnds(left, right string) *Bar
// Advance increments the current progress by n.
func (b *Bar) Advance(n int64)
// Set sets the current progress to n.
func (b *Bar) Set(n int64)
// String renders the progress bar as a string.
// It accounts for ANSI sequences in FilledChar, EmptyChar, ends, and template
// components when calculating visible width, ensuring the output fits the
// terminal width (if AutoTrim is enabled). Uses util.VisibleLength internally.
func (b *Bar) String() string
// WriteTo writes the bar directly to an io.Writer, updating the line in place
// (using cursor movement) if the output is a terminal.
func (b *Bar) WriteTo(w io.Writer) (int, error)
// Finish renders a final complete bar, optionally with a “done” message.
func (b *Bar) Finish(message string) string
// Example template:
// "{{.Bar}} {{.Percent}} | {{.Current}}/{{.Total}} | {{.Speed}}/s | {{.Elapsed}}<{{.Remain}}"
Fluent Builder API chain/chain.go
package chain
type Builder struct {
buf strings.Builder
}
func New() *Builder
func (b *Builder) MoveTo(row, col int) *Builder
func (b *Builder) Up(n int) *Builder
func (b *Builder) Fg(color color.Color4) *Builder
func (b *Builder) FgRGB(r, g, b uint8) *Builder
func (b *Builder) Bold() *Builder
func (b *Builder) Write(text string) *Builder
func (b *Builder) Writef(format string, args ...any) *Builder
func (b *Builder) Reset() *Builder
func (b *Builder) String() string
func (b *Builder) WriteTo(w io.Writer) (int, error)
// Example usage:
// chain.New().MoveTo(5, 10).Fg(color.Red).Bold().Write("Hello").String()
Utility Functions util/util.go
package util
// Terminal detection
func IsTerminal(fd uintptr) bool
func GetTerminalSize() (rows, cols int, err error)
func SupportsTrueColor() bool
func Supports256Colors() bool
// Sequence utilities
func StripANSI(s string) string
func VisibleLength(s string) int // Length without ANSI codes
func WrapANSI(s string, width int) string
// Human‑friendly formatting
// HumanTime formats a duration given in seconds into a readable string,
// e.g., "5m30s", "1h2m", "3d12h".
func HumanTime(seconds float64) string
// HumanSize formats a byte count into a readable string with appropriate unit,
// e.g., "1.2KB", "4.5MB", "7.8GB". Uses decimal (power‑of‑1000) units.
func HumanSize(bytes int64) string
// Writer wrapper
type Writer struct {
io.Writer
isTerminal bool
}
func (w *Writer) WriteANSI(seq string) (int, error)
func (w *Writer) WriteStyled(text, style string) (int, error)
// Safe output (checks if output is terminal)
func SafeOutput(w io.Writer) *Writer
Complete Example
package main
import (
"fmt"
"github.com/yourname/konsoru/color"
"github.com/yourname/konsoru/cursor"
"github.com/yourname/konsoru/style"
"github.com/yourname/konsoru/chain"
"github.com/yourname/konsoru/bar"
"time"
)
func main() {
// Low‑level usage
fmt.Print(
cursor.MoveTo(10, 20),
color.Fg24(color.RGB{255, 0, 0}),
style.Bold,
"ERROR: Something failed",
style.ResetAll,
cursor.MoveTo(11, 20),
)
// Fluent builder
msg := chain.New().
MoveTo(5, 10).
FgRGB(255, 200, 0).
Bold().
Write("Welcome to ").
FgRGB(100, 200, 255).
Write("Konsoru").
Reset().
String()
fmt.Print(msg)
// High‑level helpers
fmt.Println(style.ErrorText("File not found"))
fmt.Println(style.SuccessText("Operation completed"))
// Progress bar
b := bar.New(1000).
SetWidth(0). // auto‑width from terminal
SetChars("█", "░").
SetEnds("[", "]").
SetTemplate("{{.Bar}} {{.Percent}} | {{.Current}}/{{.Total}}")
for i := 0; i <= 1000; i += 50 {
b.Set(int64(i))
fmt.Print("\r" + b.String())
time.Sleep(100 * time.Millisecond)
}
fmt.Println("\n" + b.Finish("Done"))
}
Testing Strategy
- Unit tests for each sequence generator
- Golden tests for complex output
- Integration tests with actual terminal emulators
- Fuzz testing for input parsing
- Bar tests with varying terminal widths and ANSI‑laden characters
Performance Considerations
- All sequence generators return strings (no allocations for constants)
- Builder pattern reuses buffer
- Input parser works on slices, avoids copying
- Bar rendering caches width and visible‑length calculations
Compatibility Notes
- Follows ECMA‑48 standard
- Includes common xterm extensions
- Clearly documents non‑standard sequences
- Provides fallbacks where possible
- Bar respects terminal width and ANSI‑sequence‑aware length calculation
Roadmap
- Phase 1: Cursor, colors, basic attributes
- Phase 2: Screen control, input handling
- Phase 3: Fluent API, utilities, progress bar
- Phase 4: Windows compatibility layer