table

package
v0.0.0-...-b9feb98 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2026 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package table provides formatted table rendering for terminal output.

This package enables the creation of beautiful, styled tables with customizable borders, alignment, and formatting. Tables are rendered as Renderables and can be displayed using a rich.Console.

Basic Usage

Create a simple table with headers and rows:

tbl := table.New().
	Headers("Name", "Age", "City").
	Row("Alice", "30", "New York").
	Row("Bob", "25", "Los Angeles").
	Row("Carol", "35", "Chicago")

console.Renderln(tbl)

Column Configuration

Customize individual columns with detailed configuration:

col1 := table.NewColumn("Name").
	WithAlign(table.AlignLeft).
	WithMinWidth(10)

col2 := table.NewColumn("Age").
	WithAlign(table.AlignRight).
	WithWidth(5)

col3 := table.NewColumn("City").
	WithAlign(table.AlignCenter).
	WithMaxWidth(20)

tbl := table.New().
	AddColumn(col1).
	AddColumn(col2).
	AddColumn(col3).
	Row("Alice", "30", "New York")

Border Styles

Choose from predefined border styles or create custom ones:

tbl.Box(table.BoxRounded)   // Rounded corners (default)
tbl.Box(table.BoxDouble)    // Double-line borders
tbl.Box(table.BoxHeavy)     // Heavy borders
tbl.Box(table.BoxSimple)    // Simple single-line borders
tbl.Box(table.BoxASCII)     // ASCII-only characters
tbl.Box(table.BoxNone)      // No borders

Styling

Apply custom styles to borders, headers, and titles:

tbl := table.New().
	Title("User Report").
	TitleStyle(rich.NewStyle().Bold().Foreground(rich.Cyan)).
	BorderStyle(rich.NewStyle().Dim()).
	Headers("Name", "Status")

Column-specific styling:

col := table.NewColumn("Status").
	WithHeaderStyle(rich.NewStyle().Bold().Foreground(rich.Yellow)).
	WithCellStyle(rich.NewStyle().Italic())

Alignment

Control how content is aligned within columns:

table.AlignLeft    // Left-aligned (default)
table.AlignCenter  // Centered
table.AlignRight   // Right-aligned

Width Control

Tables support flexible width management:

col.WithWidth(20)      // Fixed width of 20 characters
col.WithMinWidth(10)   // Minimum width of 10 characters
col.WithMaxWidth(50)   // Maximum width of 50 characters

Width calculation:

  • If Width is set, the column uses that exact width
  • Otherwise, width is calculated from content and constrained by MinWidth/MaxWidth
  • By default, columns auto-size to fit their content

Options

Additional table configuration:

tbl.ShowHeader(false)   // Hide the header row
tbl.ShowEdge(false)     // Hide outer borders
tbl.Padding(2)          // Set cell padding (default: 1)

Custom Box Styles

Create custom border styles:

customBox := table.Box{
	TopLeft:     "╔",
	Top:         "═",
	TopRight:    "╗",
	Left:        "║",
	Right:       "║",
	BottomLeft:  "╚",
	Bottom:      "═",
	BottomRight: "╝",
	// ... other fields
}

tbl.Box(customBox)

Complete Example

import (
	"github.com/eberle1080/go-rich"
	"github.com/eberle1080/go-rich/table"
)

console := rich.NewConsole(nil)

tbl := table.New().
	Title("Sales Report").
	Box(table.BoxDouble).
	BorderStyle(rich.NewStyle().Foreground(rich.Cyan)).
	Headers("Product", "Quantity", "Price").
	Row("Widget A", "150", "$29.99").
	Row("Widget B", "200", "$39.99").
	Row("Widget C", "75", "$49.99")

console.Renderln(tbl)

Index

Constants

This section is empty.

Variables

View Source
var (
	// BoxASCII uses ASCII characters (compatible everywhere).
	// This style works on all terminals and systems, including those without
	// Unicode support. It's the most compatible option but least visually appealing.
	//
	// Example:
	//   +------+------+
	//   | Name | Age  |
	//   +------+------+
	//   | Bob  | 25   |
	//   +------+------+
	BoxASCII = Box{
		TopLeft:     "+",
		Top:         "-",
		TopRight:    "+",
		Left:        "|",
		Right:       "|",
		BottomLeft:  "+",
		Bottom:      "-",
		BottomRight: "+",
		MidLeft:     "+",
		MidRight:    "+",
		MidTop:      "+",
		MidBottom:   "+",
		Mid:         "+",
		HeaderRow:   "-",
		HeaderLeft:  "+",
		HeaderRight: "+",
	}

	// BoxRounded uses rounded corners for a softer appearance.
	// This style uses Unicode box-drawing characters with rounded corners,
	// creating a modern, friendly look. This is the default style.
	//
	// Example:
	//   ╭──────┬──────╮
	//   │ Name │ Age  │
	//   ├──────┼──────┤
	//   │ Bob  │ 25   │
	//   ╰──────┴──────╯
	BoxRounded = Box{
		TopLeft:     "╭",
		Top:         "─",
		TopRight:    "╮",
		Left:        "│",
		Right:       "│",
		BottomLeft:  "╰",
		Bottom:      "─",
		BottomRight: "╯",
		MidLeft:     "├",
		MidRight:    "┤",
		MidTop:      "┬",
		MidBottom:   "┴",
		Mid:         "┼",
		HeaderRow:   "─",
		HeaderLeft:  "├",
		HeaderRight: "┤",
	}

	// BoxDouble uses double-line box drawing characters for emphasis.
	// This style uses thick double-line Unicode box-drawing characters,
	// creating a bold, formal appearance. Good for highlighting important tables.
	//
	// Example:
	//   ╔══════╦══════╗
	//   ║ Name ║ Age  ║
	//   ╠══════╬══════╣
	//   ║ Bob  ║ 25   ║
	//   ╚══════╩══════╝
	BoxDouble = Box{
		TopLeft:     "╔",
		Top:         "═",
		TopRight:    "╗",
		Left:        "║",
		Right:       "║",
		BottomLeft:  "╚",
		Bottom:      "═",
		BottomRight: "╝",
		MidLeft:     "╠",
		MidRight:    "╣",
		MidTop:      "╦",
		MidBottom:   "╩",
		Mid:         "╬",
		HeaderRow:   "═",
		HeaderLeft:  "╠",
		HeaderRight: "╣",
	}

	// BoxHeavy uses heavy box drawing characters for maximum visual weight.
	// This style uses thick single-line Unicode box-drawing characters,
	// creating a strong, bold appearance while remaining cleaner than double-line.
	//
	// Example:
	//   ┏━━━━━━┳━━━━━━┓
	//   ┃ Name ┃ Age  ┃
	//   ┣━━━━━━╋━━━━━━┫
	//   ┃ Bob  ┃ 25   ┃
	//   ┗━━━━━━┻━━━━━━┛
	BoxHeavy = Box{
		TopLeft:     "┏",
		Top:         "━",
		TopRight:    "┓",
		Left:        "┃",
		Right:       "┃",
		BottomLeft:  "┗",
		Bottom:      "━",
		BottomRight: "┛",
		MidLeft:     "┣",
		MidRight:    "┫",
		MidTop:      "┳",
		MidBottom:   "┻",
		Mid:         "╋",
		HeaderRow:   "━",
		HeaderLeft:  "┣",
		HeaderRight: "┫",
	}

	// BoxSimple uses simple single-line characters for a clean look.
	// This style uses thin single-line Unicode box-drawing characters,
	// creating a minimal, clean appearance. Good for dense information displays.
	//
	// Example:
	//   ┌──────┬──────┐
	//   │ Name │ Age  │
	//   ├──────┼──────┤
	//   │ Bob  │ 25   │
	//   └──────┴──────┘
	BoxSimple = Box{
		TopLeft:     "┌",
		Top:         "─",
		TopRight:    "┐",
		Left:        "│",
		Right:       "│",
		BottomLeft:  "└",
		Bottom:      "─",
		BottomRight: "┘",
		MidLeft:     "├",
		MidRight:    "┤",
		MidTop:      "┬",
		MidBottom:   "┴",
		Mid:         "┼",
		HeaderRow:   "─",
		HeaderLeft:  "├",
		HeaderRight: "┤",
	}

	// BoxNone has no borders at all.
	// This style removes all border characters, creating a borderless table.
	// Useful for simple data display where visual separation isn't needed,
	// or when the table is part of a larger bordered container.
	//
	// Example:
	//   Name   Age
	//   Bob    25
	BoxNone = Box{}
)

Predefined box styles. These provide ready-to-use border styles for common aesthetic preferences.

Functions

This section is empty.

Types

type Align

type Align int

Align specifies how content is aligned within a column. Alignment affects how text is positioned when the cell content is shorter than the column width.

const (
	// AlignLeft aligns content to the left side of the column.
	// This is the default and most common alignment for text content.
	AlignLeft Align = iota

	// AlignCenter centers content within the column.
	// Useful for headers, short labels, or creating visual symmetry.
	AlignCenter

	// AlignRight aligns content to the right side of the column.
	// Commonly used for numeric data to align decimal points.
	AlignRight
)

type Box

type Box struct {
	TopLeft  string // Top-left corner character
	Top      string // Top edge character (repeated horizontally)
	TopRight string // Top-right corner character

	Left  string // Left edge character (repeated vertically)
	Right string // Right edge character (repeated vertically)

	BottomLeft  string // Bottom-left corner character
	Bottom      string // Bottom edge character (repeated horizontally)
	BottomRight string // Bottom-right corner character

	MidLeft   string // Left T-junction (where header separator meets left edge)
	MidRight  string // Right T-junction (where header separator meets right edge)
	MidTop    string // Top T-junction (where column separator meets top edge)
	MidBottom string // Bottom T-junction (where column separator meets bottom edge)
	Mid       string // Cross junction (where header separator meets column separator)

	HeaderRow   string // Header separator row character (repeated horizontally)
	HeaderLeft  string // Header separator left junction
	HeaderRight string // Header separator right junction
}

Box defines the characters used to draw table borders. Each field represents a specific position or edge in the table structure. By customizing these characters, you can create tables with different visual styles.

Box structure:

TopLeft ──Top── MidTop ──Top── TopRight
│                               │
Left     cell    Left    cell   Right
│                               │
HeaderLeft ─HeaderRow─ Mid ─HeaderRow─ HeaderRight
│                               │
Left     cell    Left    cell   Right
│                               │
BottomLeft ──Bottom── MidBottom ──Bottom── BottomRight

The package provides predefined box styles (BoxSimple, BoxRounded, BoxDouble, etc.) for common use cases.

type Column

type Column struct {
	Header string // Header text displayed in the header row

	Width    int // Fixed width in characters (0 = auto-size from content)
	MinWidth int // Minimum width in characters (0 = no minimum)
	MaxWidth int // Maximum width in characters (0 = unlimited)

	Align Align // How content is aligned within the column

	HeaderStyle rich.Style // Style applied to the header cell
	CellStyle   rich.Style // Style applied to data cells in this column

	NoWrap bool // If true, prevent text wrapping (truncate instead)
}

Column represents a table column configuration. A column defines how a particular column in a table should be rendered, including its header text, width constraints, alignment, and styling.

Width behavior:

  • If Width > 0: Column has a fixed width
  • If Width == 0: Width is calculated from content, constrained by MinWidth/MaxWidth
  • MinWidth sets a floor (column won't be narrower than this)
  • MaxWidth sets a ceiling (column won't be wider than this, 0 = unlimited)

Styling is applied separately to headers and data cells, allowing for visual distinction between them.

func NewColumn

func NewColumn(header string) *Column

NewColumn creates a new column with the given header. The column is initialized with sensible defaults:

  • Auto-sized width (calculated from content)
  • Left alignment
  • Bold header style
  • Unstyled cell content

Use the With* methods to customize the column configuration.

Example:

col := table.NewColumn("Name")

func (*Column) WithAlign

func (c *Column) WithAlign(align Align) *Column

WithAlign sets the alignment for the column. Affects both header and cell content alignment.

Example:

col := table.NewColumn("Price").WithAlign(table.AlignRight)

func (*Column) WithCellStyle

func (c *Column) WithCellStyle(style rich.Style) *Column

WithCellStyle sets the cell style for the column. This style is applied to all data cells in this column.

Example:

col := table.NewColumn("Error").
	WithCellStyle(rich.NewStyle().Foreground(rich.Red))

func (*Column) WithHeaderStyle

func (c *Column) WithHeaderStyle(style rich.Style) *Column

WithHeaderStyle sets the header style for the column. This style is applied only to the header cell in this column.

Example:

col := table.NewColumn("Status").
	WithHeaderStyle(rich.NewStyle().Foreground(rich.Yellow))

func (*Column) WithMaxWidth

func (c *Column) WithMaxWidth(width int) *Column

WithMaxWidth sets the maximum width for the column. The column won't exceed this width. Content longer than this will be truncated. Set to 0 for unlimited width.

Example:

col := table.NewColumn("Description").WithMaxWidth(50)

func (*Column) WithMinWidth

func (c *Column) WithMinWidth(width int) *Column

WithMinWidth sets the minimum width for the column. The column will be at least this wide, even if content is shorter. Useful for ensuring columns don't become too narrow.

Example:

col := table.NewColumn("ID").WithMinWidth(5)

func (*Column) WithNoWrap

func (c *Column) WithNoWrap() *Column

WithNoWrap disables text wrapping for the column. When set, long text will be truncated instead of wrapping to multiple lines. Currently this is the only supported behavior (wrapping is not yet implemented).

Example:

col := table.NewColumn("Path").WithNoWrap()

func (*Column) WithWidth

func (c *Column) WithWidth(width int) *Column

WithWidth sets a fixed width for the column. When set, the column will always be exactly this width, regardless of content. Content longer than the width will be truncated.

Example:

col := table.NewColumn("Name").WithWidth(20)

type Table

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

Table represents a table with headers, rows, and borders. Tables provide a structured way to display tabular data with customizable appearance. They implement the rich.Renderable interface and can be rendered to a Console.

A table consists of:

  • Columns: Define headers, widths, alignment, and styles
  • Rows: Data organized as string arrays (one per row)
  • Optional title: Displayed above the table
  • Border style (Box): Visual appearance of table borders
  • Various display options: header visibility, edge visibility, padding

Tables are built using a fluent API:

table.New().
	Title("Users").
	Headers("Name", "Age").
	Row("Alice", "30").
	Row("Bob", "25")

func New

func New() *Table

New creates a new table with sensible defaults. The table is initialized with:

  • BoxSimple border style (clean single-line borders)
  • Header row visible
  • Outer borders visible
  • 1 character of padding in each cell
  • Dim style for borders
  • Bold style for title

Use the fluent API methods to customize the table before rendering.

Example:

tbl := table.New().
	Headers("Name", "Age").
	Row("Alice", "30").
	Row("Bob", "25")
console.Renderln(tbl)

func (*Table) AddColumn

func (t *Table) AddColumn(column *Column) *Table

AddColumn adds a column to the table. Use this when you need fine-grained control over column configuration. For simple cases, use Headers() instead.

Example:

col := table.NewColumn("Price").
	WithAlign(table.AlignRight).
	WithWidth(10)
tbl := table.New().AddColumn(col)

func (*Table) BorderStyle

func (t *Table) BorderStyle(style rich.Style) *Table

BorderStyle sets the style for all border characters. This affects the visual appearance of the borders but not their shape. Default is dim (faint) style.

Example:

tbl := table.New().BorderStyle(rich.NewStyle().Foreground(rich.Cyan))

func (*Table) Box

func (t *Table) Box(box Box) *Table

Box sets the border style using predefined or custom box characters. See the Box type and predefined styles (BoxSimple, BoxRounded, etc.) for options.

Example:

tbl := table.New().Box(table.BoxDouble)

func (*Table) Headers

func (t *Table) Headers(headers ...string) *Table

Headers is a convenience method to add columns from header strings. Creates one column per header with default settings (left-aligned, auto-width, bold header). This is the quickest way to set up a simple table.

Example:

tbl := table.New().Headers("Name", "Age", "City")

func (*Table) Padding

func (t *Table) Padding(padding int) *Table

Padding sets the cell padding in characters. Padding is added to both left and right sides of cell content. Default is 1.

Example:

tbl := table.New().Padding(2) // 2 spaces on each side

func (*Table) Render

func (t *Table) Render(console *rich.Console, width int) rich.Segments

Render implements rich.Renderable. Converts the table into styled segments that can be displayed on the console.

The rendering process:

  1. Calculate optimal column widths based on content and constraints
  2. Render top border (if showEdge is true)
  3. Render title row (if title is set)
  4. Render header row (if showHeader is true)
  5. Render header separator
  6. Render data rows
  7. Render bottom border (if showEdge is true)

The width parameter is the maximum available width for the table. The console parameter provides access to the color mode and other settings.

func (*Table) Row

func (t *Table) Row(cells ...string) *Table

Row adds a data row to the table. Each argument becomes a cell in the row, matched to columns by position. If fewer cells than columns are provided, remaining cells are empty. If more cells than columns are provided, extra cells are ignored.

Example:

tbl := table.New().
	Headers("Name", "Age").
	Row("Alice", "30").
	Row("Bob", "25")

func (*Table) ShowEdge

func (t *Table) ShowEdge(show bool) *Table

ShowEdge controls whether to show the outer border. When false, only internal column separators are shown (no top/bottom/left/right edges). Default is true.

Example:

tbl := table.New().ShowEdge(false)

func (*Table) ShowHeader

func (t *Table) ShowHeader(show bool) *Table

ShowHeader controls whether to show the header row. When false, only data rows are displayed (no header row or header separator). Default is true.

Example:

tbl := table.New().ShowHeader(false)

func (*Table) Title

func (t *Table) Title(title string) *Table

Title sets the table title displayed at the top. The title is centered and displayed in its own row above the headers. If empty (default), no title row is shown.

Example:

tbl := table.New().Title("User Report")

func (*Table) TitleStyle

func (t *Table) TitleStyle(style rich.Style) *Table

TitleStyle sets the style for the title text. Only affects the title if one is set via Title(). Default is bold style.

Example:

tbl := table.New().
	Title("Report").
	TitleStyle(rich.NewStyle().Bold().Foreground(rich.Green))

Jump to

Keyboard shortcuts

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