colour

package module
v0.0.0-...-e1934f7 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2019 License: MIT Imports: 8 Imported by: 0

README

Colour

Colour lets you use colourized outputs in terms of ANSI Escape Codes in Go (Golang). It has support for Windows too! The API can be used in several ways, pick one that suits you.

Install

go get github.com/felix/colour

Examples

Standard colours
// Print with default helper functions
colour.Cyan("Prints text in cyan.")

// A newline will be appended automatically
colour.Blue("Prints %s in blue.", "text")

// These are using the default foreground colours
colour.Red("We have red")
colour.Magenta("And many others ..")

Mix and reuse colours
// Create a new colour object
c := colour.New(colour.FgCyan).Add(colour.Underline)
c.Println("Prints cyan text with an underline.")

// Or just add them to New()
d := colour.New(colour.FgCyan, colour.Bold)
d.Printf("This prints bold cyan %s\n", "too!.")

// Mix up foreground and background colours, create new mixes!
red := colour.New(colour.FgRed)

boldRed := red.Add(colour.Bold)
boldRed.Println("This will print text in bold red.")

whiteBackground := red.Add(colour.BgWhite)
whiteBackground.Println("Red text with white background.")
Use your own output (io.Writer)
// Use your own io.Writer output
colour.New(colour.FgBlue).Fprintln(myWriter, "blue colour!")

blue := colour.New(colour.FgBlue)
blue.Fprint(writer, "This will print text in blue.")
Custom print functions (PrintFunc)
// Create a custom print function for convenience
red := colour.New(colour.FgRed).PrintfFunc()
red("Warning")
red("Error: %s", err)

// Mix up multiple attributes
notice := colour.New(colour.Bold, colour.FgGreen).PrintlnFunc()
notice("Don't forget this...")
Custom fprint functions (FprintFunc)
blue := colour.New(FgBlue).FprintfFunc()
blue(myWriter, "important notice: %s", stars)

// Mix up with multiple attributes
success := colour.New(colour.Bold, colour.FgGreen).FprintlnFunc()
success(myWriter, "Don't forget this...")
Insert into noncolour strings (SprintFunc)
// Create SprintXxx functions to mix strings with other non-colourized strings:
yellow := colour.New(colour.FgYellow).SprintFunc()
red := colour.New(colour.FgRed).SprintFunc()
fmt.Printf("This is a %s and this is %s.\n", yellow("warning"), red("error"))

info := colour.New(colour.FgWhite, colour.BgGreen).SprintFunc()
fmt.Printf("This %s rocks!\n", info("package"))

// Use helper functions
fmt.Println("This", colour.RedString("warning"), "should be not neglected.")
fmt.Printf("%v %v\n", colour.GreenString("Info:"), "an important message.")

// Windows supported too! Just don't forget to change the output to colour.Output
fmt.Fprintf(colour.Output, "Windows support: %s", colour.GreenString("PASS"))
Plug into existing code
// Use handy standard colours
colour.Set(colour.FgYellow)

fmt.Println("Existing text will now be in yellow")
fmt.Printf("This one %s\n", "too")

colour.Unset() // Don't forget to unset

// You can mix up parameters
colour.Set(colour.FgMagenta, colour.Bold)
defer colour.Unset() // Use it in your function

fmt.Println("All text will now be bold magenta.")
Disable/Enable colour

There might be a case where you want to explicitly disable/enable colour output. the go-isatty package will automatically disable colour output for non-tty output streams (for example if the output were piped directly to less)

Colour has support to disable/enable colours both globally and for single colour definitions. For example suppose you have a CLI app and a --no-colour bool flag. You can easily disable the colour output with:


var flagNoColour = flag.Bool("no-colour", false, "Disable colour output")

if *flagNoColour {
	colour.NoColour = true // disables colourized output
}

It also has support for single colour definitions (local). You can disable/enable colour output on the fly:

c := colour.New(colour.FgCyan)
c.Println("Prints cyan text")

c.DisableColour()
c.Println("This is printed without any colour")

c.EnableColour()
c.Println("This prints again cyan...")

License

The MIT License (MIT).

Documentation

Overview

Package colour is an ANSI colour package to output colourized or SGR defined output to the standard output. The API can be used in several way, pick one that suits you.

Use simple and default helper functions with predefined foreground colours:

colour.Cyan("Prints text in cyan.")

// a newline will be appended automatically
colour.Blue("Prints %s in blue.", "text")

// More default foreground colours..
colour.Red("We have red")
colour.Yellow("Yellow colour too!")
colour.Magenta("And many others ..")

// Hi-intensity colours
colour.HiGreen("Bright green colour.")
colour.HiBlack("Bright black means gray..")
colour.HiWhite("Shiny white colour!")

However there are times where custom colour mixes are required. Below are some examples to create custom colour objects and use the print functions of each separate colour object.

// Create a new colour object
c := colour.New(colour.FgCyan).Add(colour.Underline)
c.Println("Prints cyan text with an underline.")

// Or just add them to New()
d := colour.New(colour.FgCyan, colour.Bold)
d.Printf("This prints bold cyan %s\n", "too!.")

// Mix up foreground and background colours, create new mixes!
red := colour.New(colour.FgRed)

boldRed := red.Add(colour.Bold)
boldRed.Println("This will print text in bold red.")

whiteBackground := red.Add(colour.BgWhite)
whiteBackground.Println("Red text with White background.")

// Use your own io.Writer output
colour.New(colour.FgBlue).Fprintln(myWriter, "blue colour!")

blue := colour.New(colour.FgBlue)
blue.Fprint(myWriter, "This will print text in blue.")

You can create PrintXxx functions to simplify even more:

// Create a custom print function for convenient
red := colour.New(colour.FgRed).PrintfFunc()
red("warning")
red("error: %s", err)

// Mix up multiple attributes
notice := colour.New(colour.Bold, colour.FgGreen).PrintlnFunc()
notice("don't forget this...")

You can also FprintXxx functions to pass your own io.Writer:

blue := colour.New(FgBlue).FprintfFunc()
blue(myWriter, "important notice: %s", stars)

// Mix up with multiple attributes
success := colour.New(colour.Bold, colour.FgGreen).FprintlnFunc()
success(myWriter, don't forget this...")

Or create SprintXxx functions to mix strings with other non-colourized strings:

yellow := New(FgYellow).SprintFunc()
red := New(FgRed).SprintFunc()

fmt.Printf("this is a %s and this is %s.\n", yellow("warning"), red("error"))

info := New(FgWhite, BgGreen).SprintFunc()
fmt.Printf("this %s rocks!\n", info("package"))

Windows support is enabled by default. All Print functions work as intended. However only for colour.SprintXXX functions, user should use fmt.FprintXXX and set the output to colour.Output:

fmt.Fprintf(colour.Output, "Windows support: %s", colour.GreenString("PASS"))

info := New(FgWhite, BgGreen).SprintFunc()
fmt.Fprintf(colour.Output, "this %s rocks!\n", info("package"))

Using with existing code is possible. Just use the Set() method to set the standard output to the given parameters. That way a rewrite of an existing code is not required.

// Use handy standard colours.
colour.Set(colour.FgYellow)

fmt.Println("Existing text will be now in Yellow")
fmt.Printf("This one %s\n", "too")

colour.Unset() // don't forget to unset

// You can mix up parameters
colour.Set(colour.FgMagenta, colour.Bold)
defer colour.Unset() // use it in your function

fmt.Println("All text will be now bold magenta.")

There might be a case where you want to disable colour output (for example to pipe the standard output of your app to somewhere else). `Colour` has support to disable colours both globally and for single colour definition. For example suppose you have a CLI app and a `--no-colour` bool flag. You can easily disable the colour output with:

var flagNoColour = flag.Bool("no-colour", false, "Disable colour output")

if *flagNoColour {
	colour.NoColour = true // disables colourized output
}

It also has support for single colour definitions (local). You can disable/enable colour output on the fly:

c := colour.New(colour.FgCyan)
c.Println("Prints cyan text")

c.DisableColour()
c.Println("This is printed without any colour")

c.EnableColour()
c.Println("This prints again cyan...")

Index

Constants

This section is empty.

Variables

View Source
var (
	// NoColour defines if the output is colourized or not. It's dynamically set to
	// false or true based on the stdout's file descriptor referring to a terminal
	// or not. This is a global option and affects all colours. For more control
	// over each colour block use the methods DisableColour() individually.
	NoColour = os.Getenv("TERM") == "dumb" ||
		(!isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd()))

	// Output defines the standard output of the print functions. By default
	// os.Stdout is used.
	Output = colorable.NewColorableStdout()

	// Error defines a colour supporting writer for os.Stderr.
	Error = colorable.NewColorableStderr()
)

Functions

func Black

func Black(format string, a ...interface{})

Black is a convenient helper function to print with black foreground. A newline is appended to format by default.

func BlackString

func BlackString(format string, a ...interface{}) string

BlackString is a convenient helper function to return a string with black foreground.

func Blue

func Blue(format string, a ...interface{})

Blue is a convenient helper function to print with blue foreground. A newline is appended to format by default.

func BlueString

func BlueString(format string, a ...interface{}) string

BlueString is a convenient helper function to return a string with blue foreground.

func Cyan

func Cyan(format string, a ...interface{})

Cyan is a convenient helper function to print with cyan foreground. A newline is appended to format by default.

func CyanString

func CyanString(format string, a ...interface{}) string

CyanString is a convenient helper function to return a string with cyan foreground.

func Green

func Green(format string, a ...interface{})

Green is a convenient helper function to print with green foreground. A newline is appended to format by default.

func GreenString

func GreenString(format string, a ...interface{}) string

GreenString is a convenient helper function to return a string with green foreground.

func HiBlack

func HiBlack(format string, a ...interface{})

HiBlack is a convenient helper function to print with hi-intensity black foreground. A newline is appended to format by default.

func HiBlackString

func HiBlackString(format string, a ...interface{}) string

HiBlackString is a convenient helper function to return a string with hi-intensity black foreground.

func HiBlue

func HiBlue(format string, a ...interface{})

HiBlue is a convenient helper function to print with hi-intensity blue foreground. A newline is appended to format by default.

func HiBlueString

func HiBlueString(format string, a ...interface{}) string

HiBlueString is a convenient helper function to return a string with hi-intensity blue foreground.

func HiCyan

func HiCyan(format string, a ...interface{})

HiCyan is a convenient helper function to print with hi-intensity cyan foreground. A newline is appended to format by default.

func HiCyanString

func HiCyanString(format string, a ...interface{}) string

HiCyanString is a convenient helper function to return a string with hi-intensity cyan foreground.

func HiGreen

func HiGreen(format string, a ...interface{})

HiGreen is a convenient helper function to print with hi-intensity green foreground. A newline is appended to format by default.

func HiGreenString

func HiGreenString(format string, a ...interface{}) string

HiGreenString is a convenient helper function to return a string with hi-intensity green foreground.

func HiMagenta

func HiMagenta(format string, a ...interface{})

HiMagenta is a convenient helper function to print with hi-intensity magenta foreground. A newline is appended to format by default.

func HiMagentaString

func HiMagentaString(format string, a ...interface{}) string

HiMagentaString is a convenient helper function to return a string with hi-intensity magenta foreground.

func HiRed

func HiRed(format string, a ...interface{})

HiRed is a convenient helper function to print with hi-intensity red foreground. A newline is appended to format by default.

func HiRedString

func HiRedString(format string, a ...interface{}) string

HiRedString is a convenient helper function to return a string with hi-intensity red foreground.

func HiWhite

func HiWhite(format string, a ...interface{})

HiWhite is a convenient helper function to print with hi-intensity white foreground. A newline is appended to format by default.

func HiWhiteString

func HiWhiteString(format string, a ...interface{}) string

HiWhiteString is a convenient helper function to return a string with hi-intensity white foreground.

func HiYellow

func HiYellow(format string, a ...interface{})

HiYellow is a convenient helper function to print with hi-intensity yellow foreground. A newline is appended to format by default.

func HiYellowString

func HiYellowString(format string, a ...interface{}) string

HiYellowString is a convenient helper function to return a string with hi-intensity yellow foreground.

func Magenta

func Magenta(format string, a ...interface{})

Magenta is a convenient helper function to print with magenta foreground. A newline is appended to format by default.

func MagentaString

func MagentaString(format string, a ...interface{}) string

MagentaString is a convenient helper function to return a string with magenta foreground.

func Red

func Red(format string, a ...interface{})

Red is a convenient helper function to print with red foreground. A newline is appended to format by default.

func RedString

func RedString(format string, a ...interface{}) string

RedString is a convenient helper function to return a string with red foreground.

func Unset

func Unset()

Unset resets all escape attributes and clears the output. Usually should be called after Set().

func White

func White(format string, a ...interface{})

White is a convenient helper function to print with white foreground. A newline is appended to format by default.

func WhiteString

func WhiteString(format string, a ...interface{}) string

WhiteString is a convenient helper function to return a string with white foreground.

func Yellow

func Yellow(format string, a ...interface{})

Yellow is a convenient helper function to print with yellow foreground. A newline is appended to format by default.

func YellowString

func YellowString(format string, a ...interface{}) string

YellowString is a convenient helper function to return a string with yellow foreground.

Types

type Attribute

type Attribute int

Attribute defines a single SGR Code

const (
	Reset Attribute = iota
	Bold
	Faint
	Italic
	Underline
	BlinkSlow
	BlinkRapid
	ReverseVideo
	Concealed
	CrossedOut
)

Base attributes

const (
	FgBlack Attribute = iota + 30
	FgRed
	FgGreen
	FgYellow
	FgBlue
	FgMagenta
	FgCyan
	FgWhite
)

Foreground text colours

const (
	FgHiBlack Attribute = iota + 90
	FgHiRed
	FgHiGreen
	FgHiYellow
	FgHiBlue
	FgHiMagenta
	FgHiCyan
	FgHiWhite
)

Foreground Hi-Intensity text colours

const (
	BgBlack Attribute = iota + 40
	BgRed
	BgGreen
	BgYellow
	BgBlue
	BgMagenta
	BgCyan
	BgWhite
)

Background text colours

const (
	BgHiBlack Attribute = iota + 100
	BgHiRed
	BgHiGreen
	BgHiYellow
	BgHiBlue
	BgHiMagenta
	BgHiCyan
	BgHiWhite
)

Background Hi-Intensity text colours

type Colour

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

Colour defines a custom colour object which is defined by SGR parameters.

func New

func New(value ...Attribute) *Colour

New returns a newly created colour object.

func Set

func Set(p ...Attribute) *Colour

Set sets the given parameters immediately. It will change the colour of output with the given SGR parameters until colour.Unset() is called.

func (*Colour) Add

func (c *Colour) Add(value ...Attribute) *Colour

Add is used to chain SGR parameters. Use as many as parameters to combine and create custom colour objects. Example: Add(colour.FgRed, colour.Underline).

func (*Colour) DisableColour

func (c *Colour) DisableColour()

DisableColour disables the colour output. Useful to not change any existing code and still being able to output. Can be used for flags like "--no-colour". To enable back use EnableColour() method.

func (*Colour) EnableColour

func (c *Colour) EnableColour()

EnableColour enables the colour output. Use it in conjunction with DisableColour(). Otherwise this method has no side effects.

func (*Colour) Equals

func (c *Colour) Equals(c2 *Colour) bool

Equals returns a boolean value indicating whether two colours are equal.

func (*Colour) Fprint

func (c *Colour) 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. On Windows, users should wrap w with colorable.NewColorable() if w is of type *os.File.

func (*Colour) FprintFunc

func (c *Colour) FprintFunc() func(w io.Writer, a ...interface{})

FprintFunc returns a new function that prints the passed arguments as colourized with colour.Fprint().

func (*Colour) Fprintf

func (c *Colour) 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. On Windows, users should wrap w with colorable.NewColorable() if w is of type *os.File.

func (*Colour) FprintfFunc

func (c *Colour) FprintfFunc() func(w io.Writer, format string, a ...interface{})

FprintfFunc returns a new function that prints the passed arguments as colourized with colour.Fprintf().

func (*Colour) Fprintln

func (c *Colour) 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. On Windows, users should wrap w with colorable.NewColorable() if w is of type *os.File.

func (*Colour) FprintlnFunc

func (c *Colour) FprintlnFunc() func(w io.Writer, a ...interface{})

FprintlnFunc returns a new function that prints the passed arguments as colourized with colour.Fprintln().

func (*Colour) Print

func (c *Colour) 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. This is the standard fmt.Print() method wrapped with the given colour.

func (*Colour) PrintFunc

func (c *Colour) PrintFunc() func(a ...interface{})

PrintFunc returns a new function that prints the passed arguments as colourized with colour.Print().

func (*Colour) Printf

func (c *Colour) 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. This is the standard fmt.Printf() method wrapped with the given colour.

func (*Colour) PrintfFunc

func (c *Colour) PrintfFunc() func(format string, a ...interface{})

PrintfFunc returns a new function that prints the passed arguments as colourized with colour.Printf().

func (*Colour) Println

func (c *Colour) 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. This is the standard fmt.Print() method wrapped with the given colour.

func (*Colour) PrintlnFunc

func (c *Colour) PrintlnFunc() func(a ...interface{})

PrintlnFunc returns a new function that prints the passed arguments as colourized with colour.Println().

func (*Colour) Set

func (c *Colour) Set() *Colour

Set sets the SGR sequence.

func (*Colour) Sprint

func (c *Colour) Sprint(a ...interface{}) string

Sprint is just like Print, but returns a string instead of printing it.

func (*Colour) SprintFunc

func (c *Colour) SprintFunc() func(a ...interface{}) string

SprintFunc returns a new function that returns colourized strings for the given arguments with fmt.Sprint(). Useful to put into or mix into other string. Windows users should use this in conjunction with colour.Output, example:

put := New(FgYellow).SprintFunc()
fmt.Fprintf(colour.Output, "This is a %s", put("warning"))

func (*Colour) Sprintf

func (c *Colour) Sprintf(format string, a ...interface{}) string

Sprintf is just like Printf, but returns a string instead of printing it.

func (*Colour) SprintfFunc

func (c *Colour) SprintfFunc() func(format string, a ...interface{}) string

SprintfFunc returns a new function that returns colourized strings for the given arguments with fmt.Sprintf(). Useful to put into or mix into other string. Windows users should use this in conjunction with colour.Output.

func (*Colour) Sprintln

func (c *Colour) Sprintln(a ...interface{}) string

Sprintln is just like Println, but returns a string instead of printing it.

func (*Colour) SprintlnFunc

func (c *Colour) SprintlnFunc() func(a ...interface{}) string

SprintlnFunc returns a new function that returns colourized strings for the given arguments with fmt.Sprintln(). Useful to put into or mix into other string. Windows users should use this in conjunction with colour.Output.

Jump to

Keyboard shortcuts

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