termhyo

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Dec 15, 2025 License: MIT Imports: 7 Imported by: 0

README

termhyo

Go Reference Go Report Card GitHub release License

termhyo is a Go package for beautifully displaying tabular data. The name combines "terminal" and the Japanese word "表 (hyo)" meaning "table", and is specialized for terminal display.

Features

  • Two rendering modes: Flexible display with BufferedMode and StreamingMode
  • Multiple border styles: Choose from Box Drawing, ASCII, Rounded, Double, Minimal, and VerticalBar (only vertical | separators)
  • Automatic width calculation: Automatic column width adjustment and alignment
  • Unicode support: Proper handling of multibyte characters, combining characters, emojis, and East Asian text
  • Interface design: Extensible renderer architecture

Installation

To install termhyo, use go get:

go get github.com/noborus/termhyo
Requirements
  • Go 1.23 or later

Basic Usage

Simple Table
package main

import (
    "os"
    "github.com/noborus/termhyo"
)

func main() {
    columns := []termhyo.Column{
        {Title: "ID", Align: termhyo.Right},
        {Title: "Name", Align: termhyo.Left},
        {Title: "Score", Align: termhyo.Center},
    }

    table := termhyo.NewTable(os.Stdout, columns)
    table.AddRow("1", "Alice", "85")
    table.AddRow("2", "Bob", "92")
    table.Render()
}
Changing Border Style
table := termhyo.NewTable(os.Stdout, columns, termhyo.Border(termhyo.ASCIIStyle))
Text Alignment

termhyo provides type-safe alignment options:

// Available alignment constants
termhyo.Left     // Left-aligned text
termhyo.Center   // Center-aligned text
termhyo.Right    // Right-aligned text
termhyo.Default  // Default/unspecified alignment (defaults to left)

// Column-level alignment
columns := []termhyo.Column{
    {Title: "ID", Align: termhyo.Right},
    {Title: "Name", Align: termhyo.Left},
    {Title: "Score", Align: termhyo.Center},
}

// Cell-level alignment (overrides column alignment)
table.AddRowCells(
    termhyo.Cell{Content: "1", Align: termhyo.Center},
    termhyo.Cell{Content: "Alice"},  // Uses column alignment
    termhyo.Cell{Content: "85"},
)
Custom Border Configuration
// Create custom border configuration
customConfig := termhyo.TableBorderConfig{
    Chars: map[string]string{
        "horizontal": "=",
        "vertical":   "|",
        "cross":      "+",
        // ... other border characters
    },
    Top:      false, // No top border
    Bottom:   false, // No bottom border
    Middle:   true,  // Keep header separator
    Left:     false, // No left border
    Right:    false, // No right border
    Vertical: true,  // Keep internal column separators
    Padding:  true,  // Enable content padding
}

table := termhyo.NewTable(os.Stdout, columns, termhyo.BorderConfig(customConfig))

Running Examples

You can run various example programs to see termhyo in action. See the examples directory for more.

Rendering Modes

BufferedMode
  • Collects all rows and renders them in batch
  • Automatic width calculation and alignment possible
  • Automatically selected when column width is 0 (auto) or alignment is enabled
StreamingMode
  • Renders immediately as rows are added
  • Automatically selected when fixed width and alignment disabled
  • Memory efficient

Border Styles

  • BoxDrawingStyle: Unicode Box Drawing characters (default)
  • ASCIIStyle: ASCII characters
  • RoundedStyle: Rounded corner style
  • DoubleStyle: Double line style
  • MinimalStyle: Minimal border
  • VerticalBarStyle: Only vertical bar separators (|), no outer borders
  • MarkdownStyle: Markdown table format
  • TSVStyle: Tab-separated values format

License

MIT License

Documentation

Overview

Package termhyo provides a flexible and feature-rich library for rendering beautiful tables in terminal applications.

The name combines "terminal" and the Japanese word "表 (hyo)" meaning "table".

Features

- Multiple rendering modes: Buffered and Streaming - Rich border styling: BoxDrawing, ASCII, Rounded, Double, Minimal, VerticalBar (only |), Markdown, TSV, and custom borders - Functional Option Pattern for table configuration (Border, Header, AutoAlign, BorderConfig, etc.) - Comprehensive header styling with ANSI escape sequences and true color - Unicode and multi-byte character support (East Asian, combining, emoji, etc.) - Automatic column width calculation and type-safe alignment - Fine-grained border control (show/hide top, bottom, left, right, vertical, middle) - Extensible renderer interface

Basic Usage

columns := []termhyo.Column{
	{Title: "ID", Align: termhyo.Right},
	{Title: "Name", Align: termhyo.Left},
	{Title: "Score", Align: termhyo.Center},
}
table := termhyo.NewTable(os.Stdout, columns)
table.AddRow("1", "Alice", "85")
table.AddRow("2", "Bob", "92")
table.Render()

Border Style Example

table := termhyo.NewTable(os.Stdout, columns, termhyo.Border(termhyo.VerticalBarStyle), termhyo.AutoAlign(false))

Header Styling Example

headerStyle := termhyo.HeaderStyle{
	Bold:            true,
	ForegroundColor: termhyo.AnsiWhite,
	BackgroundColor: termhyo.AnsiBgBlue,
}
table.SetHeaderStyle(headerStyle)

Custom Border Example

customConfig := termhyo.TableBorderConfig{
	Chars: map[string]string{"vertical": "|"},
	Top: false, Bottom: false, Left: false, Right: false, Vertical: true,
}
table := termhyo.NewTable(os.Stdout, columns, termhyo.BorderConfig(customConfig))

Rendering Modes

- BufferedMode: Used when columns have auto-width (Width: 0) or alignment is enabled. Calculates optimal widths. - StreamingMode: Used when all columns have fixed widths and alignment is disabled. Memory efficient.

Character & Color Support

- Handles ASCII, Unicode, multi-byte, combining, emoji, and ANSI escape sequences - Correct display width calculation for all character types - Full ANSI color, 256-color, and 24-bit true color for headers - Text formatting: Bold, Italic, Underline, Reverse, etc.

See Also

See the examples/ directory for comprehensive usage:

- Basic table creation - Header styling variations - Border style demonstrations (including VerticalBarStyle) - Unicode and multilingual support - Markdown/TSV output - Streaming mode usage - Custom border configuration

Index

Constants

View Source
const (
	// Text formatting.
	AnsiReset     = "\x1b[0m"
	AnsiBold      = "\x1b[1m"
	AnsiDim       = "\x1b[2m"
	AnsiItalic    = "\x1b[3m"
	AnsiUnderline = "\x1b[4m"
	AnsiBlink     = "\x1b[5m"
	AnsiReverse   = "\x1b[7m"
	AnsiStrike    = "\x1b[9m"

	// Foreground colors (text colors).
	AnsiBlack   = "\x1b[30m"
	AnsiRed     = "\x1b[31m"
	AnsiGreen   = "\x1b[32m"
	AnsiYellow  = "\x1b[33m"
	AnsiBlue    = "\x1b[34m"
	AnsiMagenta = "\x1b[35m"
	AnsiCyan    = "\x1b[36m"
	AnsiWhite   = "\x1b[37m"

	// Bright foreground colors.
	AnsiBrightBlack   = "\x1b[90m"
	AnsiBrightRed     = "\x1b[91m"
	AnsiBrightGreen   = "\x1b[92m"
	AnsiBrightYellow  = "\x1b[93m"
	AnsiBrightBlue    = "\x1b[94m"
	AnsiBrightMagenta = "\x1b[95m"
	AnsiBrightCyan    = "\x1b[96m"
	AnsiBrightWhite   = "\x1b[97m"

	// Background colors.
	AnsiBgBlack   = "\x1b[40m"
	AnsiBgRed     = "\x1b[41m"
	AnsiBgGreen   = "\x1b[42m"
	AnsiBgYellow  = "\x1b[43m"
	AnsiBgBlue    = "\x1b[44m"
	AnsiBgMagenta = "\x1b[45m"
	AnsiBgCyan    = "\x1b[46m"
	AnsiBgWhite   = "\x1b[47m"

	// Bright background colors.
	AnsiBgBrightBlack   = "\x1b[100m"
	AnsiBgBrightRed     = "\x1b[101m"
	AnsiBgBrightGreen   = "\x1b[102m"
	AnsiBgBrightYellow  = "\x1b[103m"
	AnsiBgBrightBlue    = "\x1b[104m"
	AnsiBgBrightMagenta = "\x1b[105m"
	AnsiBgBrightCyan    = "\x1b[106m"
	AnsiBgBrightWhite   = "\x1b[107m"
)

ANSI escape sequences for text formatting.

Variables

View Source
var (
	// ErrNoColumns is returned when trying to render a table with no columns defined.
	ErrNoColumns = errors.New("no columns defined")
	// ErrNoHeader is returned when trying to render a table without a header.
	ErrNoHeader = errors.New("header is required")
	// ErrNoMarkdownHeader is returned when trying to render a markdown table without a header.
	ErrNoMarkdownHeader = errors.New("markdown table requires at least one non-empty header")
	// ErrTableAlreadyRendered is returned when trying to render a table that has already been rendered.
	ErrTableAlreadyRendered = errors.New("table has already been rendered")
	// ErrAddAfterRender is returned when trying to add a row after rendering.
	ErrAddAfterRender = errors.New("cannot add row after table has been rendered")
)

Functions

func BgRGB256

func BgRGB256(colorCode int) string

BgRGB256 returns a 256-color ANSI code for background.

func RGB256

func RGB256(colorCode int) string

RGB256 returns a 256-color ANSI code for foreground.

func StringWidth

func StringWidth(s string) int

StringWidth returns the display width of a string on terminal. This properly handles multibyte characters, combining characters, emojis, and ANSI escape sequences. This is the public version of stringWidth for external use.

func TrueColorBg

func TrueColorBg(r, g, b int) string

TrueColorBg returns a true color (24-bit) ANSI code for background.

func TrueColorFg

func TrueColorFg(r, g, b int) string

TrueColorFg returns a true color (24-bit) ANSI code for foreground.

Types

type Alignment

type Alignment string

Alignment represents text alignment options.

const (
	// Default represents default/unspecified alignment.
	Default Alignment = ""
	// Left aligns text to the left.
	Left Alignment = "left"
	// Center aligns text to the center.
	Center Alignment = "center"
	// Right aligns text to the right.
	Right Alignment = "right"
)

func (Alignment) String

func (a Alignment) String() string

String returns the string representation of the alignment.

type BorderStyle

type BorderStyle string

BorderStyle defines different border styles.

const (
	// BoxDrawingStyle uses Unicode box drawing characters.
	BoxDrawingStyle BorderStyle = "box"
	// ASCIIStyle uses ASCII characters.
	ASCIIStyle BorderStyle = "ascii"
	// RoundedStyle uses rounded corners.
	RoundedStyle BorderStyle = "rounded"
	// DoubleStyle uses double line box drawing.
	DoubleStyle BorderStyle = "double"
	// MinimalStyle uses minimal borders.
	MinimalStyle BorderStyle = "minimal"
	// VerticalBarStyle uses only vertical bar separators (|), no outer borders.
	VerticalBarStyle BorderStyle = "vertical_bar"
	// MarkdownStyle uses Markdown table format.
	MarkdownStyle BorderStyle = "markdown"
	// TSVStyle uses tab separators only.
	TSVStyle BorderStyle = "tsv"
)

type Buffered

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

Buffered implements buffered rendering strategy.

func (*Buffered) AddRow

func (r *Buffered) AddRow(table *Table, row Row) error

AddRow adds a row to the buffered renderer.

func (*Buffered) IsRendered

func (r *Buffered) IsRendered() bool

IsRendered checks if the table has been rendered.

func (*Buffered) Render

func (r *Buffered) Render(table *Table) error

Render renders the buffered content all at once.

type Cell

type Cell struct {
	Content string    // Cell content
	Align   Alignment // Cell-specific alignment override
}

Cell represents a table cell.

type Column

type Column struct {
	Title    string    // Column header title
	Width    int       // Column width (0 = auto-width)
	MaxWidth int       // Maximum width for auto-width columns (0 = no limit)
	Align    Alignment // Alignment: Left, Center, Right
}

Column defines column properties.

type HeaderStyle

type HeaderStyle struct {
	// Text formatting
	Bold      bool
	Underline bool
	Italic    bool
	Dim       bool
	Blink     bool
	Reverse   bool
	Strike    bool

	// Colors
	ForegroundColor string // ANSI color code or empty for default
	BackgroundColor string // ANSI color code or empty for default

	// Custom escape sequences
	CustomPrefix string // Custom ANSI sequence to prepend
	CustomSuffix string // Custom ANSI sequence to append
}

HeaderStyle defines the styling for table headers.

func BoldHeaderStyle

func BoldHeaderStyle() HeaderStyle

BoldHeaderStyle returns a header style with bold text.

func ColoredHeaderStyle

func ColoredHeaderStyle(fgColor, bgColor string) HeaderStyle

ColoredHeaderStyle returns a header style with specified colors.

func DefaultHeaderStyle

func DefaultHeaderStyle() HeaderStyle

DefaultHeaderStyle returns a default header style with bold and underline.

func UnderlineHeaderStyle

func UnderlineHeaderStyle() HeaderStyle

UnderlineHeaderStyle returns a header style with underlined text.

func (HeaderStyle) ApplyStyle

func (hs HeaderStyle) ApplyStyle(text string) string

ApplyStyle applies the header style to the given text.

func (HeaderStyle) Combine

func (hs HeaderStyle) Combine(other HeaderStyle) HeaderStyle

Combine combines this header style with another, with the other style taking precedence.

type MarkdownRenderer

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

MarkdownRenderer implements Markdown table format with streaming support.

func (*MarkdownRenderer) AddRow

func (r *MarkdownRenderer) AddRow(_ *Table, row Row) error

AddRow adds a row for markdown rendering (buffered mode for width calculation).

func (*MarkdownRenderer) IsRendered

func (r *MarkdownRenderer) IsRendered() bool

IsRendered returns whether the table has been rendered.

func (*MarkdownRenderer) Render

func (r *MarkdownRenderer) Render(table *Table) error

Render renders any remaining content (for streaming, this is just cleanup).

type RenderMode

type RenderMode int

RenderMode defines when to start rendering.

const (
	// BufferedMode: collect all rows before rendering (for auto-width).
	BufferedMode RenderMode = iota
	// StreamingMode: render immediately (for fixed-width).
	StreamingMode
)

func (RenderMode) String

func (m RenderMode) String() string

String returns the string representation of the RenderMode.

type Renderer

type Renderer interface {
	AddRow(table *Table, row Row) error
	Render(table *Table) error
	IsRendered() bool
}

Renderer defines the interface for different rendering strategies.

type Row

type Row struct {
	Cells []Cell // Row cells
}

Row represents a table row.

type Streaming

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

Streaming implements streaming rendering strategy.

func (*Streaming) AddRow

func (r *Streaming) AddRow(table *Table, row Row) error

AddRow adds a row to the streaming renderer.

func (*Streaming) IsRendered

func (r *Streaming) IsRendered() bool

IsRendered checks if the table has been rendered.

func (*Streaming) Render

func (r *Streaming) Render(table *Table) error

Render renders the streaming content, typically just the footer.

type Table

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

Table represents the main table structure.

func NewTable

func NewTable(writer io.Writer, columns []Column, opts ...TableOption) *Table

NewTable creates a new table with the given columns and optional configuration.

This function uses the Functional Option Pattern:

table := termhyo.NewTable(os.Stdout, columns, termhyo.Border(termhyo.BoxDrawingStyle), termhyo.Header(headerStyle), ...)

You can specify border style, header style, alignment, etc. by passing option functions.

Example:

table := termhyo.NewTable(os.Stdout, columns, termhyo.Border(termhyo.DoubleStyle), termhyo.AutoAlign(false))

This is the recommended way to create and configure tables in termhyo.

func (*Table) AddRow

func (t *Table) AddRow(cells ...string) error

AddRow adds a row to the table.

func (*Table) AddRowCells

func (t *Table) AddRowCells(cells ...Cell) error

AddRowCells adds a row with detailed cell configuration.

func (*Table) CalculateColumnWidths

func (t *Table) CalculateColumnWidths()

CalculateColumnWidths calculates optimal widths for auto-width columns.

func (*Table) GetAutoAlign added in v0.2.0

func (t *Table) GetAutoAlign() bool

GetAutoAlign returns the current auto-align setting.

func (*Table) GetBorderConfig

func (t *Table) GetBorderConfig() TableBorderConfig

GetBorderConfig returns the current border configuration.

func (*Table) GetBorderStyle

func (t *Table) GetBorderStyle() BorderStyle

GetBorderStyle returns the current border style.

func (*Table) GetHeaderStyle

func (t *Table) GetHeaderStyle() HeaderStyle

GetHeaderStyle returns the current header style.

func (*Table) Render

func (t *Table) Render() error

Render renders the complete table.

func (*Table) RenderBorderLine

func (t *Table) RenderBorderLine(position string) error

RenderBorderLine renders horizontal border lines.

func (*Table) RenderFooter

func (t *Table) RenderFooter() error

RenderFooter renders the table footer.

func (*Table) RenderHeader

func (t *Table) RenderHeader() error

RenderHeader renders the table header row, including the top border and header separator line if enabled.

func (*Table) RenderHeaderRow

func (t *Table) RenderHeaderRow(row Row) error

RenderHeaderRow renders a header row with full-line styling.

func (*Table) RenderRow

func (t *Table) RenderRow(row Row) error

RenderRow renders a single row.

func (*Table) SetAutoAlign

func (t *Table) SetAutoAlign(autoAlign bool)

SetAutoAlign sets whether to skip alignment for all columns.

func (*Table) SetBorderConfig

func (t *Table) SetBorderConfig(config TableBorderConfig)

SetBorderConfig allows setting a custom border configuration.

func (*Table) SetBorderStyle

func (t *Table) SetBorderStyle(style BorderStyle)

SetBorderStyle changes the border style of the table.

func (*Table) SetHeaderStyle

func (t *Table) SetHeaderStyle(style HeaderStyle)

SetHeaderStyle sets the styling for header row.

func (*Table) SetHeaderStyleBorderless

func (t *Table) SetHeaderStyleBorderless(style HeaderStyle)

SetHeaderStyleBorderless sets the header style and disables ALL borders including left/right. This creates the most minimal table with only styled header and column spacing.

func (*Table) SetHeaderStyleMinimal

func (t *Table) SetHeaderStyleMinimal(style HeaderStyle)

SetHeaderStyleMinimal sets the header style and disables absolutely ALL borders and separators. This creates the most minimal possible table with only styled header and whitespace separation.

func (*Table) SetHeaderStyleWithoutBorders

func (t *Table) SetHeaderStyleWithoutBorders(style HeaderStyle)

SetHeaderStyleWithoutBorders sets the header style and disables all horizontal borders. This creates a completely clean look with only the styled header for distinction.

func (*Table) SetHeaderStyleWithoutSeparator

func (t *Table) SetHeaderStyleWithoutSeparator(style HeaderStyle)

SetHeaderStyleWithoutSeparator sets the header style and disables the header separator line. This is a convenience method for the common use case of styled headers not needing separators.

func (*Table) SetRenderer

func (t *Table) SetRenderer(renderer Renderer)

SetRenderer allows setting a custom renderer.

type TableBorderConfig

type TableBorderConfig struct {
	Chars    map[string]string
	Top      bool // Show top border
	Bottom   bool // Show bottom border
	Middle   bool // Show middle separator between header and data
	Left     bool // Show left border
	Right    bool // Show right border
	Vertical bool // Show internal vertical separators
	Padding  bool // Add content padding
}

TableBorderConfig holds border style configuration.

func GetBorderConfig

func GetBorderConfig(style BorderStyle) TableBorderConfig

GetBorderConfig returns border configuration for the specified style.

type TableOption

type TableOption func(*Table)

TableOption is a functional option for configuring Table.

func AutoAlign

func AutoAlign(autoAlign bool) TableOption

AutoAlign sets the align flag (option).

func Border

func Border(style BorderStyle) TableOption

Border sets the border style (option).

func BorderConfig

func BorderConfig(cfg TableBorderConfig) TableOption

BorderConfig sets a custom border configuration (option).

Example:

cfg := termhyo.GetBorderConfig(termhyo.BoxDrawingStyle)
cfg.Left = false
table := termhyo.NewTable(os.Stdout, columns, termhyo.BorderConfig(cfg))
func Header(style HeaderStyle) TableOption

Header sets the header style (option).

Directories

Path Synopsis
examples
autoalign_false command
basic command
combining command
custom_borders command
header_styles command
japanese command
markdown command
streaming command
styles command
unicode command

Jump to

Keyboard shortcuts

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