termtools

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 6, 2021 License: MIT Imports: 4 Imported by: 1

README

module termtools

version 1.0.0

termtools is basically a collection of utilities to style console output on Linux systems. The module allows to colorize terminal output in a very simple and straighforward way. Most of the code is a wrapper around fmt module from Go's standard library.

termtools module also includes utility functions to control cursor position in the terminal.

Note: This README is NOT intended to document all of what termtools has to offer and only provides some usage examples. Please see full module documentation at https://pkg.go.dev/github.com/dmfed/termtools for a complete list of what is available.

Getting termtools

go get -u github.com/dmfed/termtools and you are good to Go :)

import "github.com/dmfed/termtools" to import module in you code

Basic usage

First of all you can directly use any ANSI escapes declared in the module. (For a complete list of exported constants see https://pkg.go.dev/github.com/dmfed/termtools.)

s := termtools.Red + "We're gophers" + termtools.Reset 	// adding escape for red and escape for color reset
fmt.Println(s) 						// the string "We're gophers" will output in red.

You can also get your string colorized using function similar to fmt.Sprint (same signature as Sprint, but first parameter is color name).

mystring := termtools.Csprint("red", "This will print in red") // Colorizes input string
fmt.Println(mystring)

See below for a full list of supported color names.

Using Printer

More clever way would be to use Printer.

var printer termtools.Printer 				// Initializes new Printer
printer.SetColor(9) 					// Sets color (9 is orange)
printer.Println("This will output in orange") 		// This prints in orange
printer.SetColor("red")					// Sets color
printer.Println("This will output in red")		// This prints in red
printer.ToggleUnderline()				// switches undeline mode on
printer.Println("This will output in undelined red")	// prints in underlined red

Font and backgrount colors can be set either by color name (supplied as string) or by color numeric id ranging from 0 to 255 inclusive. To set font or background color by name use printer.SetColor(colorname interface{}) and printer.SetBackground(colorname string) methods of Printer accordingly. See https://pkg.go.dev/github.com/dmfed/termtools for a complete list of Printer methods.

Supported color names are:

"black", "blue", "cyan", "green", "magenta", "red", "white", "yellow", "brightblack", "brightblue", "brightcyan", "brightgreen", "brightmagenta", "brightred", "brightwhite", "brightyellow"

Color numeric IDs are as follows:

image of palette with colors numbered 0-255

To see the above palette in your terminal git clone https://github.com/dmfed/termtools/ then cd into the repo and issue go test. The test will output known colors and the pallette with codes. See also see samples/palette.go

NOTE: colors may not display correctly in some shells and terminals depending on your settings.

Printer modes: bold, underline, reversed, blinking

Printer has four modes: bold, reversed, underline, and blinking. Bold, underline and blinking are self explanatory. Reversed mode if switched on swaps font and background colors). These modes can be toggled on and off with ToggleBold(), ToggleBlinking(), ToggleReversed(), and ToggleUnderline() methods of Printer. For a complete list of Printer methods see https://pkg.go.dev/github.com/dmfed/termtools.

NewPrinter

Printer instance can be initialized with all options set to needed values at once. Use termtools.NewPrinter() to set up instance of Printer as required.

The functions sugnature is as follows:

func NewPrinter(conf PrinterConfig) (p *Printer, err error)

It accepts PrinterConfig as single argument.

type PrinterConfig struct {
	Name       string
	Color      interface{}
	Background interface{}
	Bold       bool
	Underline  bool
	Reversed   bool
	Blinking   bool
	Prefix     string
	Suffix     string
}

Here is an example.

printer, err := termtools.NewPrinter(termtools.PrinterConfig{Color: "blue", Blinking: true})
if err != nil {
	printer.Println(err)
}
printer.Println("Printing in blue blinking here.")

Printing methods

Printer type implements most print methods as in fmt module from standard library copying their signatures, names and behaviour. You can call Println, Print, Sprint, Sprintf, Errorf etc. In fact printing methods just wrap around fmt module by adding required ANSI escapes to the original values passed.

For example fhe following adds color escape codes to the input and color reset escape at the end:

greenprinter := termtools.Printer{} 		// initializes new Printer
greenprinter.SetColor("green") 				// sets Printer color to green
s := greenprinter.Sprint("Hello, world!") 	// s now holds "Hello, world!" with green color prefix and reset suffix attached.

Note that len(greenprinter.Sprint("Hello, world!")) in the above example will not be the same as len(fmt.Sprint("Hello, world!")) because ANSI escapes actually add to the length of the output string. This might be annoying if you're trying to keep output centered horizontally and rely on calculation of string length.

For a detailed list of printing methods see package documention at pkg.go.dev

Moving cursor around

termtools includes functions and methods of Printer type to manipulate cursor position on screen, clear screen and delete lines of text.

func PrintCentered(s string) {
	x, y, _ := termtools.GetTermSize() 				// returns number of columns and rows in current terminal
	termtools.ClearScreen()						// clears screen
	fmt.Print(strings.Repeat("\n", y))
	s = termtools.ColorSprint("blue", s)				// sets input string color to blue
	termtools.PrintAtPositionAndReturn(x/2-len(s)/2, y/2, s)	// prints at requested position and returns cursor
}

Or using termtools.Printer

var p termtools.Printer
p.MoveTo(10,10)
p.Print("This starts at column 10, row 10")

termtools has the following functions to control cursor position (signatures are self-explanatory):

func MoveCursorTo(column, row int), func MoveCursorHome(), func MoveCursorUp(rows int), func MoveCursorDown(rows int), MoveCursorLeft(columns int), MoveCursorRight(columns int), MoveCursorToRow(row int), func MoveCursorToNextRow()

Most of this functionality is also implemented for termtools.Printer type with shorter and bit different names. See docs at pkg.go.dev

Clearing screen, deleting lines of text

termtools has the following set of functions available to delete lines of text and clear screen:

ClearScreen(), ClearScreenUp(), ClearScreenDown(), ClearLine(), ClearLineLeft(), ClearLineRight()

Using PrintSuite to style your program output

termtools.PrintSuite can act as an (almost) full replacement to fmt module from standard library. It is intended to hold one or more configurations of termtools.Printer and switch them on the fly. This way you can get different output styles for different kinds of messages in your program.

type PrintSuite struct {
	Printer
	// Has unexported field.
}

termtools.PrintSuite embeds default Printer, so you can call any printing method on it directly.

In example below we set up PrintSuite to be available globally in the program then configure two printers (red and green underlined).

We then can use (for example) red printer to display error messages and green printer to display success notifications.

Consider code below:

package main

import "github.com/dmfed/termtools"

var prnt = termtools.PrintSuite{} // here we define prnt globally to reuse it from any part of program

func setupPrinters() {
	configs := []termtools.PrinterConfig{
		{Name: "error", Color: "red"},
		{Name: "notify", Color: "green", Underline: true}}
	if err := prnt.Configure(configs...); err != nil {
		prnt.Println(err)
	}
}

func main() {
	setupPrinters()
	// We now can use different printers for different kinds of messages anywhere in out program.
	// For example print errors in red
	prnt.Use("error").Print("We call prnt.Use(\"error\").Print() to output using printer named \"error\"\n")

	// or print notifications in green
	prnt.Use("notify").Print("and prnt.Use(\"notify\").Print() to use printer named \"notify\"\n")

	// or use unstyled output of embedded printer for everything else like this:
	prnt.Println("This will print without any styling.")

	// or like this:
	prnt.UseDefault().Println("This will print without any styling.")
}

IMPORTANT: When passing termtools.PrinterConfig configuration(s) to PrintSuite Configure() method always make sure that Name field ot config(s) is NOT EMPTY. Otherwise Configure will fail with an error. Some of passed configurations (precceding the one that is missing name) may be processed and PrintSuite will still be usable but the mathod will terminate upon encountering config with empty Name field.

Note that Use() method in example above returns pointer to named printer, so you can call any Printer method directly. Also note that PrintSuite embeds Printer instance so any Printer method can be called on it without Use() (i.e prnt.Println("This will print without any styling.")). This will use embedded Printer instance.

To change embedded printer style use SwitchTo(printername string).

prnt.SwitchTo("notify")
prnt.Println("Call to prnt.Println (and other methods) from this point on will use \"notify\" style.")

To reset embedded Printer instance use SwitchToDefault()

prnt.SwitchToDefault()
prnt.Println("Call to prnt.Println will now act as simple call to fmt.Println again."

For a full list of PrintSuite methods see package documention at pkg.go.dev

Example programs

Some example programs are included in samples directory of the repo at https://github.com/dmfed/termtools/tree/main/samples

Here's the listing of one of the examples:

package main

import (
	"fmt"
	"math/rand"
	"time"

	tt "github.com/dmfed/termtools"
)

// PrintStair is an example function
func PrintStair(a ...interface{}) {
	rand.Seed(time.Now().UnixNano())
	var p tt.Printer            // initializes Printer
	_, y, _ := tt.GetTermSize() // gets size of terminal window
	y = y/2 - 6
	for xpos := 0; xpos <= 80; xpos = xpos + 5 {
		p.SetColorID(rand.Intn(256))
		p.PrintAtPosition(xpos, y, a...)
		y++
	}
	p.Reset()
}

func main() {
	// Simplest use is to call ColorSprint (same signature as in fmt.Sprint, but the
	// first argument is the name of the color).
	tt.ClearScreen()                                            // Clears Screen
	tt.MoveCursorTo(0, 0)                                       // Moves cursor to top left
	mystring := tt.ColorSprint("red", "This will print in red") // Colorizes input string
	fmt.Println(mystring)

	// Now using the Printer
	var p tt.Printer                                        // Initialize new Printer
	p.ToggleUnderline()                                     // Set Printer to print underlined
	p.SetColor("green")                                     // Set font color to green
	p.Println("Printing in green underlined with Printer.") // This will print in green underlined

	PrintStair("I'm a walrus!")
}

Please see https://pkg.go.dev/github.com/dmfed/termtools for a complete documentation of termtools.

That's all folks!

Thank you for reading this far :)

I hope you might find termtools useful. Any feedback is welcome.

I'm planning to freeze all function signatures in v1.0.0. Until then some functions signatures might change and I'm also considering adding and/or removing some stuff.

Documentation

Overview

Package termtools provides basic functionality to style console output on Linux

v1.0.0

See package README for usage examples: github.com/dmfed/termtools

General note concerning module usage: Whenever color value of type interface{} is required by signature of a method or function, either string or int may be supplied. Valid color names (to be passed as string) are: "black", "blue", "cyan", "green", "magenta", "red", "white", "yellow", "brightblack", "brightblue", "brightcyan", "brightgreen", "brightmagenta", "brightred", "brightwhite", "brightyellow". Valid color IDs (to be passed as int) are from 0 to 255 inclusive.

Index

Constants

View Source
const (
	// The following constants hold ANSI escape sequences setting color and style of output
	Esc string = "\x1b"

	//Basic 8 colors
	Black   string = Esc + "[30m"
	Red            = Esc + "[31m"
	Green          = Esc + "[32m"
	Yellow         = Esc + "[33m"
	Blue           = Esc + "[34m"
	Magenta        = Esc + "[35m"
	Cyan           = Esc + "[36m"
	White          = Esc + "[37m"

	//Additional 8 bright colors
	BrightBlack   string = Esc + "[30;1m"
	BrightRed            = Esc + "[31;1m"
	BrightGreen          = Esc + "[32;1m"
	BrightYellow         = Esc + "[33;1m"
	BrightBlue           = Esc + "[34;1m"
	BrightMagenta        = Esc + "[35;1m"
	BrightCyan           = Esc + "[36;1m"
	BrightWhite          = Esc + "[37;1m"

	//Basic 8 background colors
	BBlack   string = Esc + "[40m"
	BRed            = Esc + "[41m"
	BGreen          = Esc + "[42m"
	BYellow         = Esc + "[43m"
	BBlue           = Esc + "[44m"
	BMagenta        = Esc + "[45m"
	BCyan           = Esc + "[46m"
	BWhite          = Esc + "[47m"

	//Additional 8 bright background colors
	BBrightBlack   string = Esc + "[40;1m"
	BBrightRed            = Esc + "[41;1m"
	BBrightGreen          = Esc + "[42;1m"
	BBrightYellow         = Esc + "[43;1m"
	BBrightBlue           = Esc + "[44;1m"
	BBrightMagenta        = Esc + "[45;1m"
	BBrightCyan           = Esc + "[46;1m"
	BBrightWhite          = Esc + "[47;1m"

	// Color format string to use with 256 color codes. Needs int in range [0;255].
	ColorIDTemplate      string = Esc + "[38;5;%vm"
	BackgroundIDTemplate        = Esc + "[48;5;%vm"

	//Styles. Can be used separately or together with color and background codes.
	Bold      string = Esc + "[1m"
	Underline        = Esc + "[4m"
	Blinking         = Esc + "[5m"
	Reversed         = Esc + "[7m"

	// Reset escape sequence
	Reset string = Esc + "[0m"

	// Cursor maniputation
	CursorSave                  string = Esc + "[s"
	CursorRestore                      = Esc + "[u"
	CursorHome                         = Esc + "[H"
	CursorGotoTemplate                 = Esc + "[%v;%vH"
	CursorMoveUpTemplate               = Esc + "[%vA"
	CursorMoveDownTemplate             = Esc + "[%vB"
	CursorMoveRightTemplate            = Esc + "[%vC"
	CursorMoveLeftTemplate             = Esc + "[%vD"
	CursorMoveToNextRowTemplate        = Esc + "[E"
	CursorMoveToRowTemplate            = Esc + "[%vH"

	// Clear screen codes
	Clear     string = Esc + "[2J"
	ClearUp          = Esc + "[1J"
	ClearDown        = Esc + "[0J"

	// Clear line codes
	ClearL      string = Esc + "[2K"
	ClearLLeft         = Esc + "[1K"
	ClearLRight        = Esc + "[0K"
)

Variables

View Source
var (
	ErrUnknownColor    = errors.New("error: unknown color name or color id out of range [0;255]")
	ErrUnknownTermSize = errors.New("error: could not find out terminal size")
)
View Source
var (
	ErrFailedToSetColor      = errors.New("error: failed to set printer color")
	ErrFailedToSetBackground = errors.New("error: failed to set printer background")
)
View Source
var (
	ErrUnknownPrinter               = errors.New("error: no such printer")
	ErrFailedToAdd                  = errors.New("error: failed to add printer: name already taken or nil pointer passed")
	ErrFailedToProcessPrinterConfig = errors.New("error: failed to process PrinterConfig: field Name must not be empty when adding to PrintSuite")
	ErrEmptyName                    = errors.New("error: printer name may not be empty string")
)

Functions

func ClearLine

func ClearLine()

ClearLine deletes the whole line of text

func ClearLineLeft

func ClearLineLeft()

ClearLineLeft deletes line left of cursor position

func ClearLineRight

func ClearLineRight()

ClearLineRight deletes line right of cursor position

func ClearScreen

func ClearScreen()

ClearScreen clears screen

func ClearScreenDown

func ClearScreenDown()

ClearScreenDown clears screen from current cursor position down

func ClearScreenUp

func ClearScreenUp()

ClearScreenUp clears screen from current cursor position up

func Csprint added in v1.0.0

func Csprint(color interface{}, a ...interface{}) string

Csprint formats using the default formats for its operands and returns the resulting string. It accepts color color identifier (string or int). If color is invalid the function will return fmt.Sprint(a).

func Csprintf added in v1.0.0

func Csprintf(color interface{}, format string, a ...interface{}) string

Csprintf formats according to a format specifier and returns the resulting string. It accepts color color identifier (string or int). If color is invalid the function will return fmt.Sprintf(format, a).

func GetBackgroundCode added in v1.0.0

func GetBackgroundCode(color interface{}) (string, error)

GetBackgroundCode accepts color identifier (string or int) and returns ANSI escape sequence for requested background color. If color is invalid the function will return empty string and an error.

func GetColorCode added in v1.0.0

func GetColorCode(color interface{}) (string, error)

GetColorCode accepts color identifier (string or int) and returns ANSI escape sequence for requested color. If color is invalid the function will return empty string and an error.

func GetTermSize

func GetTermSize() (columns int, rows int, err error)

GetTermSize returns current terminal size (number of columns and rows). It may fail to get correct values and will return -1, -1 in this case. If you're relying on output to precisely position cursor on screen always check error.

func MoveCursorDown added in v0.8.0

func MoveCursorDown(rows int)

MoveCursorDown moves cursor down specified number of rows

func MoveCursorHome added in v1.0.0

func MoveCursorHome()

MoveCursorHome moves cursor to the upper left corner of the screen. Essentially the same as MoveCursorTo(0, 0).

func MoveCursorLeft added in v0.8.0

func MoveCursorLeft(columns int)

MoveCursorLeft moves cursor left specified number of columns

func MoveCursorRight added in v0.8.0

func MoveCursorRight(columns int)

MoveCursorRight moves cursor left specified number of columns

func MoveCursorTo added in v0.8.0

func MoveCursorTo(column, row int)

MoveCursorTo moves cursor to the specified position in terminal. (0, 0) is upper left. Will do nothing if x or y are out of bounds or we can not get size of terminal.

func MoveCursorToNextRow added in v0.8.0

func MoveCursorToNextRow()

MoveCursorToNextRow moves cursor to next row

func MoveCursorToRow added in v0.8.0

func MoveCursorToRow(row int)

MoveCursorToRow places cursor at the beginning of specified row

func MoveCursorUp added in v0.8.0

func MoveCursorUp(rows int)

MoveCursorUp moves cursor up specified number of rows

func PrintAtPosition added in v0.8.0

func PrintAtPosition(column, row int, a ...interface{})

PrintAtPosition moves cursor in the current terminal to the specified position and prints. It does not return the cursor to the initial position so subsequent call to Print/Println etc. will output immediately after the previous output. Will print at current cursor position if terminal size is unavailable or supplied column and row are out of range.

func PrintAtPositionAndReturn

func PrintAtPositionAndReturn(column, row int, a ...interface{})

PrintAtPositionAndReturn moves cursor in the current terminal to the specified position, prints, and then returns cursor to the inital position. Will print at current cursor position if terminal size is unavailable or supplied column and row are out of range.

func RestoreCursorPosition added in v0.8.0

func RestoreCursorPosition()

RestoreCursorPosition places cursor to original position when SaveCursorPosition was called and restores attributes.

func SaveCursorPosition added in v0.8.0

func SaveCursorPosition()

SaveCursorPosition saves current cursor position and attributes. Call RestoreCursorPosition() to return

Types

type PrintSuite added in v1.0.0

type PrintSuite struct {
	Printer
	// contains filtered or unexported fields
}

PrintSuite zero ore more configurations of Printer which allows to switch added printer configurations on the fly to use differrent output styles. Printer configurations can be added with AddPrinter() and Configure() methods.

An instance of printer is embedded into PrintSuite so you can call printer methods on it directly. By default the embedded printer acts exactly the same way as functions from fmt module of standard library (does not alter output in any way). Embedded printer configuration can be changed either by calling termtools.Printer methods or by adding a new prtinter configuration and switching to it with SwitchTo().

func (*PrintSuite) AddPrinter added in v1.0.0

func (suite *PrintSuite) AddPrinter(printername string, p *Printer) error

AddPrinter accepts name of printer and pointer to printer. If nil pointer or empty string is passed or if printername is already added the method will fail with an error.

func (*PrintSuite) Configure added in v1.0.0

func (suite *PrintSuite) Configure(configs ...PrinterConfig) error

Configure accepts one or more PrinterConfig and adds printers to PrintSuite. If one or more configs fail to process the method will return an error listing names that failed to add. Important: if method encounters empty Name field in PrinterConfig(s), the method will fail with an error and subsequent configurations will not be processed.

func (*PrintSuite) SwitchTo added in v1.0.0

func (suite *PrintSuite) SwitchTo(printername string) error

SwitchTo sets the embedded PrintSuite printer to printer with requested name. If printername is not known the method will return an error without changes to current configuration.

func (*PrintSuite) SwitchToDefault added in v1.0.0

func (suite *PrintSuite) SwitchToDefault()

SwitchToDefault switches active printer of PrintSuite to default Printer{} with no settings.

func (*PrintSuite) Use added in v1.0.0

func (suite *PrintSuite) Use(printername string) *Printer

Use returns instance of printer with requested printername. If printername is invalid (no printer with such name has been added or name is empty string) a default Printer instance is returned.

func (*PrintSuite) UseDefault added in v1.0.0

func (suite *PrintSuite) UseDefault() *Printer

UseDefault acts in the same manner as Use but always returns printer with no style options set which will output the same as fmt module functions.

type Printer

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

Printer holds color and style settings and implements most methods as in fmt module like Print, Println, Sprint etc. adding color and styles to the input values.

func NewPrinter

func NewPrinter(conf PrinterConfig) (p *Printer, err error)

NewPrinter takes PrinterConfig and returns pointer to Printer. If invalid color(s) identifier is encountered the function returns instance of printer with color(s) not set. Otherwise the printer is functional. Check for errors to make sure that returned Printer is fully configured.

func (*Printer) Errorf

func (p *Printer) Errorf(format string, a ...interface{}) error

Errorf formats according to a format specifier and returns the string as a value that satisfies error.

func (*Printer) Fprint

func (p *Printer) Fprint(w io.Writer, a ...interface{}) (n int, err error)

Fprint formats using the default formats for its operands and writes to w. Spaces are added between operands when neither is a string. It returns the number of bytes written and any write error encountered.

func (*Printer) Fprintf

func (p *Printer) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error)

Fprintf formats according to a format specifier and writes to w. It returns the number of bytes written and any write error encountered.

func (*Printer) Fprintln

func (p *Printer) Fprintln(w io.Writer, a ...interface{}) (n int, err error)

Fprintln formats using the default formats for its operands and writes to w. Spaces are always added between operands and a newline is appended. It returns the number of bytes written and any write error encountered.

func (*Printer) MoveDown added in v0.8.0

func (p *Printer) MoveDown(rows int)

MoveDown moves cursor down specified number of rows.

func (*Printer) MoveHome added in v1.0.0

func (p *Printer) MoveHome()

MoveHome places cursor at the top left corner of the screen.

func (*Printer) MoveLeft added in v0.8.0

func (p *Printer) MoveLeft(columns int)

MoveLeft moves cursor left specified number of columns.

func (*Printer) MoveRight added in v0.8.0

func (p *Printer) MoveRight(columns int)

MoveRight moves cursor right specified number of columns.

func (*Printer) MoveTo added in v0.8.0

func (p *Printer) MoveTo(column, row int)

MoveTo places cursor at the specified column and row.

func (*Printer) MoveToNextRow added in v0.8.0

func (p *Printer) MoveToNextRow()

MoveToNextRow moves cursor to the next row..

func (*Printer) MoveToRow added in v0.8.0

func (p *Printer) MoveToRow(row int)

MoveToRow moves cursor to the specified row

func (*Printer) MoveUp added in v0.8.0

func (p *Printer) MoveUp(rows int)

MoveUp moves cursor up specified number of rows.

func (*Printer) Print

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

Print formats using the default formats for its operands and writes to standard output. Spaces are added between operands when neither is a string. It returns the number of bytes written and any write error encountered.

func (*Printer) PrintAtPosition added in v0.8.0

func (p *Printer) PrintAtPosition(column, row int, a ...interface{}) (n int, err error)

PrintAtPosition moves cursor to specified column and row and issues Print It does not return to the initial position. It returns the number of bytes written and any write error encountered. See also PrintAtPositionAndReturn method.

func (*Printer) PrintAtPositionAndReturn added in v0.8.0

func (p *Printer) PrintAtPositionAndReturn(column, row int, a ...interface{}) (n int, err error)

PrintAtPositionAndReturn moves cursor to specified column and row and issues Print then moves cursor to initial position when method was called. It returns the number of bytes written and any write error encountered.

func (*Printer) Printf

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

Printf formats according to a format specifier and writes to standard output. It returns the number of bytes written and any write error encountered.

func (*Printer) Println

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

Println formats using the default formats for its operands and writes to standard output. Spaces are always added between operands and a newline is appended. It returns the number of bytes written and any write error encountered.

func (*Printer) Reset

func (p *Printer) Reset()

Reset resets printer state to initial state (no color, no background, bold, underline and reversed modes turned off).

func (*Printer) SetBackground

func (p *Printer) SetBackground(color interface{}) error

SetBackground sets background color of printer. Argument color is the same as in SetColor method. will return an error and currently set Printer color will not be changed.

func (*Printer) SetColor

func (p *Printer) SetColor(color interface{}) error

SetColor sets color of printer. Argument "color" must be either string or int. Valid color names are: "black", "blue", "cyan", "green", "magenta", "red", "white", "yellow", "brightblack", "brightblue", "brightcyan", "brightgreen", "brightmagenta", "brightred", "brightwhite", "brightyellow". Valid numbers are from 0 to 255 inclusive. If color is not known, is empty, or int is out of range the method will return an error and currently set Printer color will not be changed.

func (*Printer) SetPrefixSuffix added in v1.0.0

func (p *Printer) SetPrefixSuffix(prefix, suffix string)

SetPrefixSuffix configures Printer to always preceed output with prefix and end output with suffix. Printer color and style settings apply to prefix and suffix.

func (*Printer) Sprint

func (p *Printer) Sprint(a ...interface{}) string

Sprint formats using the default formats for its operands and returns the resulting string. Spaces are added between operands when neither is a string.

func (*Printer) Sprintf

func (p *Printer) Sprintf(format string, a ...interface{}) string

Sprintf formats according to a format specifier and returns the resulting string.

func (*Printer) Sprintln

func (p *Printer) Sprintln(a ...interface{}) string

Sprintln formats using the default formats for its operands and returns the resulting string. Spaces are always added between operands and a newline is appended.

func (*Printer) ToggleBlinking added in v1.0.0

func (p *Printer) ToggleBlinking()

ToggleBlinking toggles blinking mode of Printer

func (*Printer) ToggleBold

func (p *Printer) ToggleBold()

ToggleBold toggles bold mode of Printer

func (*Printer) ToggleReversed

func (p *Printer) ToggleReversed()

ToggleReversed toggles reverse mode of Printer

func (*Printer) ToggleUnderline

func (p *Printer) ToggleUnderline()

ToggleUnderline toggles underline mode of Printer

type PrinterConfig added in v1.0.0

type PrinterConfig struct {
	// Name identifies configuration when used
	// with PrintSuite type. Name field is mandatory when passing PrinterConfig
	// to PrintSuite Configure method!
	//
	// When setting up a Printer instance with NewPrinter() Name field may be omitted.
	Name string
	// Color and Backgrount fields may hold color name (as string) or color ID in range
	// [0;255]. See package docs for list of available color names.
	Color      interface{}
	Background interface{}
	// Bold, Underline, Reversed, Blinking switch relevant printer modes on if set to true.
	Bold      bool
	Underline bool
	Reversed  bool
	Blinking  bool
	// Prefix and suffix are added to output if they are not empty strings.
	Prefix string
	Suffix string
}

PrinterConfig describes configuration of Printer.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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