termtables

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2019 License: Apache-2.0 Imports: 12 Imported by: 0

README

termtables

Actions Status GoDoc Go Report Card

A Go port of the Ruby library terminal-tables for fast and simple ASCII table generation. This project was originally created by Apcera and adopted here when they removed it from GitHub.

Installation

go get github.com/ajankovic/termtables

or add as a Go module

APC Command Line usage

--markdown — output a markdown table, e.g. apc app list --markdown

--html — output an html table, e.g. apc app list --html

--ascii — output an ascii table, e.g. apc app list --ascii

Basic Usage

package main

import (
  "fmt"
  termtables "github.com/ajankovic/termtables"
)

func main() {
  table := termtables.CreateTable()

  table.AddHeaders("Name", "Age")
  table.AddRow("John", "30")
  table.AddRow("Sam", 18)
  table.AddRow("Julie", 20.14)

  fmt.Println(table.Render())
}

Result:

+-------+-------+
| Name  | Age   |
+-------+-------+
| John  | 30    |
| Sam   | 18    |
| Julie | 20.14 |
+-------+-------+

Advanced Usage

The package function-call EnableUTF8() will cause any tables created after that point to use Unicode box-drawing characters for the table lines.

Calling EnableUTF8PerLocale() uses the C library's locale functionality to determine if the current locale environment variables say that the current character map is UTF-8. If, and only if, so, then EnableUTF8() will be called.

Calling SetModeHTML(true) will cause any tables created after that point to be emitted in HTML, while SetModeMarkdown(true) will trigger Markdown. Neither should result in changes to later API to get the different results; the primary intended use-case is extracting the same table, but for documentation.

The table method .AddSeparator() inserts a rule line in the output. This only applies in normal terminal output mode.

The table method .AddTitle() adds a title to the table; in terminal output, this is an initial row; in HTML, it's a caption. In Markdown, it's a line of text before the table, prefixed by Table: .

The table method .SetAlign() takes an alignment and a column number (indexing starts at 1) and changes all current cells in that column to have the given alignment. It does not change the alignment of cells added to the table after this call. Alignment is only stored on a per-cell basis.

Known Issues

Normal output:

  • .SetAlign() does not affect headers.

Markdown output mode:

  • When emitting Markdown, the column markers are not re-flowed if a vertical bar is an element of a cell, causing an escape to take place; since Markdown is often converted to HTML, this only affects text viewing.
  • A title in Markdown is not escaped against all possible forms of Markdown markup (to avoid adding a dependency upon a Markdown library, as supported syntax can vary).
  • Markdown requires headers, so a dummy header will be inserted if needed.
  • Table alignment is not reflected in Markdown output.

Documentation

Index

Constants

View Source
const (
	TitleAsCaption titleStyle = iota
	TitleAsThSpan
)
View Source
const (
	// LINE_INNER *must* be the default; where there are vertical lines drawn
	// across an inner line, the character at that position should indicate
	// that the vertical line goes both up and down from this horizontal line.
	LINE_INNER lineType = iota

	// LINE_TOP has only descenders
	LINE_TOP

	// LINE_SUBTOP has only descenders in the middle, but goes both up and
	// down at the far left & right edges.
	LINE_SUBTOP

	// LINE_BOTTOM has only ascenders.
	LINE_BOTTOM
)

These lines are for horizontal rules; these indicate desired styling, but simplistic (pure ASCII) markup characters may end up leaving the variant lines indistinguishable from LINE_INNER.

View Source
const (
	AlignLeft   = tableAlignment(1)
	AlignCenter = tableAlignment(2)
	AlignRight  = tableAlignment(3)
)

These constants control the alignment which should be used when rendering the content of a cell.

Variables

View Source
var DefaultStyle = &TableStyle{
	SkipBorder: false,
	BorderX:    "-", BorderY: "|", BorderI: "+",
	PaddingLeft: 1, PaddingRight: 1,
	Width:     80,
	Alignment: AlignLeft,
}

DefaultStyle is a TableStyle which can be used to get some simple default styling for a table, using ASCII characters for drawing borders.

View Source
var MaxColumns = 80

MaxColumns represents the maximum number of columns that are available for display without wrapping around the right-hand side of the terminal window. At program initialization, the value will be automatically set according to available sources of information, including the $COLUMNS environment variable and, on Unix, tty information.

Functions

func EnableUTF8

func EnableUTF8()

EnableUTF8 will unconditionally enable using UTF-8 box-drawing characters for any tables created after this call, as the default style.

func EnableUTF8PerLocale

func EnableUTF8PerLocale()

EnableUTF8PerLocale will use current locale character map information to determine if UTF-8 is expected and, if so, is equivalent to EnableUTF8.

func SetHTMLStyleTitle

func SetHTMLStyleTitle(want titleStyle)

SetHTMLStyleTitle lets an HTML title output mode be chosen.

func SetModeHTML

func SetModeHTML(onoff bool)

SetModeHTML will control whether or not new tables generated will be in HTML mode by default; HTML-or-not takes precedence over options which control how a terminal output will be rendered, such as whether or not to use UTF8. This affects any tables created after this call.

func SetModeMarkdown

func SetModeMarkdown(onoff bool)

SetModeMarkdown will control whether or not new tables generated will be in Markdown mode by default. HTML-mode takes precedence.

Types

type Cell

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

A Cell denotes one cell of a table; it spans one row and a variable number of columns. A given Cell can only be used at one place in a table; the act of adding the Cell to the table mutates it with position information, so do not create one "const" Cell to add it multiple times.

func CreateCell

func CreateCell(v interface{}, style *CellStyle) *Cell

CreateCell returns a Cell where the content is the supplied value, with the optional supplied style (which may be given as nil). The style can include a non-zero ColSpan to cause the cell to become column-spanning. Changing the style afterwards will not adjust the column-spanning state of the cell itself.

func (*Cell) Render

func (c *Cell) Render(style *renderStyle) (buffer string)

Render returns a string representing the content of the cell, together with padding (to the widths specified) and handling any alignment.

func (*Cell) Width

func (c *Cell) Width() int

Width returns the width of the content of the cell, measured in runes as best as possible considering sophisticated Unicode.

type CellStyle

type CellStyle struct {
	// Alignment indicates the alignment to be used in rendering the content
	Alignment tableAlignment

	// ColSpan indicates how many columns this Cell is expected to consume.
	ColSpan int
}

A CellStyle controls all style applicable to one Cell.

type Element

type Element interface {
	Render(*renderStyle) string
}

Element the interface that can draw a representation of the contents of a table cell.

type Row

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

A Row represents one row of a Table, consisting of some number of Cell items.

func CreateRow

func CreateRow(items []interface{}) *Row

CreateRow returns a Row where the cells are created as needed to hold each item given; each item can be a Cell or content to go into a Cell created to hold it.

func (*Row) AddCell

func (r *Row) AddCell(item interface{})

AddCell adds one item to a row as a new cell, where the item is either a Cell or content to be put into a cell.

func (*Row) HTML

func (r *Row) HTML(tag string, style *renderStyle) string

HTML returns an HTML representations of the contents of one row of a table.

func (*Row) Render

func (r *Row) Render(style *renderStyle) string

Render returns a string representing the content of one row of a table, where the Row contains Cells (not Separators) and the representation includes any vertical borders needed.

type Separator

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

A Separator is a horizontal rule line, with associated information which indicates where in a table it is, sufficient for simple cases to let clean tables be drawn. If a row-spanning cell is created, then this will be insufficient: we can get away with hand-waving of "well, it's showing where the border would be" but a more capable handling will require structure reworking. Patches welcome.

func (*Separator) Render

func (s *Separator) Render(style *renderStyle) string

Render returns the string representation of a horizontal rule line in the table.

type StraightSeparator

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

A StraightSeparator is a horizontal line with associated information about what sort of position it takes in the table, so as to control which shapes will be used where vertical lines are expected to touch this horizontal line.

func (*StraightSeparator) Render

func (s *StraightSeparator) Render(style *renderStyle) string

Render returns a string representing this separator, with all border crossings appropriately chosen.

type Table

type Table struct {
	Style *TableStyle
	// contains filtered or unexported fields
}

Table represents a terminal table. The Style can be directly accessed and manipulated; all other access is via methods.

func CreateTable

func CreateTable() *Table

CreateTable creates an empty Table using defaults for style.

func (*Table) AddHeaders

func (t *Table) AddHeaders(headers ...interface{})

AddHeaders supplies column headers for the table.

func (*Table) AddRow

func (t *Table) AddRow(items ...interface{}) *Row

AddRow adds the supplied items as cells in one row of the table.

func (*Table) AddSeparator

func (t *Table) AddSeparator()

AddSeparator adds a line to the table content, where the line consists of separator characters.

func (*Table) AddTitle

func (t *Table) AddTitle(title interface{})

AddTitle supplies a table title, which if present will be rendered as one cell across the width of the table, as the first row.

func (*Table) Render

func (t *Table) Render() string

Render returns a string representation of a fully rendered table, drawn out for display, with embedded newlines. If this table is in HTML mode, then this is equivalent to RenderHTML().

func (*Table) RenderHTML

func (t *Table) RenderHTML() (buffer string)

RenderHTML returns a string representation of a the table, suitable for inclusion as HTML elsewhere. Primary use-case controlling layout style is for inclusion into Markdown documents, documenting normal table use. Thus we leave the padding in place to have columns align when viewed as plain text and rely upon HTML ignoring extra whitespace.

func (*Table) SetAlign

func (t *Table) SetAlign(align tableAlignment, column int)

SetAlign changes the alignment for elements in a column of the table; alignments are stored with each cell, so cells added after a call to SetAlign will not pick up the change. Columns are numbered from 1.

func (*Table) SetHTMLStyleTitle

func (t *Table) SetHTMLStyleTitle(want titleStyle)

SetHTMLStyleTitle lets an HTML output mode be chosen; we should rework this into a more generic and extensible API as we clean up termtables.

func (*Table) SetModeHTML

func (t *Table) SetModeHTML()

SetModeHTML switches this table to be in HTML when rendered; the default depends upon whether the package function SetModeHTML() has been called, and with what value. This method forces the feature on for this table. Turning off involves choosing a different mode, per-table.

func (*Table) SetModeMarkdown

func (t *Table) SetModeMarkdown()

SetModeMarkdown switches this table to be in Markdown mode

func (*Table) SetModeTerminal

func (t *Table) SetModeTerminal()

SetModeTerminal switches this table to be in terminal mode.

func (*Table) UTF8Box

func (t *Table) UTF8Box()

UTF8Box sets the table style to use UTF-8 box-drawing characters, overriding all relevant style elements at the time of the call.

type TableStyle

type TableStyle struct {
	SkipBorder        bool
	BorderX           string
	BorderY           string
	BorderI           string
	BorderTop         string
	BorderBottom      string
	BorderRight       string
	BorderLeft        string
	BorderTopLeft     string
	BorderTopRight    string
	BorderBottomLeft  string
	BorderBottomRight string
	PaddingLeft       int
	PaddingRight      int
	Width             int
	Alignment         tableAlignment
	// contains filtered or unexported fields
}

TableStyle controls styling information for a Table as a whole.

For the Border rules, only X, Y and I are needed, and all have defaults. The others will all default to the same as BorderI.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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