goterm

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Jan 25, 2022 License: MIT Imports: 11 Imported by: 358

README

Description

This library provides basic building blocks for building advanced console UIs.

Initially created for Gor.

Full API documentation: http://godoc.org/github.com/buger/goterm

Basic usage

Full screen console app, printing current time:

import (
    tm "github.com/buger/goterm"
    "time"
)

func main() {
    tm.Clear() // Clear current screen

    for {
        // By moving cursor to top-left position we ensure that console output
        // will be overwritten each time, instead of adding new.
        tm.MoveCursor(1,1)

        tm.Println("Current Time:", time.Now().Format(time.RFC1123))

        tm.Flush() // Call it every time at the end of rendering

        time.Sleep(time.Second)
    }
}

This can be seen in examples/time_example.go. To run it yourself, go into your $GOPATH/src/github.com/buger/goterm directory and run go run ./examples/time_example.go

Print red bold message on white background:

tm.Println(tm.Background(tm.Color(tm.Bold("Important header"), tm.RED), tm.WHITE))

Create box and move it to center of the screen:

tm.Clear()

// Create Box with 30% width of current screen, and height of 20 lines
box := tm.NewBox(30|tm.PCT, 20, 0)

// Add some content to the box
// Note that you can add ANY content, even tables
fmt.Fprint(box, "Some box content")

// Move Box to approx center of the screen
tm.Print(tm.MoveTo(box.String(), 40|tm.PCT, 40|tm.PCT))

tm.Flush()

This can be found in examples/box_example.go.

Draw table:

// Based on http://golang.org/pkg/text/tabwriter
totals := tm.NewTable(0, 10, 5, ' ', 0)
fmt.Fprintf(totals, "Time\tStarted\tActive\tFinished\n")
fmt.Fprintf(totals, "%s\t%d\t%d\t%d\n", "All", started, started-finished, finished)
tm.Println(totals)
tm.Flush()

This can be found in examples/table_example.go.

Line charts

Chart example:

screen shot 2013-07-09 at 5 05 37 pm

    import (
        tm "github.com/buger/goterm"
    )

    chart := tm.NewLineChart(100, 20)
    
    data := new(tm.DataTable)
    data.AddColumn("Time")
    data.AddColumn("Sin(x)")
    data.AddColumn("Cos(x+1)")

    for i := 0.1; i < 10; i += 0.1 {
	data.AddRow(i, math.Sin(i), math.Cos(i+1))
    }
    
    tm.Println(chart.Draw(data))

This can be found in examples/chart_example.go.

Drawing 2 separate graphs in different scales. Each graph have its own Y axe.

chart.Flags = tm.DRAW_INDEPENDENT

Drawing graph with relative scale (Grapwh draw starting from min value instead of zero)

chart.Flags = tm.DRAW_RELATIVE

Documentation

Overview

Provides basic bulding blocks for advanced console UI

Coordinate system:

1/1---X---->
 |
 Y
 |
 v

Documentation for ANSI codes: http://en.wikipedia.org/wiki/ANSI_escape_code#Colors

Inspired by: http://www.darkcoding.net/software/pretty-command-line-console-output-on-unix-in-python-and-go-lang/

Index

Constants

View Source
const (
	AXIS_LEFT = iota
	AXIS_RIGHT
)
View Source
const (
	DRAW_INDEPENDENT = 1 << iota
	DRAW_RELATIVE
)
View Source
const (
	BLACK = iota
	RED
	GREEN
	YELLOW
	BLUE
	MAGENTA
	CYAN
	WHITE
)

List of possible colors

View Source
const DEFAULT_BORDER = "- │ ┌ ┐ └ ┘"
View Source
const PCT = 0x8000 << shift
View Source
const RESET = "\033[0m"

Reset all custom styles

View Source
const RESET_COLOR = "\033[32m"

Reset to default color

View Source
const RESET_LINE = "\r\033[K"

Return cursor to start of line and clean it

Variables

View Source
var ANSI_RE = regexp.MustCompile(`\\0\d+\[\d+(?:;\d+)?m`)

Global screen buffer Its not recommended write to buffer dirrectly, use package Print,Printf,Println fucntions instead.

Functions

func Background

func Background(str string, color int) string

Change background color of string:

tm.Background("string", tm.RED)

func Bold

func Bold(str string) string

Make bold

func Clear

func Clear()

Clear screen

func Color

func Color(str string, color int) string

Apply given color to string:

tm.Color("RED STRING", tm.RED)

func Context

func Context(data string, idx, max int) string

func CurrentHeight

func CurrentHeight() int

CurrentHeight gets current height. Line count in Screen buffer.

func Flush

func Flush()

Flush buffer and ensure that it will not overflow screen

func GetXY

func GetXY(x int, y int) (int, int)

GetXY gets relative or absolute coordinates To get relative, set PCT flag to number:

// Get 10% of total width to `x` and 20 to y
x, y = tm.GetXY(10|tm.PCT, 20)

func Height

func Height() int

Height gets console height

func Highlight

func Highlight(str, substr string, color int) string

func HighlightRegion

func HighlightRegion(str string, from, to, color int) string

func MoveCursor

func MoveCursor(x int, y int)

Move cursor to given position

func MoveCursorBackward

func MoveCursorBackward(bias int)

Move cursor backward relative the current position

func MoveCursorDown

func MoveCursorDown(bias int)

Move cursor down relative the current position

func MoveCursorForward

func MoveCursorForward(bias int)

Move cursor forward relative the current position

func MoveCursorUp

func MoveCursorUp(bias int)

Move cursor up relative the current position

func MoveTo

func MoveTo(str string, x int, y int) (out string)

Move string to possition

func Print

func Print(a ...interface{}) (n int, err error)

func Printf

func Printf(format string, a ...interface{}) (n int, err error)

func Println

func Println(a ...interface{}) (n int, err error)

func ResetLine

func ResetLine(str string) (out string)

ResetLine returns carrier to start of line

func Width

func Width() int

Width gets console width

Types

type Box

type Box struct {
	Buf *bytes.Buffer

	Width  int
	Height int

	// To get even padding: PaddingX ~= PaddingY*4
	PaddingX int
	PaddingY int

	// Should contain 6 border pieces separated by spaces
	//
	// Example border:
	//   "- │ ┌ ┐ └ ┘"
	Border string

	Flags int // Not used now
}

Box allows you to create independent parts of screen, with its own buffer and borders. Can be used for creating modal windows

Generates boxes likes this: ┌--------┐ │hello │ │world │ │ │ └--------┘

func NewBox

func NewBox(width, height int, flags int) *Box

Create new Box. Width and height can be relative:

// Create box with 50% with of current screen and 10 lines height
box := tm.NewBox(50|tm.PCT, 10, 0)

func (*Box) String

func (b *Box) String() (out string)

String renders Box

func (*Box) Write

func (b *Box) Write(p []byte) (int, error)

type Chart

type Chart interface {
	Draw(data DataTable, flags int) string
}

type DataTable

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

func (*DataTable) AddColumn

func (d *DataTable) AddColumn(name string)

func (*DataTable) AddRow

func (d *DataTable) AddRow(elms ...float64)

type LineChart

type LineChart struct {
	Buf []string

	Width  int
	Height int

	Flags int
	// contains filtered or unexported fields
}

func NewLineChart

func NewLineChart(width, height int) *LineChart

func (*LineChart) Draw

func (c *LineChart) Draw(data *DataTable) (out string)

func (*LineChart) DrawAxes

func (c *LineChart) DrawAxes(maxX, minX, maxY, minY float64, index int)

func (*LineChart) DrawLine

func (c *LineChart) DrawLine(x0, y0, x1, y1 int, symbol string)

type Table

type Table struct {
	tabwriter.Writer

	Buf *bytes.Buffer
}

Tabwriter with own buffer:

    	totals := tm.NewTable(0, 10, 5, ' ', 0)
		fmt.Fprintf(totals, "Time\tStarted\tActive\tFinished\n")
		fmt.Fprintf(totals, "%s\t%d\t%d\t%d\n", "All", started, started-finished, finished)
		tm.Println(totals)

 Based on http://golang.org/pkg/text/tabwriter

func NewTable

func NewTable(minwidth, tabwidth, padding int, padchar byte, flags uint) *Table

Same as here http://golang.org/pkg/text/tabwriter/#Writer.Init

func (*Table) String

func (t *Table) String() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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