stable

package module
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Dec 23, 2023 License: MIT Imports: 11 Imported by: 3

README

stable - streaming pretty text table

Go Reference

If you just need an executable tool to format tables, please use csvtk pretty (code, usage and example), which uses this package.

Table of Contents

Features

  • Supporting streaming output (optional).

    When a writer is configured, a newly added row is formatted and written to the writer immediately. It is memory-effective for a large number of rows. And it is helpful to pipe the data in shell.

  • Supporting wrapping text or clipping text.

    The minimum and maximum width of the column can be configured for each column or globally.

  • Configured table styles.

    Some preset styles are also provided.

  • Unicode supported

Not-supported features:

  • Row/column span
  • Colorful text

Install

go get -u github.com/shenwei356/table

Examples

Note that the output is well-formatted in the terminal. However, rows containing Unicode are not displayed appropriately in text editors and browsers.

  1. Basic usages.

     tbl := New().HumanizeNumbers().MaxWidth(40)
    
     tbl.Header([]string{
         "id",
         "name",
         "sentence",
     })
     tbl.AddRow([]interface{}{100, "Donec Vitae", "Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse."})
     tbl.AddRow([]interface{}{2000, "Quaerat Voluptatem", "At vero eos et accusamus et iusto odio."})
     tbl.AddRow([]interface{}{3000000, "Aliquam lorem", "Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero."})
    
     fmt.Printf("%s\n", tbl.Render(StyleGrid))
    
     +-----------+--------------------+------------------------------------------+
     | id        | name               | sentence                                 |
     +===========+====================+==========================================+
     | 100       | Donec Vitae        | Quis autem vel eum iure reprehenderit    |
     |           |                    | qui in ea voluptate velit esse.          |
     +-----------+--------------------+------------------------------------------+
     | 2,000     | Quaerat Voluptatem | At vero eos et accusamus et iusto odio.  |
     +-----------+--------------------+------------------------------------------+
     | 3,000,000 | Aliquam lorem      | Curabitur ullamcorper ultricies nisi.    |
     |           |                    | Nam eget dui. Etiam rhoncus. Maecenas    |
     |           |                    | tempus, tellus eget condimentum          |
     |           |                    | rhoncus, sem quam semper libero.         |
     +-----------+--------------------+------------------------------------------+
    
  2. Unicode.

     tbl := New().HumanizeNumbers().MaxWidth(20) //.ClipCell("...")
    
     tbl.Header([]string{
         "id",
         "name",
         "sentence",
     })
     tbl.AddRow([]interface{}{100, "Wei Shen", "How are you?"})
     tbl.AddRow([]interface{}{1000, "沈 伟", "I'm fine, thank you. And you?"})
     tbl.AddRow([]interface{}{100000, "沈伟", "谢谢,我很好,你呢?"})
    
     fmt.Printf("%s\n", tbl.Render(StyleGrid))
    
     style: grid
     +---------+----------+----------------------+
     | id      | name     | sentence             |
     +=========+==========+======================+
     | 100     | Wei Shen | How are you?         |
     +---------+----------+----------------------+
     | 1,000   | 沈 伟    | I'm fine, thank      |
     |         |          | you. And you?        |
     +---------+----------+----------------------+
     | 100,000 | 沈伟     | 谢谢,我很好         |
     |         |          | ,你呢?             |
     +---------+----------+----------------------+
    

     // clipping text instead of wrapping
    
     fmt.Printf("%s\n", tbl.ClipCell("...").Render(StyleGrid))
    
     +---------+----------+----------------------+
     | id      | name     | sentence             |
     +=========+==========+======================+
     | 100     | Wei Shen | How are you?         |
     +---------+----------+----------------------+
     | 1,000   | 沈 伟    | I'm fine, thank y... |
     +---------+----------+----------------------+
     | 100,000 | 沈伟     | 谢谢,我很好,你呢? |
     +---------+----------+----------------------+
    

  3. Custom columns format.

     tbl := New()
    
     tbl.HeaderWithFormat([]Column{
         {Header: "number", MinWidth: 5, MaxWidth: 10, HumanizeNumbers: true, Align: AlignRight},
         {Header: "name", MinWidth: 10, MaxWidth: 16, Align: AlignCenter},
         {Header: "sentence", MaxWidth: 40, Align: AlignLeft},
     })
     tbl.AddRow([]interface{}{100, "Donec Vitae", "Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse."})
     tbl.AddRow([]interface{}{2000, "Quaerat Voluptatem", "At vero eos et accusamus et iusto odio."})
     tbl.AddRow([]interface{}{3000000, "Aliquam lorem", "Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero."})
    
     fmt.Printf("%s\n", tbl.Render(StyleGrid))
    
     +------------+-----------------+------------------------------------------+
     |     number |      name       | sentence                                 |
     +============+=================+==========================================+
     |        100 |   Donec Vitae   | Quis autem vel eum iure reprehenderit    |
     |            |                 | qui in ea voluptate velit esse.          |
     +------------+-----------------+------------------------------------------+
     |      2,000 |    Quaerat      | At vero eos et accusamus et iusto odio.  |
     |            |   Voluptatem    |                                          |
     +------------+-----------------+------------------------------------------+
     |  3,000,000 |  Aliquam lorem  | Curabitur ullamcorper ultricies nisi.    |
     |            |                 | Nam eget dui. Etiam rhoncus. Maecenas    |
     |            |                 | tempus, tellus eget condimentum          |
     |            |                 | rhoncus, sem quam semper libero.         |
     +------------+-----------------+------------------------------------------+
    
  4. Streaming the output, i.e., a newly added row is formatted and written to the configured writer immediately.

     tbl := New().MinWidth(10)
    
     // write to stdout, and determine the max width according to the first row
     tbl.Writer(os.Stdout, 1)
     tbl.Style(StyleGrid)
    
     tbl.Header([]string{
         "number",
         "name",
         "sentence",
     })
    
     // when a new row is added, it writes to stdout immediately.
     tbl.AddRow([]interface{}{100, "Donec Vitae", "Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse."})
     tbl.AddRow([]interface{}{2000, "Quaerat Voluptatem", "At vero eos et accusamus et iusto odio."})
     tbl.AddRow([]interface{}{3000000, "Aliquam lorem", "Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero."})
    
     // flush the remaining data
     tbl.Flush()
    
    
     +------------+-------------+-----------------------------------------------------------------------+
     | number     | name        | sentence                                                              |
     +============+=============+=======================================================================+
     | 100        | Donec Vitae | Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse. |
     +------------+-------------+-----------------------------------------------------------------------+
     | 2000       | Quaerat     | At vero eos et accusamus et iusto odio.                               |
     |            | Voluptatem  |                                                                       |
     +------------+-------------+-----------------------------------------------------------------------+
     | 3000000    | Aliquam     | Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus.    |
     |            | lorem       | Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper     |
     |            |             | libero.                                                               |
     +------------+-------------+-----------------------------------------------------------------------+
    
  5. Custom delimiter for wrapping text. In this example, complete lineage contains a list of words joined with ;.

     tbl := New()
    
     tbl.SetHeader([]string{
         "taxid",
         "name",
         "complete lineage",
     })
     tbl.AddRow([]interface{}{
         9606,
         "Homo sapiens",
         "cellular organisms;Eukaryota;Opisthokonta;Metazoa;Eumetazoa;Bilateria;Deuterostomia;Chordata;Craniata;Vertebrata;Gnathostomata;Teleostomi;Euteleostomi;Sarcopterygii;Dipnotetrapodomorpha;Tetrapoda;Amniota;Mammalia;Theria;Eutheria;Boreoeutheria;Euarchontoglires;Primates;Haplorrhini;Simiiformes;Catarrhini;Hominoidea;Hominidae;Homininae;Homo;Homo sapiens",
     })
     tbl.AddRow([]interface{}{
         562, "Escherichia coli",
         "cellular organisms;Bacteria;Pseudomonadota;Gammaproteobacteria;Enterobacterales;Enterobacteriaceae;Escherichia;Escherichia coli",
     })
    
     fmt.Printf("%s\n", tbl.WrapDelimiter(';').AlignLeft().MaxWidth(50).Render(StyleGrid))
    
     +-------+------------------+----------------------------------------------------+
     | taxid | name             | complete lineage                                   |
     +=======+==================+====================================================+
     | 9606  | Homo sapiens     | cellular organisms;Eukaryota;Opisthokonta;Metazoa; |
     |       |                  | Eumetazoa;Bilateria;Deuterostomia;Chordata;        |
     |       |                  | Craniata;Vertebrata;Gnathostomata;Teleostomi;      |
     |       |                  | Euteleostomi;Sarcopterygii;Dipnotetrapodomorpha;   |
     |       |                  | Tetrapoda;Amniota;Mammalia;Theria;Eutheria;        |
     |       |                  | Boreoeutheria;Euarchontoglires;Primates;           |
     |       |                  | Haplorrhini;Simiiformes;Catarrhini;Hominoidea;     |
     |       |                  | Hominidae;Homininae;Homo;Homo sapiens              |
     +-------+------------------+----------------------------------------------------+
     | 562   | Escherichia coli | cellular organisms;Bacteria;Pseudomonadota;        |
     |       |                  | Gammaproteobacteria;Enterobacterales;              |
     |       |                  | Enterobacteriaceae;Escherichia;Escherichia coli    |
     +-------+------------------+----------------------------------------------------+
    

Styles

Note that the output is well-formatted in the terminal. However, rows containing Unicode are not displayed appropriately in text editors and browsers.

style: plain
id          name                 sentence
100         Donec Vitae          Quis autem vel eum iure reprehenderit
                                 qui in ea voluptate velit esse.
2,000       Quaerat Voluptatem   At vero eos et accusamus et iusto odio.
3,000,000   Aliquam lorem        Curabitur ullamcorper ultricies nisi.
                                 Nam eget dui. Etiam rhoncus. Maecenas
                                 tempus, tellus eget condimentum
                                 rhoncus, sem quam semper libero.

style: simple
---------------------------------------------------------------------------
id          name                 sentence
---------------------------------------------------------------------------
100         Donec Vitae          Quis autem vel eum iure reprehenderit
                                qui in ea voluptate velit esse.
2,000       Quaerat Voluptatem   At vero eos et accusamus et iusto odio.
3,000,000   Aliquam lorem        Curabitur ullamcorper ultricies nisi.
                                Nam eget dui. Etiam rhoncus. Maecenas
                                tempus, tellus eget condimentum
                                rhoncus, sem quam semper libero.
---------------------------------------------------------------------------


style: 3line
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
id          name                 sentence
---------------------------------------------------------------------------
100         Donec Vitae          Quis autem vel eum iure reprehenderit
                                qui in ea voluptate velit esse.
2,000       Quaerat Voluptatem   At vero eos et accusamus et iusto odio.
3,000,000   Aliquam lorem        Curabitur ullamcorper ultricies nisi.
                                Nam eget dui. Etiam rhoncus. Maecenas
                                tempus, tellus eget condimentum
                                rhoncus, sem quam semper libero.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━


style: grid
+-----------+--------------------+------------------------------------------+
| id        | name               | sentence                                 |
+===========+====================+==========================================+
| 100       | Donec Vitae        | Quis autem vel eum iure reprehenderit    |
|           |                    | qui in ea voluptate velit esse.          |
+-----------+--------------------+------------------------------------------+
| 2,000     | Quaerat Voluptatem | At vero eos et accusamus et iusto odio.  |
+-----------+--------------------+------------------------------------------+
| 3,000,000 | Aliquam lorem      | Curabitur ullamcorper ultricies nisi.    |
|           |                    | Nam eget dui. Etiam rhoncus. Maecenas    |
|           |                    | tempus, tellus eget condimentum          |
|           |                    | rhoncus, sem quam semper libero.         |
+-----------+--------------------+------------------------------------------+

style: light
┌-----------┬--------------------┬------------------------------------------┐
| id        | name               | sentence                                 |
├===========┼====================┼==========================================┤
| 100       | Donec Vitae        | Quis autem vel eum iure reprehenderit    |
|           |                    | qui in ea voluptate velit esse.          |
├-----------┼--------------------┼------------------------------------------┤
| 2,000     | Quaerat Voluptatem | At vero eos et accusamus et iusto odio.  |
├-----------┼--------------------┼------------------------------------------┤
| 3,000,000 | Aliquam lorem      | Curabitur ullamcorper ultricies nisi.    |
|           |                    | Nam eget dui. Etiam rhoncus. Maecenas    |
|           |                    | tempus, tellus eget condimentum          |
|           |                    | rhoncus, sem quam semper libero.         |
└-----------┴--------------------┴------------------------------------------┘

style: bold
┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ id        ┃ name               ┃ sentence                                 ┃
┣━━━━━━━━━━━╋━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
┃ 100       ┃ Donec Vitae        ┃ Quis autem vel eum iure reprehenderit    ┃
┃           ┃                    ┃ qui in ea voluptate velit esse.          ┃
┣━━━━━━━━━━━╋━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
┃ 2,000     ┃ Quaerat Voluptatem ┃ At vero eos et accusamus et iusto odio.  ┃
┣━━━━━━━━━━━╋━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
┃ 3,000,000 ┃ Aliquam lorem      ┃ Curabitur ullamcorper ultricies nisi.    ┃
┃           ┃                    ┃ Nam eget dui. Etiam rhoncus. Maecenas    ┃
┃           ┃                    ┃ tempus, tellus eget condimentum          ┃
┃           ┃                    ┃ rhoncus, sem quam semper libero.         ┃
┗━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

style: double
╔═══════════╦════════════════════╦══════════════════════════════════════════╗
║ id        ║ name               ║ sentence                                 ║
╠═══════════╬════════════════════╬══════════════════════════════════════════╣
║ 100       ║ Donec Vitae        ║ Quis autem vel eum iure reprehenderit    ║
║           ║                    ║ qui in ea voluptate velit esse.          ║
╠═══════════╬════════════════════╬══════════════════════════════════════════╣
║ 2,000     ║ Quaerat Voluptatem ║ At vero eos et accusamus et iusto odio.  ║
╠═══════════╬════════════════════╬══════════════════════════════════════════╣
║ 3,000,000 ║ Aliquam lorem      ║ Curabitur ullamcorper ultricies nisi.    ║
║           ║                    ║ Nam eget dui. Etiam rhoncus. Maecenas    ║
║           ║                    ║ tempus, tellus eget condimentum          ║
║           ║                    ║ rhoncus, sem quam semper libero.         ║
╚═══════════╩════════════════════╩══════════════════════════════════════════╝

Support

Please open an issue to report bugs, propose new functions or ask for help.

License

Copyright (c) 2023, Wei Shen (shenwei356@gmail.com)

MIT License

Alternate packages

  • go-prettytable, it does not support wrapping cells and it's not flexible to add rows that the number of columns is dynamic.
  • gotabulate, it supports wrapping cells, but it has to read all data in memory before outputing the result. We followed the configuration of table styles from this package.
  • go-pretty, it supports wrapping cells, but it has to read all data in memory before outputing the result. We used some table styles with minor differences in this package.
  • table, it renders colorful texts, and supports Multicolumns and nested tables.

Documentation

Overview

Copyright © 2023 Wei Shen <shenwei356@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Copyright © 2023 Wei Shen <shenwei356@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Copyright © 2023 Wei Shen <shenwei356@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Index

Constants

This section is empty.

Variables

View Source
var ErrAddRowAfterFlush = fmt.Errorf("stable: calling AddRow is not allowed after calling Flush()")
View Source
var ErrInvalidAlign = fmt.Errorf("stable: invalid align value")

ErrInvalidAlign means a invalid align value is given.

View Source
var ErrNoDataAdded = fmt.Errorf("stable: no data added")

ErrNoDataAdded means not data is added. Not used.

View Source
var ErrSetHeaderAfterDataAdded = fmt.Errorf("stable: setting header is not allowed after some data being added")

-------------------------------------------------------------------------- ErrSetHeaderAfterDataAdded means that setting header is not allowed after some data being added.

View Source
var ErrUnmatchedColumnNumber = fmt.Errorf("stable: unmatched column number")

ErrUnmatchedColumnNumber means that the column number of the newly added row is not matched with that of previous ones.

View Source
var ErrWriterRepeatedlySet = fmt.Errorf("stable: writer repeatedly set")

ErrWriterRepeatedlySet means that the writer is repeatedly set.

View Source
var StyleBold = &TableStyle{
	Name: "bold",

	LineTop:         LineStyle{"┏", "━", "┳", "┓"},
	LineBelowHeader: LineStyle{"┣", "━", "╋", "┫"},
	LineBetweenRows: LineStyle{"┣", "━", "╋", "┫"},
	LineBottom:      LineStyle{"┗", "━", "┻", "┛"},

	HeaderRow: RowStyle{"┃", "┃", "┃"},
	DataRow:   RowStyle{"┃", "┃", "┃"},
	Padding:   " ",
}
View Source
var StyleDouble = &TableStyle{
	Name: "double",

	LineTop:         LineStyle{"╔", "═", "╦", "╗"},
	LineBelowHeader: LineStyle{"╠", "═", "╬", "╣"},
	LineBetweenRows: LineStyle{"╠", "═", "╬", "╣"},
	LineBottom:      LineStyle{"╚", "═", "╩", "╝"},

	HeaderRow: RowStyle{"║", "║", "║"},
	DataRow:   RowStyle{"║", "║", "║"},
	Padding:   " ",
}
View Source
var StyleGrid = &TableStyle{
	Name: "grid",

	LineTop:         LineStyle{"+", "-", "+", "+"},
	LineBelowHeader: LineStyle{"+", "=", "+", "+"},
	LineBetweenRows: LineStyle{"+", "-", "+", "+"},
	LineBottom:      LineStyle{"+", "-", "+", "+"},

	HeaderRow: RowStyle{"|", "|", "|"},
	DataRow:   RowStyle{"|", "|", "|"},
	Padding:   " ",
}
View Source
var StyleLight = &TableStyle{
	Name: "light",

	LineTop:         LineStyle{"┌", "-", "┬", "┐"},
	LineBelowHeader: LineStyle{"├", "=", "┼", "┤"},
	LineBetweenRows: LineStyle{"├", "-", "┼", "┤"},
	LineBottom:      LineStyle{"└", "-", "┴", "┘"},

	HeaderRow: RowStyle{"|", "|", "|"},
	DataRow:   RowStyle{"|", "|", "|"},
	Padding:   " ",
}
View Source
var StylePlain = &TableStyle{
	Name: "plain",

	HeaderRow: RowStyle{"", "   ", ""},
	DataRow:   RowStyle{"", "   ", ""},
	Padding:   "",
}
View Source
var StyleSimple = &TableStyle{
	Name: "simple",

	LineTop:         LineStyle{"", "-", "-", ""},
	LineBelowHeader: LineStyle{"", "-", "-", ""},
	LineBottom:      LineStyle{"", "-", "-", ""},

	HeaderRow: RowStyle{"", " ", ""},
	DataRow:   RowStyle{"", " ", ""},
	Padding:   " ",
}
View Source
var StyleThreeLine = &TableStyle{
	Name: "3line",

	LineTop:         LineStyle{"", "━", "━", ""},
	LineBelowHeader: LineStyle{"", "-", "-", ""},
	LineBottom:      LineStyle{"", "━", "━", ""},

	HeaderRow: RowStyle{"", " ", ""},
	DataRow:   RowStyle{"", " ", ""},
	Padding:   " ",
}

Functions

This section is empty.

Types

type Align

type Align int

Align is the type of text alignment. Actually, there are only 3 values.

const (
	AlignLeft Align = iota + 1
	AlignCenter
	AlignRight
)

func (Align) String

func (a Align) String() string

type Column

type Column struct {
	Header string // column name
	Align  Align  // text align

	MinWidth int // minimum width
	MaxWidth int // maximum width, it will be overrided by the global MaxWidth of the table

	HumanizeNumbers bool // add comma to numbers, for example 1000 -> 1,000
}

Column is the configuration of a column.

type LineStyle

type LineStyle struct {
	Begin string
	Hline string
	Sep   string
	End   string
}

func (LineStyle) Visible

func (s LineStyle) Visible() bool

type RowStyle

type RowStyle struct {
	Begin string
	Sep   string
	End   string
}

type Table

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

Table is the table struct.

func New

func New() *Table

New creates a new Table object.

func (*Table) AddRow

func (t *Table) AddRow(row []interface{}) error

AddRow adds a row.

func (*Table) AddRowStringSlice

func (t *Table) AddRowStringSlice(row []string) error

func (*Table) Align

func (t *Table) Align(align Align) (*Table, error)

Align sets the global text alignment. Only three values are allowed: AlignLeft, AlignCenter, AlignRight.

func (*Table) AlignCenter

func (t *Table) AlignCenter() *Table

AlignCenter sets the global text alignment as Center.

func (*Table) AlignLeft

func (t *Table) AlignLeft() *Table

AlignLeft sets the global text alignment as Left.

func (*Table) AlignRight

func (t *Table) AlignRight() *Table

AlignRight sets the global text alignment as Right.

func (*Table) ClipCell

func (t *Table) ClipCell(mark string) *Table

ClipCell sets the mark to indicate the cell is clipped.

func (*Table) Flush

func (t *Table) Flush()

Flush dumps the remaining data.

func (*Table) HasHeaders added in v0.1.3

func (t *Table) HasHeaders() bool

HasHeaders tell whether the table has an available header line. It may return false even if you have called Header() or HeaderWithFormat(), when all headers are empty strings.

func (*Table) Header

func (t *Table) Header(headers []string) (*Table, error)

Header sets column names.

func (*Table) HeaderWithFormat

func (t *Table) HeaderWithFormat(headers []Column) (*Table, error)

HeaderWithFormat sets column names and other configuration of the column.

func (*Table) HumanizeNumbers

func (t *Table) HumanizeNumbers() *Table

HumanizeNumbers makes the numbers more readable by adding commas to numbers. E.g., 1000 -> 1,000.

func (*Table) MaxWidth

func (t *Table) MaxWidth(w int) *Table

MaxWidth sets the global maximum cell width.

func (*Table) MinWidth

func (t *Table) MinWidth(w int) *Table

MinWidth sets the global minimum cell width.

func (*Table) Render

func (t *Table) Render(style *TableStyle) []byte

Render render all data with give style.

func (*Table) Style

func (t *Table) Style(style *TableStyle) *Table

Style sets the output style. If you decide to add all rows before rendering, there's no need to call this method. If you want to stream the output, please call this method before adding any rows.

func (*Table) WrapDelimiter

func (t *Table) WrapDelimiter(d rune) *Table

WrapDelimiter sets the delimiter for wrapping cell text. The default value is space. Note that in streaming mode (after calling SetWriter())

func (*Table) Writer

func (t *Table) Writer(w io.Writer, bufRows uint) error

Writer sets a writer for render the table. The first bufRows rows will be used to determine the maximum width for each cell if they are not defined with MaxWidth(). bufRows should be in range of [1,1M]. If bufRows is 0, it keeps all data in buffer. So a newly added row (Addrow()) is formatted and written to the configured writer immediately. It is memory-effective for a large number of rows. And it is helpful to pipe the data in shell. Do not forget to call Flush() after adding all rows.

type TableStyle

type TableStyle struct {
	Name string

	LineTop         LineStyle
	LineBelowHeader LineStyle
	LineBetweenRows LineStyle
	LineBottom      LineStyle

	HeaderRow RowStyle
	DataRow   RowStyle
	Padding   string
}

The data structures are similar to these in https://github.com/bndr/gotabulate.

Jump to

Keyboard shortcuts

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