table

package
v0.7.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; without headers it has an empty header row, since a pipe table is one only with the rule below its header. 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. They are the same in every locale: a character of ambiguous width, such as the rules of the frames, is one cell. A cell may span several lines; the whole row grows with it. A row may have fewer or more cells than the header; the missing ones are empty.

A drawn cell holds neither a tab nor a carriage return, whatever was appended. A tab becomes the spaces up to the next tab stop, every 8 columns counted from the start of the cell's line: the stop a terminal would move to depends on the column the cell is drawn at, which would make the same cell wider in one column than in another. A carriage return that does not end a line is dropped, since it would draw the rest of the cell over the table to its left. Every line of a table so keeps its width.

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.

Text from elsewhere

Markdown and record output is pasted, parsed or printed as it stands, and nothing in it is painted, so every cell becomes plain text there, whoever wrote it: escape sequences and control characters are removed as term.Plain removes them, a carriage return becomes a line break, and in a record a tab becomes a space. A record then carries no control character but the separators and line ends of its format.

A drawn table shows its cells as they are by default, tabs and carriage returns aside, since it cannot tell the escape sequences a caller painted into a cell, a color or an OSC 8 link, from ones that came with the data. Text from elsewhere goes through term.Sanitize or term.Plain before it is painted and appended, or the table does it for every cell: SanitizeCells keeps colors and removes everything else, PlainCells removes colors too.

Records

CSV fields are quoted as RFC 4180 describes; TSV fields are never quoted. Records end in a line feed, not the CRLF of RFC 4180, as tools on a command line expect. Every record has as many fields as the longest row or the header, the missing ones empty. A record of one empty field is written as "" in CSV, because readers skip an empty line; TSV has no quotes, so there it is the empty line, which cut(1) and awk(1) count and a reader that skips empty lines does not.

Record output is not protected against formula injection: a spreadsheet takes a cell that starts with "=", "+", "-" or "@" for a formula, and a cell with text from elsewhere may start with one. EscapeFormulas puts a single quote in front of such cells for exports people open in a spreadsheet; without it, cells are written as they are, which is what a program reading the records needs.

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. A table without headers gets an empty header row, since
	// a pipe table is one only with its header rule. 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 fill wider than one cell is cut where it does not fit a column a whole number of times. 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 EscapeFormulas added in v0.7.0

func EscapeFormulas() Option

EscapeFormulas makes CSV and TSV output safe to open in a spreadsheet when its cells hold text from elsewhere. A spreadsheet takes a cell that starts with "=", "+", "-" or "@" for a formula, which can read other cells, fetch a URL or start a program, and it skips a tab or a carriage return at the start to get there. A header or row cell that starts with one of these six, or with spaces and then one of the four, is written with a single quote in front of it, which a spreadsheet shows as text. A cell that is nothing but a number with a sign, such as "-12.5", is no formula and stays as it is.

The quote is part of the field for every other reader of the records, which is why this is an option: use it for an export people open in a spreadsheet, not for one a program parses. Drawn tables ignore it.

Example

An export people open in a spreadsheet: a comment that starts like a formula is written as text. The number stays a number.

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", "Balance", "Comment"}, table.WithFormat(format.CSV), table.EscapeFormulas())
	t.Append("Ada", "-12.50", "=HYPERLINK(\"https://evil.example\")")
	t.Append("Alan", "+3.00", "- none")
	_ = t.Render()
}
Output:
Name,Balance,Comment
Ada,-12.50,"'=HYPERLINK(""https://evil.example"")"
Alan,+3.00,'- none

func PlainCells added in v0.6.0

func PlainCells() Option

PlainCells makes the cells of a drawn table, its header cells included, plain text: each goes through term.Plain, which takes out every escape sequence, colors included, and every control character but the newline. Use it for a table of text from elsewhere that the program does not paint cell by cell; the header and rule colors the table paints itself stay. Markdown and record output are always plain text and do not need it.

Example

Names and comments from a server are shown as plain text: the window title, the cleared screen and the colors they tried to set are gone.

package main

import (
	"os"

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

func main() {
	t := table.New(os.Stdout, []string{"Name", "Comment"}, table.WithColor(false), table.PlainCells())
	t.Append("Ada\x1b]0;pwned\x07", "\x1b[2J\x1b[31mURGENT\x1b[0m: call me")
	_ = t.Render()
}
Output:
Name  Comment
Ada   URGENT: call me

func SanitizeCells added in v0.6.0

func SanitizeCells() Option

SanitizeCells makes the cells of a drawn table, its header cells included, safe to show when they hold text from elsewhere: each goes through term.Sanitize, which keeps colors, the data's as much as the caller's, and takes out every other escape sequence (an OSC 8 link the caller added, too) and every control character but the newline. Each line of a multi-line cell stands on its own, as term.SanitizeLines makes it, so a color never runs into the padding or rules beside it. Markdown and record output are always plain text and do not need it. See PlainCells for cells that should keep no colors at all.

func UppercaseHeaders

func UppercaseHeaders() Option

UppercaseHeaders draws header cells in upper case, the way kubectl-style listings do. Escape sequences in a header cell keep their case, and 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. fn gets the text of a header cell, never the escape sequences a caller painted into it: a color or an OSC 8 link stays as it is, parameters and URL included, and fn is called for each piece of text between two of them. 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. There
	// the header rule is what makes the lines a table, so a style with
	// AlignMarkers draws it for a table without headers too, under an empty
	// header row.
	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: the missing cells are empty, in a drawn table and in records alike. A drawn table shows the cells as they are, but for tabs and carriage returns, unless SanitizeCells or PlainCells says otherwise, so text from elsewhere in a cell has to be made safe first, with one of these or term.Sanitize or term.Plain; Markdown and record output make every cell plain text.

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