table

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 8 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package table renders rows of cells as an aligned text table, a framed table, a markdown pipe table, or CSV/TSV records.

A Table is built with New and options, filled with Table.Append, and written with Table.Render:

t := table.New(os.Stdout, []string{"Name", "Status"}, table.WithStyle(table.Rounded))
t.Append("api", "running")
t.Append("worker", "stopped")
err := t.Render()

The default Plain style is a drop-in for text/tabwriter listings: columns padded to their widest cell and separated by two spaces, no trailing padding, no rules. The framed styles (Light, Rounded, Heavy, Double, Fancy, ASCII) draw box rules around every cell. Markdown draws a GitHub-flavored pipe table that pastes into a document unchanged. WithDelimiter or WithFormat switch to CSV or TSV records.

Widths are measured in terminal cells, not bytes: wide runes count two cells, and escape sequences a caller painted into a cell count none. A cell may span several lines; the whole row grows with it.

Header cells and frame rules are painted with the active theme's Header and Border styles when term.Colored reports color for the writer, or as WithColor decides. Markdown and record output is never painted, and escape sequences in their cells are removed.

Example
package main

import (
	"os"

	"github.com/mittwald/cli-kit/table"
)

func services(opts ...table.Option) *table.Table {
	t := table.New(os.Stdout, []string{"Name", "Status", "Replicas"},
		append([]table.Option{table.WithColor(false)}, opts...)...)
	t.Append("api", "running", "3")
	t.Append("worker", "stopped", "0")
	return t
}

func main() {
	_ = services(table.UppercaseHeaders()).Render()
}
Output:
NAME    STATUS   REPLICAS
api     running  3
worker  stopped  0

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// Plain pads columns and separates them by two spaces, without rules.
	Plain = Style{Name: "plain"}
	// Light frames the table in light box-drawing rules.
	Light = Style{
		Name:       "light",
		Top:        Line{"┌", "─", "┬", "┐"},
		HeaderRule: Line{"├", "─", "┼", "┤"},
		RowRule:    Line{"├", "─", "┼", "┤"},
		Bottom:     Line{"└", "─", "┴", "┘"},
		Left:       "│", Separator: "│", Right: "│",
	}
	// Rounded is Light with rounded corners.
	Rounded = Style{
		Name:       "rounded",
		Top:        Line{"╭", "─", "┬", "╮"},
		HeaderRule: Line{"├", "─", "┼", "┤"},
		RowRule:    Line{"├", "─", "┼", "┤"},
		Bottom:     Line{"╰", "─", "┴", "╯"},
		Left:       "│", Separator: "│", Right: "│",
	}
	// Heavy frames the table in heavy box-drawing rules.
	Heavy = Style{
		Name:       "heavy",
		Top:        Line{"┏", "━", "┳", "┓"},
		HeaderRule: Line{"┣", "━", "╋", "┫"},
		RowRule:    Line{"┣", "━", "╋", "┫"},
		Bottom:     Line{"┗", "━", "┻", "┛"},
		Left:       "┃", Separator: "┃", Right: "┃",
	}
	// Double frames the table in double box-drawing rules.
	Double = Style{
		Name:       "double",
		Top:        Line{"╔", "═", "╦", "╗"},
		HeaderRule: Line{"╠", "═", "╬", "╣"},
		RowRule:    Line{"╠", "═", "╬", "╣"},
		Bottom:     Line{"╚", "═", "╩", "╝"},
		Left:       "║", Separator: "║", Right: "║",
	}
	// Fancy frames the table and its header in double rules but keeps single
	// verticals and between-row rules, so the header stands out while the
	// rows stay quiet.
	Fancy = Style{
		Name:       "fancy",
		Top:        Line{"╒", "═", "╤", "╕"},
		HeaderRule: Line{"╞", "═", "╪", "╡"},
		RowRule:    Line{"├", "─", "┼", "┤"},
		Bottom:     Line{"╘", "═", "╧", "╛"},
		Left:       "│", Separator: "│", Right: "│",
	}
	// ASCII frames the table in US-ASCII only, for terminals, pipes and logs
	// that mangle box-drawing runes.
	ASCII = Style{
		Name:       "ascii",
		Top:        Line{"+", "-", "+", "+"},
		HeaderRule: Line{"+", "-", "+", "+"},
		RowRule:    Line{"+", "-", "+", "+"},
		Bottom:     Line{"+", "-", "+", "+"},
		Left:       "|", Separator: "|", Right: "|",
	}
	// Markdown is a GitHub-flavored pipe table: a header rule and nothing
	// else, no indent, multi-line cells folded with <br>, pipes escaped, and
	// never painted. It is what an --output markdown flag prints; it is not
	// one of the [StyleNames], which list the drawn frames a --table-style
	// flag picks from.
	Markdown = Style{
		Name:       "markdown",
		HeaderRule: Line{"|", "-", "|", "|"},
		Left:       "|", Separator: "|", Right: "|",
		Flatten:      true,
		NoIndent:     true,
		EscapePipes:  true,
		Verbatim:     true,
		AlignMarkers: true,
	}
)

The predefined styles.

Functions

func StyleNames

func StyleNames() []string

StyleNames returns the names of the drawn styles, plain first, for help text and shell completion of a --table-style flag.

Types

type Align

type Align int

Align is how a column's cells sit within its width.

const (
	// AlignLeft pads cells on the right. It is the default.
	AlignLeft Align = iota
	// AlignRight pads cells on the left, for numbers.
	AlignRight
)

type Line

type Line struct {
	Left, Fill, Junction, Right string
}

Line is one horizontal rule: a left cap, a fill repeated across every column, a junction between columns, and a right cap. A Line without a fill is not drawn.

func (Line) Enabled

func (l Line) Enabled() bool

Enabled reports whether the rule is drawn.

type Option

type Option func(*Table)

Option configures a Table. Options apply in order, so a later option overrides an earlier one that sets the same thing.

func UppercaseHeaders

func UppercaseHeaders() Option

UppercaseHeaders draws header cells in upper case, the way kubectl-style listings do. Record output keeps the headers as given.

func WithAlignment

func WithAlignment(aligns ...Align) Option

WithAlignment sets the alignment of the columns, in order. Columns beyond the list are left-aligned.

func WithColor

func WithColor(on bool) Option

WithColor decides whether header cells and rules are painted, instead of asking term.Colored for the writer. Verbatim styles and record output are never painted.

func WithDelimiter

func WithDelimiter(r rune) Option

WithDelimiter writes records instead of drawing the table: a tab writes TSV, any other rune CSV with that field separator. Zero draws the table.

func WithFormat

func WithFormat(f format.Format) Option

WithFormat sets the table up for an output format: format.Markdown selects the Markdown style, format.CSV and format.TSV select record output, and every other format leaves the table as configured. Put it after WithStyle, so a markdown request wins over a --table-style choice.

Example (Csv)
package main

import (
	"os"

	"github.com/mittwald/cli-kit/format"
	"github.com/mittwald/cli-kit/table"
)

func main() {
	t := table.New(os.Stdout, []string{"Name", "Note"}, table.WithFormat(format.CSV))
	t.Append("api", "scaled up, then down")
	t.Append("worker", "line one\nline two")
	_ = t.Render()
}
Output:
Name,Note
api,"scaled up, then down"
worker,line one; line two
Example (Markdown)
package main

import (
	"os"

	"github.com/mittwald/cli-kit/format"
	"github.com/mittwald/cli-kit/table"
)

func services(opts ...table.Option) *table.Table {
	t := table.New(os.Stdout, []string{"Name", "Status", "Replicas"},
		append([]table.Option{table.WithColor(false)}, opts...)...)
	t.Append("api", "running", "3")
	t.Append("worker", "stopped", "0")
	return t
}

func main() {
	_ = services(table.WithFormat(format.Markdown), table.WithAlignment(table.AlignLeft, table.AlignLeft, table.AlignRight)).Render()
}
Output:
| Name   | Status  | Replicas |
|--------|---------|---------:|
| api    | running |        3 |
| worker | stopped |        0 |

func WithHeaderTransform

func WithHeaderTransform(fn func(string) string) Option

WithHeaderTransform changes how header cells are drawn, such as strings.ToUpper. Record output keeps the headers as given to New: a spreadsheet column reads better as "Date" than as "DATE".

func WithIndent

func WithIndent(indent string) Option

WithIndent starts every drawn line with indent, such as " " to line a table up under a heading. Styles with NoIndent ignore it.

func WithRecordLineJoin

func WithRecordLineJoin(sep string) Option

WithRecordLineJoin sets what joins the lines of a multi-line cell in CSV and TSV output, where a record is one line. The default is "; ".

func WithRowGap

func WithRowGap(on bool) Option

WithRowGap separates the rows of an unframed table with a blank line, which keeps multi-line rows apart. Framed styles separate rows with their RowRule instead, and record output ignores it.

func WithStyle

func WithStyle(s Style) Option

WithStyle draws the table in s. The default is Plain.

Example
package main

import (
	"os"

	"github.com/mittwald/cli-kit/table"
)

func services(opts ...table.Option) *table.Table {
	t := table.New(os.Stdout, []string{"Name", "Status", "Replicas"},
		append([]table.Option{table.WithColor(false)}, opts...)...)
	t.Append("api", "running", "3")
	t.Append("worker", "stopped", "0")
	return t
}

func main() {
	_ = services(table.WithStyle(table.Rounded)).Render()
}
Output:
╭────────┬─────────┬──────────╮
│ Name   │ Status  │ Replicas │
├────────┼─────────┼──────────┤
│ api    │ running │ 3        │
├────────┼─────────┼──────────┤
│ worker │ stopped │ 0        │
╰────────┴─────────┴──────────╯

func WithTheme

func WithTheme(th theme.Theme) Option

WithTheme paints header cells and rules with th's Header and Border styles instead of the active theme's.

type Style

type Style struct {
	// Name is how the style is selected by [LookupStyle].
	Name string
	// Top, HeaderRule, RowRule and Bottom are the horizontal rules above the
	// header, below it, between rows and below the last row.
	Top, HeaderRule, RowRule, Bottom Line
	// Left, Separator and Right are the vertical rules. A style without a
	// Separator is not framed: its columns are separated by Gutter instead.
	Left, Separator, Right string
	// Gutter separates the columns of a style without vertical rules. Empty
	// means two spaces.
	Gutter string
	// Flatten folds a multi-line cell onto one line, joining its lines with
	// LineBreak. A markdown row is one line by definition.
	Flatten bool
	// LineBreak joins the lines of a flattened cell. Empty means "<br>".
	LineBreak string
	// NoIndent drops the left indent [WithIndent] sets, for output that is
	// pasted verbatim and must start at column 0.
	NoIndent bool
	// EscapePipes escapes backslashes and pipes in cells, so a value that
	// carries a pipe cannot open a column of its own in a markdown table.
	EscapePipes bool
	// Verbatim marks output another document takes as it stands: it is never
	// painted, and escape sequences are removed from its cells.
	Verbatim bool
	// AlignMarkers marks right-aligned columns with a colon at the right end
	// of the header rule, the way markdown declares column alignment.
	AlignMarkers bool
}

Style is a complete table frame. The zero Style is Plain. Every fill and rule rune of the predefined styles is one cell wide, so a rule measures exactly as wide as the rows it separates.

func LookupStyle

func LookupStyle(name string) (Style, bool)

LookupStyle resolves a style name, ignoring case and surrounding space. It knows the drawn styles of StyleNames, not Markdown.

func ParseStyle

func ParseStyle(name string) (Style, error)

ParseStyle is LookupStyle with an error that names the value and every accepted style, for flag validation.

func (Style) Framed

func (s Style) Framed() bool

Framed reports whether the style draws vertical rules.

type Table

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

Table collects rows and renders them. Build one with New.

func New

func New(w io.Writer, headers []string, opts ...Option) *Table

New returns a table that writes to w, with one column per header. A table without headers prints its rows alone.

func (*Table) Append

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

Append adds a row. Cells may carry escape sequences and newlines; a row may be shorter or longer than the header.

func (*Table) Len

func (t *Table) Len() int

Len returns the number of rows appended so far.

func (*Table) Render

func (t *Table) Render() error

Render writes the table.

func (*Table) TotalWidth

func (t *Table) TotalWidth() int

TotalWidth returns the width of the drawn table in cells: the indent, every column, and the gutters or rules between them. Every line of a framed table is exactly this wide; an unframed table leaves its last column unpadded, so its lines may be shorter. It is useful to right-align something to the table's edge.

Jump to

Keyboard shortcuts

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