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.
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, 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.
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 ¶
- Variables
- func StyleNames() []string
- type Align
- type Line
- type Option
- func PlainCells() Option
- func SanitizeCells() Option
- func UppercaseHeaders() Option
- func WithAlignment(aligns ...Align) Option
- func WithColor(on bool) Option
- func WithDelimiter(r rune) Option
- func WithFormat(f format.Format) Option
- func WithHeaderTransform(fn func(string) string) Option
- func WithIndent(indent string) Option
- func WithRecordLineJoin(sep string) Option
- func WithRowGap(on bool) Option
- func WithStyle(s Style) Option
- func WithTheme(th theme.Theme) Option
- type Style
- type Table
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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 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.
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 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. Record output keeps the headers as given.
func WithAlignment ¶
WithAlignment sets the alignment of the columns, in order. Columns beyond the list are left-aligned.
func WithColor ¶
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 ¶
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 ¶
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 ¶
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 ¶
WithIndent starts every drawn line with indent, such as " " to line a table up under a heading. Styles with NoIndent ignore it.
func WithRecordLineJoin ¶
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 ¶
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 ¶
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 │ ╰────────┴─────────┴──────────╯
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 ¶
LookupStyle resolves a style name, ignoring case and surrounding space. It knows the drawn styles of StyleNames, not Markdown.
func ParseStyle ¶
ParseStyle is LookupStyle with an error that names the value and every accepted style, for flag validation.
type Table ¶
type Table struct {
// contains filtered or unexported fields
}
Table collects rows and renders them. Build one with New.
func New ¶
New returns a table that writes to w, with one column per header. A table without headers prints its rows alone.
func (*Table) Append ¶
Append adds a row. Cells may carry escape sequences and newlines; a row may be shorter or longer than the header. A drawn table shows them as they are 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) TotalWidth ¶
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.