or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.mdmain-package.mdrenderer-package.mdtw-package.mdtwcache-package.mdtwwarp-package.mdtwwidth-package.md
tile.json

tw-package.mddocs/

tw Package

The tw package defines core types, interfaces, constants, and utility functions for table formatting and configuration. It provides the foundational type system for the tablewriter library, including cell configuration, rendering contexts, border symbols, generic collections, and text manipulation utilities.

Package Information

  • Package Name: tw
  • Package Type: Go module
  • Language: Go
  • Import Path: github.com/olekukonko/tablewriter/tw

Core Import

import "github.com/olekukonko/tablewriter/tw"

Overview

The tw package serves as the core type system for tablewriter, providing:

  • Interfaces: Renderer, Symbols, Formatter, Counter for extensibility
  • Core Types: Position, Align, State, Level, Location for table structure
  • Cell Configuration: Complete system for configuring cell formatting, padding, alignment, merging, and filtering
  • Rendering Context: Types that capture rendering state and formatting context
  • Symbol System: 44+ predefined border styles plus customizable symbols
  • Generic Collections: Type-safe Mapper and Slicer with rich utility methods
  • Text Utilities: Functions for padding, wrapping, width calculation, and camelCase splitting

Architecture

The tw package is organized into several logical subsystems:

  1. Interfaces: Define contracts for renderers, formatters, and counters
  2. Core Type System: Basic types for alignment, position, state, and dimensions
  3. Cell Configuration System: Hierarchical configuration for headers, rows, and footers
  4. Rendering Context System: Runtime state passed to renderers during rendering
  5. Symbol System: Border and junction characters for different styles
  6. Generic Collections: Reusable data structures with functional methods
  7. Utility Functions: Text processing, padding, and width calculation helpers

Interfaces

Renderer

Interface for table rendering engines that output to an io.Writer.

type Renderer interface {
    Start(w io.Writer) error
    Header(headers [][]string, ctx Formatting)
    Row(row []string, ctx Formatting)
    Footer(footers [][]string, ctx Formatting)
    Line(ctx Formatting)
    Config() Rendition
    Close() error
    Logger(logger *ll.Logger)
}

Methods:

  • Start(w io.Writer) error - Initialize renderer with output writer
  • Header(headers [][]string, ctx Formatting) - Render header section with formatting context
  • Row(row []string, ctx Formatting) - Render single data row with formatting context
  • Footer(footers [][]string, ctx Formatting) - Render footer section with formatting context
  • Line(ctx Formatting) - Render separator line based on formatting context
  • Config() Rendition - Get current renderer configuration
  • Close() error - Finalize rendering and cleanup resources
  • Logger(logger *ll.Logger) - Set logger instance for renderer

Renditioning

Interface for types that can update their rendition configuration dynamically.

type Renditioning interface {
    Rendition(r Rendition)
}

Methods:

  • Rendition(r Rendition) - Update rendition configuration

Symbols

Interface for table border symbol sets.

type Symbols interface {
    Name() string
    Center() string
    Row() string
    Column() string
    TopLeft() string
    TopMid() string
    TopRight() string
    MidLeft() string
    MidRight() string
    BottomLeft() string
    BottomMid() string
    BottomRight() string
    HeaderLeft() string
    HeaderMid() string
    HeaderRight() string
}

Methods:

  • Name() string - Style name
  • Center() string - Junction symbol where lines cross
  • Row() string - Horizontal line character
  • Column() string - Vertical line character
  • TopLeft() string - Top-left corner symbol
  • TopMid() string - Top junction (T pointing down)
  • TopRight() string - Top-right corner symbol
  • MidLeft() string - Left junction (T pointing right)
  • MidRight() string - Right junction (T pointing left)
  • BottomLeft() string - Bottom-left corner symbol
  • BottomMid() string - Bottom junction (T pointing up)
  • BottomRight() string - Bottom-right corner symbol
  • HeaderLeft() string - Header left junction symbol
  • HeaderMid() string - Header middle junction symbol
  • HeaderRight() string - Header right junction symbol

Formatter

Interface for types that can format themselves into a string.

type Formatter interface {
    Format() string
}

Methods:

  • Format() string - Returns formatted string representation

Counter

Interface combining io.Writer with total retrieval for counting operations (lines, bytes, etc.).

type Counter interface {
    io.Writer
    Total() int
}

Methods:

  • Write(p []byte) (n int, err error) - io.Writer implementation
  • Total() int - Get total count

Core Type System

Position

Defines table section location (header, row, or footer).

type Position string

const (
    Header Position = "header"
    Row    Position = "row"
    Footer Position = "footer"
)

func (pos Position) Validate() error

Constants:

  • Header - Table header section
  • Row - Table row section (data)
  • Footer - Table footer section

Methods:

  • Validate() error - Validates position is one of the allowed values

Align

Text alignment within table cells.

type Align string

const (
    AlignNone    Align = "none"
    AlignCenter  Align = "center"
    AlignRight   Align = "right"
    AlignLeft    Align = "left"
    AlignDefault Align = AlignLeft
    Skip         Align = ""
)

func (a Align) Validate() error

Constants:

  • AlignNone - No alignment applied
  • AlignCenter - Center-aligned text
  • AlignRight - Right-aligned text
  • AlignLeft - Left-aligned text
  • AlignDefault - Default alignment (same as AlignLeft)
  • Skip - Skip alignment for this column

Methods:

  • Validate() error - Validates alignment is one of the allowed values

Alignment

Slice of Align values with utility methods for managing column alignments.

type Alignment []Align

func (a Alignment) String() string
func (a Alignment) Add(aligns ...Align) Alignment
func (a Alignment) Set(col int, align Align) Alignment
func (a Alignment) Copy() Alignment

Methods:

  • String() string - String representation in format "0=left; 1=center; 2=right"
  • Add(aligns ...Align) Alignment - Creates new Alignment with specified alignments
  • Set(col int, align Align) Alignment - Sets alignment for specific column index
  • Copy() Alignment - Creates independent copy of alignment

State

Represents on/off/unknown state for features and settings.

type State int

const (
    Unknown State = 0
    On      State = 1
    Off     State = -1
)

func (o State) Enabled() bool
func (o State) Default() bool
func (o State) Disabled() bool
func (o State) Toggle() State
func (o State) Cond(c func() bool) bool
func (o State) Or(c State) State
func (o State) String() string

Constants:

  • Unknown - State is unknown/default (value: 0)
  • On - State is enabled (value: 1)
  • Off - State is disabled (value: -1)

Methods:

  • Enabled() bool - Returns true if state is On
  • Default() bool - Returns true if state is Unknown
  • Disabled() bool - Returns true if state is Off
  • Toggle() State - Switches between On and Off
  • Cond(c func() bool) bool - Executes function if state is enabled, returns result
  • Or(c State) State - Returns this state if enabled, otherwise returns c
  • String() string - Returns "on", "off", or "undefined"

Level

Hierarchical level in table structure (header, body, or footer).

type Level int

const (
    LevelHeader Level = 0
    LevelBody   Level = 1
    LevelFooter Level = 2
)

func (l Level) Validate() error

Constants:

  • LevelHeader - Header level (value: 0)
  • LevelBody - Body/data level (value: 1)
  • LevelFooter - Footer level (value: 2)

Methods:

  • Validate() error - Validates level is one of the allowed values

Location

Horizontal position within table row (first, middle, or end).

type Location string

const (
    LocationFirst  Location = "first"
    LocationMiddle Location = "middle"
    LocationEnd    Location = "end"
)

func (l Location) Validate() error

Constants:

  • LocationFirst - First position in row
  • LocationMiddle - Middle position in row
  • LocationEnd - End position in row

Methods:

  • Validate() error - Validates location is one of the allowed values

Caption

Table caption with positioning and alignment.

type Caption struct {
    Text  string
    Spot  Spot
    Align Align
    Width int
}

func (c Caption) WithText(text string) Caption
func (c Caption) WithSpot(spot Spot) Caption
func (c Caption) WithAlign(align Align) Caption
func (c Caption) WithWidth(width int) Caption

Fields:

  • Text string - Caption text content
  • Spot Spot - Caption position (top/bottom, left/center/right)
  • Align Align - Text alignment within caption
  • Width int - Maximum width for caption

Methods:

  • WithText(text string) Caption - Sets caption text
  • WithSpot(spot Spot) Caption - Sets caption position
  • WithAlign(align Align) Caption - Sets caption alignment
  • WithWidth(width int) Caption - Sets caption maximum width

Spot

Caption position enumeration.

type Spot int

const (
    SpotNone         Spot = 0
    SpotTopLeft      Spot = 1
    SpotTopCenter    Spot = 2
    SpotTopRight     Spot = 3
    SpotBottomLeft   Spot = 4
    SpotBottomCenter Spot = 5
    SpotBottomRight  Spot = 6
    SpotLeftTop      Spot = 7
    SpotLeftCenter   Spot = 8
    SpotLeftBottom   Spot = 9
    SpotRightTop     Spot = 10
    SpotRightCenter  Spot = 11
    SpotRIghtBottom  Spot = 12
)

Constants:

  • SpotNone - No caption position
  • SpotTopLeft - Top-left position
  • SpotTopCenter - Top-center position
  • SpotTopRight - Top-right position
  • SpotBottomLeft - Bottom-left position
  • SpotBottomCenter - Bottom-center position (default)
  • SpotBottomRight - Bottom-right position
  • SpotLeftTop - Left-top position
  • SpotLeftCenter - Left-center position
  • SpotLeftBottom - Left-bottom position
  • SpotRightTop - Right-top position
  • SpotRightCenter - Right-center position
  • SpotRIghtBottom - Right-bottom position

Control

Section control settings for hiding/showing table sections.

type Control struct {
    Hide State
}

Fields:

  • Hide State - State controlling visibility of section

Compact

Compact width optimization settings for merged cells.

type Compact struct {
    Merge State
}

Fields:

  • Merge State - Enables compact width calculation during cell merging

Struct

Settings for struct-based operations like automatic header extraction.

type Struct struct {
    AutoHeader State
    Tags       []string
}

Fields:

  • AutoHeader State - Automatically extract headers from struct field names when using Bulk with struct slices
  • Tags []string - Priority-ordered list of struct tag keys to check for header names (defaults: ["json", "db"])

Behavior

Settings controlling table rendering behaviors.

type Behavior struct {
    AutoHide  State
    TrimSpace State
    TrimLine  State
    Header    Control
    Footer    Control
    Compact   Compact
    Structs   Struct
}

Fields:

  • AutoHide State - Auto-hide empty columns (ignored in streaming mode)
  • TrimSpace State - Trim leading and trailing spaces from cell content
  • TrimLine State - Collapse empty visual lines within cells
  • Header Control - Header section control settings
  • Footer Control - Footer section control settings
  • Compact Compact - Compact width optimization settings
  • Structs Struct - Struct processing settings

Padding

Cell padding configuration for all four directions.

type Padding struct {
    Left      string
    Right     string
    Top       string
    Bottom    string
    Overwrite bool
}

func (p Padding) Equals(padding Padding) bool
func (p Padding) Empty() bool
func (p Padding) Paddable() bool

Fields:

  • Left string - Left padding characters
  • Right string - Right padding characters
  • Top string - Top padding characters
  • Bottom string - Bottom padding characters
  • Overwrite bool - Force exact usage, even when empty (overrides defaults)

Methods:

  • Equals(padding Padding) bool - Checks equality with another Padding
  • Empty() bool - Returns true if all padding strings are empty
  • Paddable() bool - Returns true if padding should override existing padding

LineCounter

Default Counter implementation for counting newline characters.

type LineCounter struct {
    // internal fields not exported
}

func (lc *LineCounter) Write(p []byte) (n int, err error)
func (lc *LineCounter) Total() int

Methods:

  • Write(p []byte) (n int, err error) - Counts newlines in written bytes
  • Total() int - Returns total newline count

Filter

Function type for row-level cell content processing.

type Filter func([]string) []string

Accepts a slice of strings (representing a row) and returns a processed slice.

Cell Configuration System

CellFormatting

Cell formatting options.

type CellFormatting struct {
    AutoWrap   int
    AutoFormat State
    MergeMode  int   // Deprecated: use CellConfig.Merging.Mode
    Alignment  Align // Deprecated: use CellConfig.Alignment
}

Fields:

  • AutoWrap int - Wrapping behavior (WrapNone, WrapNormal, WrapTruncate, WrapBreak)
  • AutoFormat State - Enable automatic formatting (e.g., title case for headers)
  • MergeMode int - Deprecated: Use CellConfig.Merging.Mode instead
  • Alignment Align - Deprecated: Use CellConfig.Alignment instead

CellMerging

Cell merging configuration.

type CellMerging struct {
    Mode          int
    ByColumnIndex Mapper[int, bool]
    ByRowIndex    Mapper[int, bool]
}

Fields:

  • Mode int - Merge type bitmask (MergeNone, MergeVertical, MergeHorizontal, MergeBoth, MergeHierarchical)
  • ByColumnIndex Mapper[int, bool] - Column indices to enable merging (nil/empty = all columns)
  • ByRowIndex Mapper[int, bool] - Row indices to enable merging (reserved for future use)

CellPadding

Cell padding settings with global and per-column configuration.

type CellPadding struct {
    Global    Padding
    PerColumn []Padding
}

Fields:

  • Global Padding - Default padding applied to all cells
  • PerColumn []Padding - Column-specific padding overrides

CellFilter

Cell filtering functions for processing content.

type CellFilter struct {
    Global    func([]string) []string
    PerColumn []func(string) string
}

Fields:

  • Global func([]string) []string - Processes entire row as slice
  • PerColumn []func(string) string - Processes individual cells by column

CellCallbacks

Cell callback functions (placeholder for future functionality).

type CellCallbacks struct {
    Global    func()
    PerColumn []func()
}

Fields:

  • Global func() - Global callback applied to all cells
  • PerColumn []func() - Column-specific callbacks

CellAlignment

Cell alignment settings with global and per-column configuration.

type CellAlignment struct {
    Global    Align
    PerColumn []Align
}

Fields:

  • Global Align - Default alignment for all cells
  • PerColumn []Align - Column-specific alignment overrides

CellConfig

Complete cell configuration combining all cell options.

type CellConfig struct {
    Formatting   CellFormatting
    Padding      CellPadding
    Callbacks    CellCallbacks
    Filter       CellFilter
    Alignment    CellAlignment
    ColMaxWidths CellWidth
    Merging      CellMerging
    ColumnAligns []Align // Deprecated: use Alignment.PerColumn
}

Fields:

  • Formatting CellFormatting - Cell formatting options
  • Padding CellPadding - Padding configuration
  • Callbacks CellCallbacks - Callback functions
  • Filter CellFilter - Filter functions for content processing
  • Alignment CellAlignment - Alignment settings
  • ColMaxWidths CellWidth - Maximum width constraints
  • Merging CellMerging - Merge configuration
  • ColumnAligns []Align - Deprecated: Use Alignment.PerColumn instead

CellWidth

Width constraints for cells and columns.

type CellWidth struct {
    Global    int
    PerColumn Mapper[int, int]
}

func (c CellWidth) Constrained() bool

Fields:

  • Global int - Global maximum width for all cells
  • PerColumn Mapper[int, int] - Column-specific width constraints

Methods:

  • Constrained() bool - Returns true if any width constraints are set

Rendering Context System

Rendition

Renderer configuration.

type Rendition struct {
    Borders   Border
    Symbols   Symbols
    Settings  Settings
    Streaming bool
}

Fields:

  • Borders Border - Border visibility settings
  • Symbols Symbols - Border symbol set
  • Settings Settings - Rendering behavior settings
  • Streaming bool - Streaming mode flag

Formatting

Complete formatting context for row rendering.

type Formatting struct {
    Row              RowContext
    Level            Level
    HasFooter        bool
    IsSubRow         bool
    NormalizedWidths Mapper[int, int]
}

Fields:

  • Row RowContext - Row configuration and state
  • Level Level - Hierarchical level (Header/Body/Footer)
  • HasFooter bool - Indicates if table includes footer section
  • IsSubRow bool - Marks this as continuation line in multi-line rows
  • NormalizedWidths Mapper[int, int] - Calculated column widths

CellContext

Individual cell properties and state.

type CellContext struct {
    Data    string
    Align   Align
    Padding Padding
    Width   int
    Merge   MergeState
}

Fields:

  • Data string - Cell content to display
  • Align Align - Text alignment within cell
  • Padding Padding - Padding characters surrounding content
  • Width int - Suggested display width
  • Merge MergeState - Cell spanning details

MergeState

Cell merge state across all directions.

type MergeState struct {
    Vertical     MergeStateOption
    Horizontal   MergeStateOption
    Hierarchical MergeStateOption
}

Fields:

  • Vertical MergeStateOption - Vertical merge state (across rows)
  • Horizontal MergeStateOption - Horizontal merge state (across columns)
  • Hierarchical MergeStateOption - Hierarchical merge state (nested)

MergeStateOption

Merge attributes for specific direction.

type MergeStateOption struct {
    Present bool
    Span    int
    Start   bool
    End     bool
}

Fields:

  • Present bool - True if merge is active in this direction
  • Span int - Number of cells this merge spans
  • Start bool - True if this cell is merge starting point
  • End bool - True if this cell is merge ending point

RowContext

Row layout properties and relationships.

type RowContext struct {
    Position     Position
    Location     Location
    Current      map[int]CellContext
    Previous     map[int]CellContext
    Next         map[int]CellContext
    Widths       Mapper[int, int]
    ColMaxWidths CellWidth
}

func (r RowContext) GetCell(col int) CellContext

Fields:

  • Position Position - Table section (Header/Row/Footer)
  • Location Location - Boundary position (First/Middle/End)
  • Current map[int]CellContext - Cells in current row by column index
  • Previous map[int]CellContext - Cells from previous row (for merge detection)
  • Next map[int]CellContext - Cells from next row (for merge detection)
  • Widths Mapper[int, int] - Computed widths for each column
  • ColMaxWidths CellWidth - Maximum allowed width per column

Methods:

  • GetCell(col int) CellContext - Gets cell by column index

Separators

Separator visibility settings.

type Separators struct {
    ShowHeader     State
    ShowFooter     State
    BetweenRows    State
    BetweenColumns State
}

Fields:

  • ShowHeader State - Show header separator line
  • ShowFooter State - Show footer separator line
  • BetweenRows State - Show separators between rows
  • BetweenColumns State - Show separators between columns

Lines

Table boundary line settings.

type Lines struct {
    ShowTop        State
    ShowBottom     State
    ShowHeaderLine State
    ShowFooterLine State
}

Fields:

  • ShowTop State - Show top border line
  • ShowBottom State - Show bottom border line
  • ShowHeaderLine State - Show header separator line
  • ShowFooterLine State - Show footer separator line

Settings

Rendering behavior configuration.

type Settings struct {
    Separators  Separators
    Lines       Lines
    CompactMode State
}

Fields:

  • Separators Separators - Separator visibility settings
  • Lines Lines - Line visibility settings
  • CompactMode State - Compact rendering mode (reserved for future use)

Border

Border visibility states.

type Border struct {
    Left      State
    Right     State
    Top       State
    Bottom    State
    Overwrite bool
}

Fields:

  • Left State - Left border visibility
  • Right State - Right border visibility
  • Top State - Top border visibility
  • Bottom State - Bottom border visibility
  • Overwrite bool - Force exact usage (override defaults)

StreamConfig

Streaming mode configuration.

type StreamConfig struct {
    Enable        bool
    StrictColumns bool
    Widths        CellWidth // Deprecated: use top-level Config.Widths
}

Fields:

  • Enable bool - Enable streaming mode
  • StrictColumns bool - Return error if row column count doesn't match (default: false)
  • Widths CellWidth - Deprecated: Use top-level Config.Widths instead

Symbol System

BorderStyle

Border styling enumeration with 44 predefined styles.

type BorderStyle int

const (
    StyleNone         BorderStyle = 0
    StyleASCII        BorderStyle = 1
    StyleLight        BorderStyle = 2
    StyleHeavy        BorderStyle = 3
    StyleDouble       BorderStyle = 4
    StyleDoubleLong   BorderStyle = 5
    StyleLightHeavy   BorderStyle = 6
    StyleHeavyLight   BorderStyle = 7
    StyleLightDouble  BorderStyle = 8
    StyleDoubleLight  BorderStyle = 9
    StyleRounded      BorderStyle = 10
    StyleMarkdown     BorderStyle = 11
    StyleGraphical    BorderStyle = 12
    StyleMerger       BorderStyle = 13
    StyleDefault      BorderStyle = 14
    StyleDotted       BorderStyle = 15
    StyleArrow        BorderStyle = 16
    StyleStarry       BorderStyle = 17
    StyleHearts       BorderStyle = 18
    StyleCircuit      BorderStyle = 19
    StyleNature       BorderStyle = 20
    StyleArtistic     BorderStyle = 21
    Style8Bit         BorderStyle = 22
    StyleChaos        BorderStyle = 23
    StyleDots         BorderStyle = 24
    StyleBlocks       BorderStyle = 25
    StyleZen          BorderStyle = 26
    StyleVintage      BorderStyle = 27
    StyleSketch       BorderStyle = 28
    StyleArrowDouble  BorderStyle = 29
    StyleCelestial    BorderStyle = 30
    StyleCyber        BorderStyle = 31
    StyleRunic        BorderStyle = 32
    StyleIndustrial   BorderStyle = 33
    StyleInk          BorderStyle = 34
    StyleArcade       BorderStyle = 35
    StyleBlossom      BorderStyle = 36
    StyleFrosted      BorderStyle = 37
    StyleMosaic       BorderStyle = 38
    StyleUFO          BorderStyle = 39
    StyleSteampunk    BorderStyle = 40
    StyleGalaxy       BorderStyle = 41
    StyleJazz         BorderStyle = 42
    StylePuzzle       BorderStyle = 43
    StyleHypno        BorderStyle = 44
)

func (s BorderStyle) String() string

Constants: 44 border style constants from StyleNone (0) to StyleHypno (44)

Methods:

  • String() string - Returns style name (e.g., "Light", "Heavy", "Rounded")

StyleName

Style name string type.

type StyleName string

const (
    StyleNameNothing     StyleName = "nothing"
    StyleNameASCII       StyleName = "ascii"
    StyleNameLight       StyleName = "light"
    StyleNameHeavy       StyleName = "heavy"
    StyleNameDouble      StyleName = "double"
    StyleNameDoubleLong  StyleName = "doublelong"
    StyleNameLightHeavy  StyleName = "lightheavy"
    StyleNameHeavyLight  StyleName = "heavylight"
    StyleNameLightDouble StyleName = "lightdouble"
    StyleNameDoubleLight StyleName = "doublelight"
    StyleNameRounded     StyleName = "rounded"
    StyleNameMarkdown    StyleName = "markdown"
    StyleNameGraphical   StyleName = "graphical"
    StyleNameMerger      StyleName = "merger"
    StyleNameDotted      StyleName = "dotted"
    StyleNameArrow       StyleName = "arrow"
    StyleNameStarry      StyleName = "starry"
    StyleNameHearts      StyleName = "hearts"
    StyleNameCircuit     StyleName = "circuit"
    StyleNameNature      StyleName = "nature"
    StyleNameArtistic    StyleName = "artistic"
    StyleName8Bit        StyleName = "8bit"
    StyleNameChaos       StyleName = "chaos"
    StyleNameDots        StyleName = "dots"
    StyleNameBlocks      StyleName = "blocks"
    StyleNameZen         StyleName = "zen"
    StyleNameVintage     StyleName = "vintage"
    StyleNameSketch      StyleName = "sketch"
    StyleNameArrowDouble StyleName = "arrowdouble"
    StyleNameCelestial   StyleName = "celestial"
    StyleNameCyber       StyleName = "cyber"
    StyleNameRunic       StyleName = "runic"
    StyleNameIndustrial  StyleName = "industrial"
    StyleNameInk         StyleName = "ink"
    StyleNameArcade      StyleName = "arcade"
    StyleNameBlossom     StyleName = "blossom"
    StyleNameFrosted     StyleName = "frosted"
    StyleNameMosaic      StyleName = "mosaic"
    StyleNameUFO         StyleName = "ufo"
    StyleNameSteampunk   StyleName = "steampunk"
    StyleNameGalaxy      StyleName = "galaxy"
    StyleNameJazz        StyleName = "jazz"
    StyleNamePuzzle      StyleName = "puzzle"
    StyleNameHypno       StyleName = "hypno"
)

func (s StyleName) String() string

Constants: 44+ style name constants matching BorderStyle values

Methods:

  • String() string - Returns style name as string

SymbolCustom

Customizable border style implementation with builder pattern.

type SymbolCustom struct {
    // internal fields not exported
}

func NewSymbolCustom(name string) *SymbolCustom
func (c *SymbolCustom) Name() string
func (c *SymbolCustom) Center() string
func (c *SymbolCustom) Row() string
func (c *SymbolCustom) Column() string
func (c *SymbolCustom) TopLeft() string
func (c *SymbolCustom) TopMid() string
func (c *SymbolCustom) TopRight() string
func (c *SymbolCustom) MidLeft() string
func (c *SymbolCustom) MidRight() string
func (c *SymbolCustom) BottomLeft() string
func (c *SymbolCustom) BottomMid() string
func (c *SymbolCustom) BottomRight() string
func (c *SymbolCustom) HeaderLeft() string
func (c *SymbolCustom) HeaderMid() string
func (c *SymbolCustom) HeaderRight() string
func (c *SymbolCustom) WithCenter(s string) *SymbolCustom
func (c *SymbolCustom) WithRow(s string) *SymbolCustom
func (c *SymbolCustom) WithColumn(s string) *SymbolCustom
func (c *SymbolCustom) WithTopLeft(s string) *SymbolCustom
func (c *SymbolCustom) WithTopMid(s string) *SymbolCustom
func (c *SymbolCustom) WithTopRight(s string) *SymbolCustom
func (c *SymbolCustom) WithMidLeft(s string) *SymbolCustom
func (c *SymbolCustom) WithMidRight(s string) *SymbolCustom
func (c *SymbolCustom) WithBottomLeft(s string) *SymbolCustom
func (c *SymbolCustom) WithBottomMid(s string) *SymbolCustom
func (c *SymbolCustom) WithBottomRight(s string) *SymbolCustom
func (c *SymbolCustom) WithHeaderLeft(s string) *SymbolCustom
func (c *SymbolCustom) WithHeaderMid(s string) *SymbolCustom
func (c *SymbolCustom) WithHeaderRight(s string) *SymbolCustom
func (s *SymbolCustom) Preview() string

Constructor:

  • NewSymbolCustom(name string) *SymbolCustom - Creates customizable border style

Methods:

  • All Symbols interface methods (see Symbols interface above)
  • Builder methods: With* methods for setting each symbol (return *SymbolCustom for chaining)
  • Preview() string - Renders small sample table to visualize border style

Usage Example:

custom := tw.NewSymbolCustom("MyStyle").
    WithRow("=").
    WithColumn("|").
    WithCenter("+").
    WithTopLeft("*").
    WithTopRight("*")

// Preview the style
fmt.Println(custom.Preview())

Glyphs

Border symbols with corners array representation (used by predefined styles).

type Glyphs struct {
    // internal fields not exported
}

func (s *Glyphs) Name() string
func (s *Glyphs) Center() string
func (s *Glyphs) Row() string
func (s *Glyphs) Column() string
func (s *Glyphs) TopLeft() string
func (s *Glyphs) TopMid() string
func (s *Glyphs) TopRight() string
func (s *Glyphs) MidLeft() string
func (s *Glyphs) MidRight() string
func (s *Glyphs) BottomLeft() string
func (s *Glyphs) BottomMid() string
func (s *Glyphs) BottomRight() string
func (s *Glyphs) HeaderLeft() string
func (s *Glyphs) HeaderMid() string
func (s *Glyphs) HeaderRight() string
func (s *Glyphs) Preview() string

Methods:

  • All Symbols interface methods (see Symbols interface above)
  • Preview() string - Renders small sample table to visualize border style

Generic Collections

Mapper[K comparable, V any]

Generic map type with rich utility methods.

type Mapper[K comparable, V any] map[K]V

func NewMapper[K comparable, V any]() Mapper[K, V]
func (m Mapper[K, V]) Get(key K) V
func (m Mapper[K, V]) OK(key K) (V, bool)
func (m Mapper[K, V]) Set(key K, value V) Mapper[K, V]
func (m Mapper[K, V]) Delete(key K) Mapper[K, V]
func (m Mapper[K, V]) Has(key K) bool
func (m Mapper[K, V]) Len() int
func (m Mapper[K, V]) Keys() []K
func (m Mapper[K, V]) Clear()
func (m Mapper[K, V]) Values() []V
func (m Mapper[K, V]) Each(fn func(K, V))
func (m Mapper[K, V]) Filter(fn func(K, V) bool) Mapper[K, V]
func (m Mapper[K, V]) MapValues(fn func(V) V) Mapper[K, V]
func (m Mapper[K, V]) Clone() Mapper[K, V]
func (m Mapper[K, V]) Slicer() Slicer[KeyValuePair[K, V]]
func (m Mapper[K, V]) SortedKeys() []K

Constructor:

  • NewMapper[K comparable, V any]() Mapper[K, V] - Creates new initialized Mapper

Methods:

  • Get(key K) V - Gets value by key (returns zero value if not found)
  • OK(key K) (V, bool) - Gets value with existence check
  • Set(key K, value V) Mapper[K, V] - Sets value for key
  • Delete(key K) Mapper[K, V] - Removes key
  • Has(key K) bool - Checks if key exists
  • Len() int - Returns number of entries
  • Keys() []K - Returns slice of all keys
  • Clear() - Removes all entries
  • Values() []V - Returns slice of all values
  • Each(fn func(K, V)) - Iterates over entries
  • Filter(fn func(K, V) bool) Mapper[K, V] - Returns new Mapper with filtered entries
  • MapValues(fn func(V) V) Mapper[K, V] - Returns new Mapper with transformed values
  • Clone() Mapper[K, V] - Creates shallow copy
  • Slicer() Slicer[KeyValuePair[K, V]] - Converts to Slicer of key-value pairs
  • SortedKeys() []K - Returns sorted keys (supports int, float, string types)

Usage Example:

// Create a Mapper of column widths
widths := tw.NewMapper[int, int]()
widths.Set(0, 20).Set(1, 30).Set(2, 15)

// Iterate over widths
widths.Each(func(col int, width int) {
    fmt.Printf("Column %d: %d\n", col, width)
})

// Filter widths > 15
wide := widths.Filter(func(col int, width int) bool {
    return width > 15
})

KeyValuePair[K comparable, V any]

Key-value pair for Mapper operations.

type KeyValuePair[K comparable, V any] struct {
    Key   K
    Value V
}

Fields:

  • Key K - Key of the pair
  • Value V - Value of the pair

Slicer[T any]

Generic slice type with rich utility methods.

type Slicer[T any] []T

func NewSlicer[T any]() Slicer[T]
func (s Slicer[T]) Get(index int) T
func (s Slicer[T]) GetOK(index int) (T, bool)
func (s Slicer[T]) Append(elements ...T) Slicer[T]
func (s Slicer[T]) Prepend(elements ...T) Slicer[T]
func (s Slicer[T]) Len() int
func (s Slicer[T]) IsEmpty() bool
func (s Slicer[T]) Has(index int) bool
func (s Slicer[T]) First() T
func (s Slicer[T]) Last() T
func (s Slicer[T]) Each(fn func(T))
func (s Slicer[T]) Filter(fn func(T) bool) Slicer[T]
func (s Slicer[T]) Map(fn func(T) T) Slicer[T]
func (s Slicer[T]) Contains(fn func(T) bool) bool
func (s Slicer[T]) Find(fn func(T) bool) (T, bool)
func (s Slicer[T]) Clone() Slicer[T]

Constructor:

  • NewSlicer[T any]() Slicer[T] - Creates new initialized Slicer

Methods:

  • Get(index int) T - Gets element by index (returns zero value if out of bounds)
  • GetOK(index int) (T, bool) - Gets element with bounds check
  • Append(elements ...T) Slicer[T] - Appends elements
  • Prepend(elements ...T) Slicer[T] - Prepends elements
  • Len() int - Returns length
  • IsEmpty() bool - Checks if empty
  • Has(index int) bool - Checks if index exists
  • First() T - Gets first element
  • Last() T - Gets last element
  • Each(fn func(T)) - Iterates over elements
  • Filter(fn func(T) bool) Slicer[T] - Returns new Slicer with filtered elements
  • Map(fn func(T) T) Slicer[T] - Returns new Slicer with transformed elements
  • Contains(fn func(T) bool) bool - Checks if any element satisfies predicate
  • Find(fn func(T) bool) (T, bool) - Finds first element matching predicate
  • Clone() Slicer[T] - Creates shallow copy

Usage Example:

// Create a Slicer of alignments
aligns := tw.NewSlicer[tw.Align]()
aligns = aligns.Append(tw.AlignLeft, tw.AlignCenter, tw.AlignRight)

// Filter to only center-aligned
centered := aligns.Filter(func(a tw.Align) bool {
    return a == tw.AlignCenter
})

Constants and Presets

Operation Status Constants

const (
    Pending = 0
    Fail    = -1
    Success = 1
)
  • Pending - Unknown/default state (value: 0)
  • Fail - Operation failed / feature disabled (value: -1)
  • Success - Operation succeeded / feature enabled (value: 1)

Width Constants

const (
    MinimumColumnWidth = 8
)
  • MinimumColumnWidth - Minimum column width in characters

Cache Constants

const (
    DefaultCacheStringCapacity = 10 * 1024
)
  • DefaultCacheStringCapacity - Default string cache capacity (10 KB)

String Constants

const (
    Empty   = ""
    Skip    = ""
    Space   = " "
    NewLine = "\n"
    Column  = ":"
    Dash    = "-"
)
  • Empty - Empty string
  • Skip - Skip/ignore marker
  • Space - Single space character
  • NewLine - Line break character
  • Column - Column separator character
  • Dash - Dash character

Section Name Constants

const (
    SectionHeader = "header"
    SectionRow    = "row"
    SectionFooter = "footer"
)
  • SectionHeader - Header section name
  • SectionRow - Row section name
  • SectionFooter - Footer section name

Wrapping Mode Constants

const (
    WrapNone     = 0
    WrapNormal   = 1
    WrapTruncate = 2
    WrapBreak    = 3
)
  • WrapNone - No wrapping
  • WrapNormal - Standard word wrapping
  • WrapTruncate - Truncate with ellipsis
  • WrapBreak - Break long words to fit

Merging Mode Constants

const (
    MergeNone         = 0
    MergeVertical     = 1
    MergeHorizontal   = 2
    MergeBoth         = 3
    MergeHierarchical = 4
)
  • MergeNone - No merging
  • MergeVertical - Merge vertically identical cells
  • MergeHorizontal - Merge horizontally identical cells
  • MergeBoth - Merge both directions
  • MergeHierarchical - Hierarchical merging

Special Character Constants

const (
    CharEllipsis = "…"
    CharBreak    = "↩"
)
  • CharEllipsis - Ellipsis character for truncation
  • CharBreak - Break character for wrapping

Preset Variables

var (
    PaddingNone    = Padding{Left: "", Right: "", Top: "", Bottom: "", Overwrite: true}
    PaddingDefault = Padding{Left: " ", Right: " ", Overwrite: true}
    BorderNone     = Border{Left: Off, Right: Off, Top: Off, Bottom: Off}
    LinesNone      = Lines{ShowTop: Off, ShowBottom: Off, ShowHeaderLine: Off, ShowFooterLine: Off}
    SeparatorsNone = Separators{ShowHeader: Off, ShowFooter: Off, BetweenRows: Off, BetweenColumns: Off}
)
  • PaddingNone - Explicitly empty padding (no spacing on any side)
  • PaddingDefault - Standard single-space padding on left/right
  • BorderNone - All borders disabled
  • LinesNone - All lines disabled
  • SeparatorsNone - All separators disabled

Style Mapping Variable

var Styles = map[BorderStyle]StyleName{ /* 44 style mappings */ }

Maps BorderStyle constants to StyleName strings. Contains all 44 border style mappings.

Utility Functions

Collection Constructors

func NewMapper[K comparable, V any]() Mapper[K, V]

Creates new initialized Mapper with specified key and value types.

func NewBoolMapper[K comparable](keys ...K) Mapper[K, bool]

Creates Mapper with boolean values set to true for given keys.

func NewIntMapper[K comparable](keys ...K) Mapper[K, int]

Creates Mapper with integer values (keys as indices, all values initialized to 0).

func NewIdentityMapper[K comparable](keys ...K) Mapper[K, K]

Creates Mapper with keys as values (identity mapping).

func NewSlicer[T any]() Slicer[T]

Creates new initialized Slicer with specified element type.

func SlicerToMapper[K comparable, V any](s Slicer[KeyValuePair[K, V]]) Mapper[K, V]

Converts Slicer of KeyValuePair to Mapper.

Symbol Functions

func NewSymbols(style BorderStyle) Symbols

Creates Symbols instance with specified predefined border style.

Parameters:

  • style BorderStyle - One of the 44 predefined border style constants

Returns: Symbols implementation for that style

Example:

symbols := tw.NewSymbols(tw.StyleRounded)
fmt.Println(symbols.TopLeft())  // "╭"
func NewSymbolCustom(name string) *SymbolCustom

Creates customizable border style with given name for fluent configuration.

Parameters:

  • name string - Custom style name

Returns: SymbolCustom instance for customization

Example:

custom := tw.NewSymbolCustom("MyStyle").
    WithRow("-").
    WithColumn("|").
    WithCenter("+")

Text Formatting Functions

func Title(name string) string

Normalizes and uppercases label for headers. Splits camelCase, converts underscores to spaces, and uppercases the result.

Parameters:

  • name string - Input label (may be camelCase, snake_case, etc.)

Returns: Formatted uppercase header string

Example:

tw.Title("userName")      // "USER NAME"
tw.Title("user_name")     // "USER NAME"
tw.Title("first.last")    // "FIRST LAST"
func SplitCamelCase(src string) []string

Splits camelCase, PascalCase, or snake_case string into separate words.

Parameters:

  • src string - Input string

Returns: Slice of words

Example:

tw.SplitCamelCase("userName")     // ["user", "Name"]
tw.SplitCamelCase("HTTPResponse") // ["HTTP", "Response"]
tw.SplitCamelCase("user_name")    // ["user", "name"]

Padding Functions

func PadCenter(s, pad string, width int) string

Centers string within specified width using padding characters.

Parameters:

  • s string - Input string
  • pad string - Padding character(s)
  • width int - Target width

Returns: Centered and padded string

func PadRight(s, pad string, width int) string

Left-aligns string, padding on right side to reach target width.

Parameters:

  • s string - Input string
  • pad string - Padding character(s)
  • width int - Target width

Returns: Left-aligned padded string

func PadLeft(s, pad string, width int) string

Right-aligns string, padding on left side to reach target width.

Parameters:

  • s string - Input string
  • pad string - Padding character(s)
  • width int - Target width

Returns: Right-aligned padded string

func Pad(s, padChar string, totalWidth int, alignment Align) string

Aligns string with padding based on alignment direction. Truncates if string exceeds width.

Parameters:

  • s string - Input string
  • padChar string - Padding character(s)
  • totalWidth int - Target width
  • alignment Align - Alignment direction (AlignLeft, AlignRight, AlignCenter)

Returns: Aligned and padded (or truncated) string

Validation Functions

func IsIsNumericOrSpace(r rune) bool

Checks if rune is digit (0-9) or space character.

Parameters:

  • r rune - Rune to check

Returns: true if numeric or space

func IsNumeric(s string) bool

Checks if string represents valid integer or floating-point number.

Parameters:

  • s string - String to check

Returns: true if valid number

Utility Functions

func Or(cond bool, valid, inValid string) string

Ternary-like string operation: returns valid if condition is true, else inValid.

Parameters:

  • cond bool - Condition
  • valid string - Return if true
  • inValid string - Return if false

Returns: Selected string

func Max(a, b int) int

Returns greater of two integers.

func Min(a, b int) int

Returns smaller of two integers.

func BreakPoint(s string, limit int) int

Finds rune index where display width first exceeds limit. Used for text wrapping.

Parameters:

  • s string - Input string
  • limit int - Width limit

Returns: Number of runes that fit within limit

func MakeAlign(l int, align Align) Alignment

Creates Alignment slice of length l filled with specified alignment.

Parameters:

  • l int - Length of alignment slice
  • align Align - Alignment to fill with

Returns: Alignment slice

Example:

// Create alignment for 3 columns, all center-aligned
align := tw.MakeAlign(3, tw.AlignCenter)
// align == Alignment{AlignCenter, AlignCenter, AlignCenter}

Types

All types listed in the sections above are exported from the tw package. Key type categories:

  • Basic Types: Position, Align, Alignment, State, Level, Location, Spot
  • Configuration Types: Caption, Control, Compact, Struct, Behavior, Padding
  • Cell Types: CellFormatting, CellMerging, CellPadding, CellFilter, CellCallbacks, CellAlignment, CellConfig, CellWidth
  • Rendering Types: Rendition, Formatting, CellContext, MergeState, MergeStateOption, RowContext, Separators, Lines, Settings, Border, StreamConfig
  • Symbol Types: BorderStyle, StyleName, SymbolCustom, Glyphs
  • Generic Types: Mapper[K,V], KeyValuePair[K,V], Slicer[T]
  • Interface Types: Renderer, Renditioning, Symbols, Formatter, Counter
  • Function Types: Filter