zgo.at/acidtab Index | Examples | Files

package acidtab

import "zgo.at/acidtab"

Package acidtab prints aligned tables.

Example (Basic)

Code:

// Create a new table
t := acidtab.New("Name", "Origin", "Job", "Speciality", "Alive")

// Add rows to it
t.Row("James Holden", "Montana", "Captain", "Tilting windmills", true)
t.Row("Amos Burton", "Baltimore", "Mechanic", "Specific people skills", true)

// And then print it:
t.Horizontal(os.Stdout)

Output:

      Name      │   Origin    │    Job     │        Speciality        │  Alive
────────────────┼─────────────┼────────────┼──────────────────────────┼─────────
  James Holden  │  Montana    │  Captain   │  Tilting windmills       │  true
  Amos Burton   │  Baltimore  │  Mechanic  │  Specific people skills  │  true
Example (Chain)

Code:

acidtab.New("Name", "Origin", "Job", "Speciality", "Alive").
    Close(acidtab.CloseTop|acidtab.CloseBottom).
    Prefix(" ").
    Pad(" ").
    FormatCol(1, "%q").
    Rows(
        "Adolphus Murtry", "Earth", "Security", "General twattery", false,
        "Fred Johnson", "Earth", "Colonol", "Beltalowda", false,
    ).
    Vertical(os.Stdout)

Output:

 ────────────┬──────────────────
  Name       │ Adolphus Murtry
  Origin     │ "Earth"
  Job        │ Security
  Speciality │ General twattery
  Alive      │ false
 ────────────┼──────────────────
  Name       │ Fred Johnson
  Origin     │ "Earth"
  Job        │ Colonol
  Speciality │ Beltalowda
  Alive      │ false
 ────────────┴──────────────────
Example (Coloptions)

Code:

t := acidtab.New("Name", "Origin", "Job", "Speciality", "Alive")
t.Close(acidtab.CloseLeft | acidtab.CloseRight)

t.AlignCol(3, acidtab.Right) // Align column 3 and 4 (starts at 0)
t.AlignCol(4, acidtab.Center)

t.FormatCol(3, "%q") // Print column 3 as %q

// Callback for column 4
t.FormatColFunc(4, func(v interface{}) string {
    if b, ok := v.(bool); ok {
        return map[bool]string{true: "yes", false: "no"}[b]
    }
    // Return a NULL byte to fall back to regular formatting.
    return "\x00"
})

t.Row("Joe Miller", "Ceres", "Cop", "Doors 'n corners", false)
t.Row("Chrisjen Avasarala", "Earth", "Politician", "Insults", true)

t.Horizontal(os.Stdout)

Output:

│         Name         │  Origin  │     Job      │      Speciality      │  Alive  │
├──────────────────────┼──────────┼──────────────┼──────────────────────┼─────────┤
│  Joe Miller          │  Ceres   │  Cop         │  "Doors 'n corners"  │   no    │
│  Chrisjen Avasarala  │  Earth   │  Politician  │           "Insults"  │   yes   │
Example (Format)

Code:

bold := func(s string) string { return "\x1b[1m" + s + "\x1b[0m" }

t := acidtab.New(bold("Name"), bold("Origin"), bold("Job"), bold("Speciality"), bold("Alive")).
    Close(acidtab.CloseAll).
    AlignCol(4, acidtab.Center).
    FormatColFunc(4, func(v interface{}) string {
        if b, ok := v.(bool); ok {
            return map[bool]string{
                true:  "\x1b[32m ✔ \x1b[0m",
                false: "\x1b[31m✘\x1b[0m",
            }[b]
        }
        return "\x00"
    })

t.Rows(
    "James Holden", "Montana 🌎", "Captain 🚀", "Tilting windmills", true,
    "Amos Burton", "Baltimore 🌎", "Mechanic 🔧", "Specific people skills", true,
    "Naomi Nagata", "Pallas 🌌", "Mechanic 💻", "Spicy red food", true,
    "Alex Kamal", "Mars 🔴", "Pilot 🎧", "Cowboys", false,
    "Joe Miller", "Ceres 🌌", "Cop 👮", "Doors 'n corners", true,
    "Chrisjen Avasarala", "Earth 🌏", "Politician 🖕", "Insults", true,
    "Prax Meng", "Ganymede 🌌", "Botanist 🌻", "Plant metaphors", true,
    "Klaes Ashford", "The belt 🌌", "Pirate 🕱", "Singing", "😢",
    "Adolphus Murtry", "Earth 🌎", "Security 💂", "General twattery", false,
    "Fred Johnson", "Earth 🌎", "Colonol 🎖", "Beltalowda", false)

t.Horizontal(os.Stdout)

Output:

┌──────────────────────┬────────────────┬─────────────────┬──────────────────────────┬─────────┐
│         Name         │     Origin     │       Job       │        Speciality        │  Alive  │
├──────────────────────┼────────────────┼─────────────────┼──────────────────────────┼─────────┤
│  James Holden        │  Montana 🌎    │  Captain 🚀     │  Tilting windmills       │    ✔    │
│  Amos Burton         │  Baltimore 🌎  │  Mechanic 🔧    │  Specific people skills  │    ✔    │
│  Naomi Nagata        │  Pallas 🌌     │  Mechanic 💻    │  Spicy red food          │    ✔    │
│  Alex Kamal          │  Mars 🔴       │  Pilot 🎧       │  Cowboys                 │    ✘    │
│  Joe Miller          │  Ceres 🌌      │  Cop 👮         │  Doors 'n corners        │    ✔    │
│  Chrisjen Avasarala  │  Earth 🌏      │  Politician 🖕  │  Insults                 │    ✔    │
│  Prax Meng           │  Ganymede 🌌   │  Botanist 🌻    │  Plant metaphors         │    ✔    │
│  Klaes Ashford       │  The belt 🌌   │  Pirate 🕱       │  Singing                 │   😢    │
│  Adolphus Murtry     │  Earth 🌎      │  Security 💂    │  General twattery        │    ✘    │
│  Fred Johnson        │  Earth 🌎      │  Colonol 🎖      │  Beltalowda              │    ✘    │
└──────────────────────┴────────────────┴─────────────────┴──────────────────────────┴─────────┘
Example (Options)

Code:

t := acidtab.New("Name", "Origin", "Job", "Speciality", "Alive")

t.Borders(acidtab.BordersHeavy)                 // Set different borders.
t.Pad(" ")                                      // Pad cells with one space.
t.Prefix(" ")                                   // Prefix every line with a space.
t.Close(acidtab.CloseTop | acidtab.CloseBottom) // "Close" top and bottom.
t.Header(false)                                 // Don't print the header.

t.Row("Naomi Nagata", "Pallas", "Mechanic", "Spicy red food", true)
t.Row("Alex Kamal", "Mars", "Pilot", "Cowboys", false)

t.Horizontal(os.Stdout)

Output:

 ━━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━
  Naomi Nagata ┃ Pallas ┃ Mechanic ┃ Spicy red food ┃ true
  Alex Kamal   ┃ Mars   ┃ Pilot    ┃ Cowboys        ┃ false
 ━━━━━━━━━━━━━━┻━━━━━━━━┻━━━━━━━━━━┻━━━━━━━━━━━━━━━━┻━━━━━━━
Example (StringRows)

Code:

bold := func(s string) string { return "\x1b[1m" + s + "\x1b[0m" }

t := acidtab.New(bold("Name"), bold("Origin"), bold("Job"), bold("Speciality"), bold("Alive")).
    Close(acidtab.CloseAll).
    AlignCol(4, acidtab.Center).
    FormatColFunc(4, func(v interface{}) string {
        if b, ok := v.(bool); ok {
            return map[bool]string{
                true:  "\x1b[32m ✔ \x1b[0m",
                false: "\x1b[31m✘\x1b[0m",
            }[b]
        }
        return "\x00"
    })

t.RowsFromString("|", "\n", false, `
		James Holden       | Montana 🌎   | Captain 🚀    | Tilting windmills      | true
		Amos Burton        | Baltimore 🌎 | Mechanic 🔧   | Specific people skills | true
		Naomi Nagata       | Pallas 🌌    | Mechanic 💻   | Spicy red food         | true
		Alex Kamal         | Mars 🔴      | Pilot 🎧      | Cowboys                | false
		Joe Miller         | Ceres 🌌     | Cop 👮        | Doors 'n corners       | true
		Chrisjen Avasarala | Earth 🌏     | Politician 🖕 | Insults                | true
		Prax Meng          | Ganymede 🌌  | Botanist 🌻   | Plant metaphors        | true
		Klaes Ashford      | The belt 🌌  | Pirate 🕱      | Singing                | 😢
		Adolphus Murtry    | Earth 🌎     | Security 💂   | General twattery       | false
		Fred Johnson       | Earth 🌎     | Colonol 🎖    | Beltalowda             | false
	`)

t.Horizontal(os.Stdout)

Output:

┌──────────────────────┬────────────────┬─────────────────┬──────────────────────────┬─────────┐
│         Name         │     Origin     │       Job       │        Speciality        │  Alive  │
├──────────────────────┼────────────────┼─────────────────┼──────────────────────────┼─────────┤
│  James Holden        │  Montana 🌎    │  Captain 🚀     │  Tilting windmills       │  true   │
│  Amos Burton         │  Baltimore 🌎  │  Mechanic 🔧    │  Specific people skills  │  true   │
│  Naomi Nagata        │  Pallas 🌌     │  Mechanic 💻    │  Spicy red food          │  true   │
│  Alex Kamal          │  Mars 🔴       │  Pilot 🎧       │  Cowboys                 │  false  │
│  Joe Miller          │  Ceres 🌌      │  Cop 👮         │  Doors 'n corners        │  true   │
│  Chrisjen Avasarala  │  Earth 🌏      │  Politician 🖕  │  Insults                 │  true   │
│  Prax Meng           │  Ganymede 🌌   │  Botanist 🌻    │  Plant metaphors         │  true   │
│  Klaes Ashford       │  The belt 🌌   │  Pirate 🕱       │  Singing                 │   😢    │
│  Adolphus Murtry     │  Earth 🌎      │  Security 💂    │  General twattery        │  false  │
│  Fred Johnson        │  Earth 🌎      │  Colonol 🎖      │  Beltalowda              │  false  │
└──────────────────────┴────────────────┴─────────────────┴──────────────────────────┴─────────┘
Example (Vertical)

Code:

t := acidtab.New("Name", "Origin", "Job", "Speciality", "Alive")
t.Row("Prax Meng", "Ganymede", "Botanist", "Plant metaphors", true)
t.Row("Klaes Ashford", "The belt", "Pirate", "Singing", "😢")
t.Vertical(os.Stdout)

Output:

  Name        │  Prax Meng
  Origin      │  Ganymede
  Job         │  Botanist
  Speciality  │  Plant metaphors
  Alive       │  true
──────────────┼───────────────────
  Name        │  Klaes Ashford
  Origin      │  The belt
  Job         │  Pirate
  Speciality  │  Singing
  Alive       │  😢

Index

Examples

Package Files

horizontal.go printas.go table.go vertical.go

Variables

var (
    BordersDefault = Borders{'─', '│', '┼', '┌', '┐', '└', '┘', '├', '┤', '┬', '┴'}
    BordersHeavy   = Borders{'━', '┃', '╋', '┏', '┓', '┗', '┛', '┣', '┫', '┳', '┻'}
    BordersDouble  = Borders{'═', '║', '╬', '╔', '╗', '╚', '╝', '╠', '╣', '╦', '╩'}
    BordersASCII   = Borders{'-', '|', '+', '+', '+', '+', '+', '+', '+', '+', '+'}
    BordersSpace   = Borders{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}
)

Characters to use to draw the borders.

type Align

type Align uint8 // Alignment for columns.
const (
    Auto Align = iota
    Left
    Right
    Center
)

Column alignment.

type Borders

type Borders struct {
    Line, Bar, Cross                           rune
    TopLeft, TopRight, BottomLeft, BottomRight rune
    BarRight, BarLeft, LineTop, LineBottom     rune
}

Borders to use.

type Close

type Close uint8 // Which sides of the table to "close".
const (
    CloseBottom Close = 1 << iota
    CloseTop
    CloseLeft
    CloseRight
    CloseAll Close = CloseBottom | CloseTop | CloseLeft | CloseRight
)

Which sides to close.

type FormatAs

type FormatAs string // How to print a value; fmt format string (e.g. "%q", "%#v", etc.)

type FormatAsFunc

type FormatAsFunc func(v interface{}) string

func FormatAsFloat

func FormatAsFloat(perc int) FormatAsFunc

FormatAsFloat prints n as a float with the given percision.

Use perc=0 to round to the nearest natural number.

func FormatAsNum

func FormatAsNum() FormatAsFunc

FormatAsNum prints n as a number with , as thousands separators.

type Table

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

Table defines a table to print.

func New

func New(header ...string) *Table

New creates a new table with the given headers.

func (*Table) AlignCol

func (t *Table) AlignCol(n int, a Align) *Table

AlignCol sets the alignment for column n.

The default is right-aligned for numbers, and left-aligned for everything else.

func (*Table) Borders

func (t *Table) Borders(borders Borders) *Table

Borders sets the characters to use for borders

func (*Table) Close

func (t *Table) Close(close Close) *Table

Close sets which sides of the table to close.

func (Table) Error

func (t Table) Error() error

Error returns any error that may have happened when setting the data.

The print functions will never set an error.

func (*Table) FormatCol

func (t *Table) FormatCol(n int, p FormatAs) *Table

FormatCol sets how to format column n, as fmt format string (e.g. "%q", "%#v", etc.)

func (*Table) FormatColFunc

func (t *Table) FormatColFunc(n int, p FormatAsFunc) *Table

FormatColFunc sets a callback function to print a cell.

func (*Table) Grow

func (t *Table) Grow(n int)

Grow the rows allocation by n.

func (*Table) Header

func (t *Table) Header(show bool, header ...string) *Table

Header sets the header.

The show parameter controls if the header is printed.

If the list of headers is given then it will use this as the headers, overriding any previously set headers.

func (Table) Horizontal

func (t Table) Horizontal(w io.Writer)

func (*Table) Pad

func (t *Table) Pad(pad string) *Table

Pad sets the left/right padding for every cell.

func (*Table) Prefix

func (t *Table) Prefix(prefix string) *Table

Prefix sets the prefix to use before the left border.

func (*Table) Row

func (t *Table) Row(r ...interface{}) *Table

Row adds a new row.

Remaining columns will be filled with spaces if the number of values is lower than the numbers of headers. It will set an error if the number of values is greater.

func (*Table) Rows

func (t *Table) Rows(r ...interface{}) *Table

Rows adds multiple rows; the number of values should be an exact multitude of the number of headers; it will set an error if it's not.

For example:

t.Rows(
    "row1", "row1",
    "row2", "row2",)

func (*Table) RowsFromString

func (t *Table) RowsFromString(colDelim, rowDelim string, header bool, rows string) *Table

RowsFromString adds multiple rows from a single string. Columns are separated by colDelim, and rows by rowDelim.

Leading and trailing whitespace will be removed, as will all whitespace surrounding the colDelim. All items will be added as strings, but you can still parse/format things with FormatColFunc().

For example:

t.Rows("|", "\n", `
    row1 | row1
    row2 | row2
`)

If header is set the first row will be used as the header, overriding any header that was given with New().

The biggest advantage is that it looks a bit nicer if you want to print out loads of static data, since gofmt doesn't format it too well. It's also a bit easier to write.

Another use case is to feed output from a program or function.

func (Table) String

func (t Table) String() string

func (Table) Vertical

func (t Table) Vertical(w io.Writer)

Vertical prints the table as vertical.

Data is always left-aligned, and Header(false) has no effect.

func (*Table) Width

func (t *Table) Width() int

Width gets the display width of the table, including any padding characters.

The width may grow if more rows are added.

Version
v0.0.0-20220402233549-aeb28219db50 (latest)
Published
Apr 2, 2022
Platform
linux/amd64
Imports
5 packages (graph)
Last checked
1 month ago

Tools for package owners.