color

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Feb 6, 2023 License: Apache-2.0 Imports: 12 Imported by: 0

README

CLI Color

GitHub go.mod Go version Actions Status Codacy Badge GoDoc GitHub tag (latest SemVer) Build Status Coverage Status Go Report Card

A command-line color library with 16/256/True color support, universal API methods and Windows support.

中文说明

Basic color preview:

basic-color

Now, 256 colors and RGB colors have also been supported to work in Windows CMD and PowerShell:

color-on-cmd-pwsh

Features

  • Simple to use, zero dependencies
  • Supports rich color output: 16-color (4-bit), 256-color (8-bit), true color (24-bit, RGB)
    • 16-color output is the most commonly used and most widely supported, working on any Windows version
    • Since v1.2.4 the 256-color (8-bit), true color (24-bit) support windows CMD and PowerShell
    • See this gist for information on true color support
  • Support converts HEX HSL value to RGB color
  • Generic API methods: Print, Printf, Println, Sprint, Sprintf
  • Supports HTML tag-style color rendering, such as <green>message</> <fg=red;bg=blue>text</>.
    • In addition to using built-in tags, it also supports custom color attributes
    • Custom color attributes support the use of 16 color names, 256 color values, rgb color values and hex color values
    • Support working on Windows cmd and powerShell terminal
  • Basic colors: Bold, Black, White, Gray, Red, Green, Yellow, Blue, Magenta, Cyan
  • Additional styles: Info, Note, Light, Error, Danger, Notice, Success, Comment, Primary, Warning, Question, Secondary
  • Support by set NO_COLOR for disable color or use FORCE_COLOR for force open color render.
  • Support Rgb, 256, 16 color conversion

GoDoc

Install

go get github.com/zhangyiming748/pretty/color

Quick start

package main

import (
	"fmt"

	"github.com/zhangyiming748/pretty/color"
)

func main() {
	// quick use package func
	color.Redp("Simple to use color")
	color.Redln("Simple to use color")
	color.Greenp("Simple to use color\n")
	color.Cyanln("Simple to use color")
	color.Yellowln("Simple to use color")

	// quick use like fmt.Print*
	color.Red.Println("Simple to use color")
	color.Green.Print("Simple to use color\n")
	color.Cyan.Printf("Simple to use %s\n", "color")
	color.Yellow.Printf("Simple to use %s\n", "color")

	// use like func
	red := color.FgRed.Render
	green := color.FgGreen.Render
	fmt.Printf("%s line %s library\n", red("Command"), green("color"))

	// custom color
	color.New(color.FgWhite, color.BgBlack).Println("custom color style")

	// can also:
	color.Style{color.FgCyan, color.OpBold}.Println("custom color style")

	// internal theme/style:
	color.Info.Tips("message")
	color.Info.Prompt("message")
	color.Info.Println("message")
	color.Warn.Println("message")
	color.Error.Println("message")

	// use style tag
	color.Print("<suc>he</><comment>llo</>, <cyan>wel</><red>come</>\n")
	// Custom label attr: Supports the use of 16 color names, 256 color values, rgb color values and hex color values
	color.Println("<fg=11aa23>he</><bg=120,35,156>llo</>, <fg=167;bg=232>wel</><fg=red>come</>")

	// apply a style tag
	color.Tag("info").Println("info style text")

	// prompt message
	color.Info.Prompt("prompt style message")
	color.Warn.Prompt("prompt style message")

	// tips message
	color.Info.Tips("tips style message")
	color.Warn.Tips("tips style message")
}

Run demo: go run ./_examples/demo.go

colored-out

Basic/16 color

Supported on any Windows version. Provide generic API methods: Print, Printf, Println, Sprint, Sprintf

color.Bold.Println("bold message")
color.Cyan.Println("yellow message")
color.Yellow.Println("yellow message")
color.Magenta.Println("yellow message")

// Only use foreground color
color.FgCyan.Printf("Simple to use %s\n", "color")
// Only use background color
color.BgRed.Printf("Simple to use %s\n", "color")

Run demo: go run ./_examples/color_16.go

basic-color

Custom build color
// Full custom: foreground, background, option
myStyle := color.New(color.FgWhite, color.BgBlack, color.OpBold)
myStyle.Println("custom color style")

// can also:
color.Style{color.FgCyan, color.OpBold}.Println("custom color style")

custom set console settings:

// set console color
color.Set(color.FgCyan)

// print message
fmt.Print("message")

// reset console settings
color.Reset()
Additional styles

provide generic API methods: Print, Printf, Println, Sprint, Sprintf

print message use defined style:

color.Info.Println("Info message")
color.Notice.Println("Notice message")
color.Error.Println("Error message")
// ...

Run demo: go run ./_examples/theme_basic.go

theme-basic

Tips style

color.Info.Tips("Info tips message")
color.Notice.Tips("Notice tips message")
color.Error.Tips("Error tips message")
color.Secondary.Tips("Secondary tips message")

Run demo: go run ./_examples/theme_tips.go

theme-tips

Prompt Style

color.Info.Prompt("Info prompt message")
color.Notice.Prompt("Notice prompt message")
color.Error.Prompt("Error prompt message")
// ...

Run demo: go run ./_examples/theme_prompt.go

theme-prompt

Block Style

color.Danger.Block("Danger block message")
color.Warn.Block("Warn block message")
// ...

Run demo: go run ./_examples/theme_block.go

theme-block

256-color usage

256 colors support Windows CMD, PowerShell environment after v1.2.4

Set the foreground or background color
  • color.C256(val uint8, isBg ...bool) Color256
c := color.C256(132) // fg color
c.Println("message")
c.Printf("format %s", "message")

c := color.C256(132, true) // bg color
c.Println("message")
c.Printf("format %s", "message")
256-color style

Can be used to set foreground and background colors at the same time.

  • S256(fgAndBg ...uint8) *Style256
s := color.S256(32, 203)
s.Println("message")
s.Printf("format %s", "message")

with options:

s := color.S256(32, 203)
s.SetOpts(color.Opts{color.OpBold})

s.Println("style with options")
s.Printf("style with %s\n", "options")

Run demo: go run ./_examples/color_256.go

color-tags

RGB/True color

RGB colors support Windows CMD, PowerShell environment after v1.2.4

Preview:

Run demo: Run demo: go run ./_examples/color_rgb.go

color-rgb

example:

color.RGB(30, 144, 255).Println("message. use RGB number")

color.HEX("#1976D2").Println("blue-darken")
color.HEX("#D50000", true).Println("red-accent. use HEX style")

color.RGBStyleFromString("213,0,0").Println("red-accent. use RGB number")
color.HEXStyle("eee", "D50000").Println("deep-purple color")
Set the foreground or background color
  • color.RGB(r, g, b uint8, isBg ...bool) RGBColor
c := color.RGB(30,144,255) // fg color
c.Println("message")
c.Printf("format %s", "message")

c := color.RGB(30,144,255, true) // bg color
c.Println("message")
c.Printf("format %s", "message")

Create a style from an hexadecimal color string:

  • color.HEX(hex string, isBg ...bool) RGBColor
c := color.HEX("ccc") // can also: "cccccc" "#cccccc"
c.Println("message")
c.Printf("format %s", "message")

c = color.HEX("aabbcc", true) // as bg color
c.Println("message")
c.Printf("format %s", "message")
RGB color style

Can be used to set the foreground and background colors at the same time.

  • color.NewRGBStyle(fg RGBColor, bg ...RGBColor) *RGBStyle
s := color.NewRGBStyle(RGB(20, 144, 234), RGB(234, 78, 23))
s.Println("message")
s.Printf("format %s", "message")

Create a style from an hexadecimal color string:

  • color.HEXStyle(fg string, bg ...string) *RGBStyle
s := color.HEXStyle("11aa23", "eee")
s.Println("message")
s.Printf("format %s", "message")

with options:

s := color.HEXStyle("11aa23", "eee")
s.SetOpts(color.Opts{color.OpBold})

s.Println("style with options")
s.Printf("style with %s\n", "options")

HTML-like tag usage

Print,Printf,Println functions support auto parse and render color tags.

	text := `
  <mga1>zhangyiming748/pretty/color:</>
     A <green>command-line</> 
     <cyan>color library</> with <fg=167;bg=232>256-color</>
     and <fg=11aa23;op=bold>True-color</> support,
     <fg=mga;op=i>universal API</> methods
     and <cyan>Windows</> support.
`
	color.Print(text)

Preview, code please see _examples/demo_tag.go:

demo_tag

Tag formats:

  • Use built in tags: <TAG_NAME>CONTENT</> e.g: <info>message</>
  • Custom tag attributes: <fg=VALUE;bg=VALUE;op=VALUES>CONTENT</> e.g: <fg=167;bg=232>wel</>

Supported on Windows cmd.exe PowerShell.

Examples:

// use style tag
color.Print("<suc>he</><comment>llo</>, <cyan>wel</><red>come</>")
color.Println("<suc>hello</>")
color.Println("<error>hello</>")
color.Println("<warning>hello</>")

// custom color attributes
color.Print("<fg=yellow;bg=black;op=underscore;>hello, welcome</>\n")

// Custom label attr: Supports the use of 16 color names, 256 color values, rgb color values and hex color values
color.Println("<fg=11aa23>he</><bg=120,35,156>llo</>, <fg=167;bg=232>wel</><fg=red>come</>")
Tag attributes

tag attributes format:

attr format:
 // VALUE please see var: FgColors, BgColors, AllOptions
 "fg=VALUE;bg=VALUE;op=VALUE"

16 color:
 "fg=yellow"
 "bg=red"
 "op=bold,underscore" // option is allow multi value
 "fg=white;bg=blue;op=bold"
 "fg=white;op=bold,underscore"

256 color:
 "fg=167"
 "fg=167;bg=23"
 "fg=167;bg=23;op=bold"
 
True color:
 // hex
 "fg=fc1cac"
 "fg=fc1cac;bg=c2c3c4"
 // r,g,b
 "fg=23,45,214"
 "fg=23,45,214;bg=109,99,88"

tag attributes parse please see func ParseCodeFromAttr()

Built-in tags

Built-in tags please see var colorTags in color_tag.go

// use style tag
color.Print("<suc>he</><comment>llo</>, <cyan>wel</><red>come</>")
color.Println("<suc>hello</>")
color.Println("<error>hello</>")

Run demo: go run ./_examples/color_tag.go

color-tags

Use color.Tag build message:

// set a style tag
color.Tag("info").Print("info style text")
color.Tag("info").Printf("%s style text", "info")
color.Tag("info").Println("info style text")

Color convert

Supports conversion between Rgb, 256, 16 colors, Rgb <=> 256 <=> 16

basic := color.Red
basic.Println("basic color")

c256 := color.Red.C256()
c256.Println("256 color")
c256.C16().Println("basic color")

rgb := color.Red.RGB()
rgb.Println("rgb color")
rgb.C256().Println("256 color")
Convert utils

color has many built-in color conversion utility functions.

func Basic2hex(val uint8) string

func Bg2Fg(val uint8) uint8
func Fg2Bg(val uint8) uint8

func C256ToRgb(val uint8) (rgb []uint8)
func C256ToRgbV1(val uint8) (rgb []uint8)

func Hex2basic(hex string, asBg ...bool) uint8
func Hex2rgb(hex string) []int
func HexToRGB(hex string) []int
func HexToRgb(hex string) (rgb []int)

func HslIntToRgb(h, s, l int) (rgb []uint8)
func HslToRgb(h, s, l float64) (rgb []uint8)
func HsvToRgb(h, s, v int) (rgb []uint8)

func Rgb2ansi(r, g, b uint8, isBg bool) uint8
func Rgb2basic(r, g, b uint8, isBg bool) uint8
func Rgb2hex(rgb []int) string
func Rgb2short(r, g, b uint8) uint8
func RgbTo256(r, g, b uint8) uint8
func RgbTo256Table() map[string]uint8
func RgbToAnsi(r, g, b uint8, isBg bool) uint8
func RgbToHex(rgb []int) string
func RgbToHsl(r, g, b uint8) []float64
func RgbToHslInt(r, g, b uint8) []int

Convert to RGBColor:

  • func RGBFromSlice(rgb []uint8, isBg ...bool) RGBColor
  • func RGBFromString(rgb string, isBg ...bool) RGBColor
  • func HEX(hex string, isBg ...bool) RGBColor
  • func HSL(h, s, l float64, isBg ...bool) RGBColor
  • func HSLInt(h, s, l int, isBg ...bool) RGBColor

Util functions

There are some useful functions reference

  • Disable() disable color render
  • SetOutput(io.Writer) custom set the colored text output writer
  • ForceOpenColor() force open color render
  • Colors2code(colors ...Color) string Convert colors to code. return like "32;45;3"
  • ClearCode(str string) string Use for clear color codes
  • ClearTag(s string) string clear all color html-tag for a string
  • IsConsole(w io.Writer) Determine whether w is one of stderr, stdout, stdin

More useful func please see https://pkg.go.dev/github.com/zhangyiming748/pretty/color

Detect color level

color automatically checks the color levels supported by the current environment.

// Level is the color level supported by a terminal.
type Level = terminfo.ColorLevel

// terminal color available level alias of the terminfo.ColorLevel*
const (
	LevelNo  = terminfo.ColorLevelNone     // not support color.
	Level16  = terminfo.ColorLevelBasic    // basic - 3/4 bit color supported
	Level256 = terminfo.ColorLevelHundreds // hundreds - 8-bit color supported
	LevelRgb = terminfo.ColorLevelMillions // millions - (24 bit)true color supported
)
  • func SupportColor() bool Whether the current environment supports color output
  • func Support256Color() bool Whether the current environment supports 256-color output
  • func SupportTrueColor() bool Whether the current environment supports (RGB)True-color output
  • func TermColorLevel() Level Get the currently supported color level

Projects using color

Check out these projects, which use https://github.com/zhangyiming748/pretty/color :

zhangyiming748/pretty packages

See also

License

MIT

Documentation

Overview

Package color is command line color library. Support rich color rendering output, universal API method, compatible with Windows system

Source code and other details for the project are available at GitHub:

https://github.com/zhangyiming748/pretty/color

More usage please see README and tests.

Example
// quick use like fmt.Print*
Red.Println("Simple to use color")
Green.Print("Simple to use color")
Cyan.Printf("Simple to use %s\n", "color")
Gray.Printf("Simple to use %s\n", "color")
Blue.Printf("Simple to use %s\n", "color")
Yellow.Printf("Simple to use %s\n", "color")
Magenta.Printf("Simple to use %s\n", "color")

// use like func
red := FgRed.Render
green := FgGreen.Render
fmt.Printf("%s line %s library\n", red("Command"), green("color"))

// custom color
New(FgWhite, BgBlack).Println("custom color style")

// can also:
Style{FgCyan, OpBold}.Println("custom color style")

// internal theme/style:
Info.Tips("message")
Info.Prompt("message")
Info.Println("info message")
Warn.Println("warning message")
Error.Println("error message")
Danger.Println("danger message")

// use style tag
Print("<suc>he</><comment>llo</>, <cyan>wel</><red>come</>\n")

// apply a style tag
Tag("info").Println("info style text")

// prompt message
Info.Prompt("prompt style message")
Warn.Prompt("prompt style message")

// tips message
Info.Tips("tips style message")
Warn.Tips("tips style message")
Output:

Index

Examples

Constants

View Source
const (
	// StartSet chars
	StartSet = "\x1b["
	// ResetSet close all properties.
	ResetSet = "\x1b[0m"
	// SettingTpl string.
	SettingTpl = "\x1b[%sm"
	// FullColorTpl for build color code
	FullColorTpl = "\x1b[%sm%s\x1b[0m"
	// CodeSuffix string for color code.
	CodeSuffix = "[0m"
)

color render templates

ESC 操作的表示:

"\033"(Octal 8进制) = "\x1b"(Hexadecimal 16进制) = 27 (10进制)
View Source
const (
	FgBase uint8 = 30
	BgBase uint8 = 40

	HiFgBase uint8 = 90
	HiBgBase uint8 = 100
)

Base value for foreground/background color base: fg 30~37, bg 40~47 light: fg 90~97, bg 100~107

View Source
const (
	Red     = FgRed
	Cyan    = FgCyan
	Gray    = FgDarkGray // is light Black
	Blue    = FgBlue
	Black   = FgBlack
	Green   = FgGreen
	White   = FgWhite
	Yellow  = FgYellow
	Magenta = FgMagenta

	Bold   = OpBold
	Normal = FgDefault

	LightRed     = FgLightRed
	LightCyan    = FgLightCyan
	LightBlue    = FgLightBlue
	LightGreen   = FgLightGreen
	LightWhite   = FgLightWhite
	LightYellow  = FgLightYellow
	LightMagenta = FgLightMagenta

	HiRed     = FgLightRed
	HiCyan    = FgLightCyan
	HiBlue    = FgLightBlue
	HiGreen   = FgLightGreen
	HiWhite   = FgLightWhite
	HiYellow  = FgLightYellow
	HiMagenta = FgLightMagenta

	BgHiRed     = BgLightRed
	BgHiCyan    = BgLightCyan
	BgHiBlue    = BgLightBlue
	BgHiGreen   = BgLightGreen
	BgHiWhite   = BgLightWhite
	BgHiYellow  = BgLightYellow
	BgHiMagenta = BgLightMagenta
)

There are basic and light foreground color aliases

View Source
const (
	TplFg256 = "38;5;%d"
	TplBg256 = "48;5;%d"
	Fg256Pfx = "38;5;"
	Bg256Pfx = "48;5;"
)

tpl for 8 bit 256 color(`2^8`)

format:

	ESC[ … 38;5;<n> … m // 选择前景色
 ESC[ … 48;5;<n> … m // 选择背景色

example:

fg "\x1b[38;5;242m"
bg "\x1b[48;5;208m"
both "\x1b[38;5;242;48;5;208m"

links:

https://zh.wikipedia.org/wiki/ANSI%E8%BD%AC%E4%B9%89%E5%BA%8F%E5%88%97#8位
View Source
const (
	TplFgRGB = "38;2;%d;%d;%d"
	TplBgRGB = "48;2;%d;%d;%d"
	FgRGBPfx = "38;2;"
	BgRGBPfx = "48;2;"
)

24 bit RGB color RGB:

R 0-255 G 0-255 B 0-255
R 00-FF G 00-FF B 00-FF (16进制)

Format:

ESC[ … 38;2;<r>;<g>;<b> … m // Select RGB foreground color
ESC[ … 48;2;<r>;<g>;<b> … m // Choose RGB background color

links:

https://zh.wikipedia.org/wiki/ANSI%E8%BD%AC%E4%B9%89%E5%BA%8F%E5%88%97#24位

example:

fg: \x1b[38;2;30;144;255mMESSAGE\x1b[0m
bg: \x1b[48;2;30;144;255mMESSAGE\x1b[0m
both: \x1b[38;2;233;90;203;48;2;30;144;255mMESSAGE\x1b[0m
View Source
const (
	AsFg uint8 = iota
	AsBg
)

mark color is fg or bg.

View Source
const (
	// MatchExpr regex to match color tags
	//
	// Notice: golang 不支持反向引用. 即不支持使用 \1 引用第一个匹配 ([a-z=;]+)
	// MatchExpr = `<([a-z=;]+)>(.*?)<\/\1>`
	// 所以调整一下 统一使用 `</>` 来结束标签,例如 "<info>some text</>"
	//
	// allow custom attrs, eg: "<fg=white;bg=blue;op=bold>content</>"
	// (?s:...) s - 让 "." 匹配换行
	MatchExpr = `<([0-9a-zA-Z_=,;]+)>(?s:(.*?))<\/>`

	// AttrExpr regex to match custom color attributes
	// eg: "<fg=white;bg=blue;op=bold>content</>"
	AttrExpr = `(fg|bg|op)[\s]*=[\s]*([0-9a-zA-Z,]+);?`

	// StripExpr regex used for removing color tags
	// StripExpr = `<[\/]?[a-zA-Z=;]+>`
	// 随着上面的做一些调整
	StripExpr = `<[\/]?[0-9a-zA-Z_=,;]*>`
)

output colored text like use html tag. (not support windows cmd)

View Source
const (
	LevelNo  = terminfo.ColorLevelNone     // not support color.
	Level16  = terminfo.ColorLevelBasic    // basic - 3/4 bit color supported
	Level256 = terminfo.ColorLevelHundreds // hundreds - 8-bit color supported
	LevelRgb = terminfo.ColorLevelMillions // millions - (24 bit)true color supported
)

terminal color available level alias of the terminfo.ColorLevel*

View Source
const CodeExpr = `\033\[[\d;?]+m`

CodeExpr regex to clear color codes eg "\033[1;36mText\x1b[0m"

Variables

View Source
var (
	// Enable switch color render and display
	//
	// NOTICE:
	// if ENV: NO_COLOR is not empty, will disable color render.
	Enable = os.Getenv("NO_COLOR") == ""
	// RenderTag render HTML tag on call color.Xprint, color.PrintX
	RenderTag = true
)
View Source
var (
	// Info color style
	Info = &Theme{"info", Style{OpReset, FgGreen}}
	// Note color style
	Note = &Theme{"note", Style{OpBold, FgLightCyan}}
	// Warn color style
	Warn = &Theme{"warning", Style{OpBold, FgYellow}}
	// Light color style
	Light = &Theme{"light", Style{FgLightWhite, BgBlack}}
	// Error color style
	Error = &Theme{"error", Style{FgLightWhite, BgRed}}
	// Danger color style
	Danger = &Theme{"danger", Style{OpBold, FgRed}}
	// Debug color style
	Debug = &Theme{"debug", Style{OpReset, FgCyan}}
	// Notice color style
	Notice = &Theme{"notice", Style{OpBold, FgCyan}}
	// Comment color style
	Comment = &Theme{"comment", Style{OpReset, FgYellow}}
	// Success color style
	Success = &Theme{"success", Style{OpBold, FgGreen}}
	// Primary color style
	Primary = &Theme{"primary", Style{OpReset, FgBlue}}
	// Question color style
	Question = &Theme{"question", Style{OpReset, FgMagenta}}
	// Secondary color style
	Secondary = &Theme{"secondary", Style{FgDarkGray}}
)

internal themes(like bootstrap style) Usage:

color.Info.Print("message")
color.Info.Printf("a %s message", "test")
color.Warn.Println("message")
color.Error.Println("message")
View Source
var AllOptions = map[string]Color{
	"reset":      OpReset,
	"bold":       OpBold,
	"fuzzy":      OpFuzzy,
	"italic":     OpItalic,
	"underscore": OpUnderscore,
	"blink":      OpBlink,
	"reverse":    OpReverse,
	"concealed":  OpConcealed,
}

AllOptions color options map

View Source
var BgColors = map[string]Color{
	"black":   BgBlack,
	"red":     BgRed,
	"green":   BgGreen,
	"yellow":  BgYellow,
	"blue":    BgBlue,
	"magenta": BgMagenta,
	"cyan":    BgCyan,
	"white":   BgWhite,
	"default": BgDefault,
}

BgColors background colors map

View Source
var ExBgColors = map[string]Color{
	"darkGray":     BgDarkGray,
	"lightRed":     BgLightRed,
	"lightGreen":   BgLightGreen,
	"lightYellow":  BgLightYellow,
	"lightBlue":    BgLightBlue,
	"lightMagenta": BgLightMagenta,
	"lightCyan":    BgLightCyan,
	"lightWhite":   BgLightWhite,
}

ExBgColors extra background colors map

View Source
var ExFgColors = map[string]Color{
	"darkGray":     FgDarkGray,
	"lightRed":     FgLightRed,
	"lightGreen":   FgLightGreen,
	"lightYellow":  FgLightYellow,
	"lightBlue":    FgLightBlue,
	"lightMagenta": FgLightMagenta,
	"lightCyan":    FgLightCyan,
	"lightWhite":   FgLightWhite,
}

ExFgColors extra foreground colors map

View Source
var FgColors = map[string]Color{
	"black":   FgBlack,
	"red":     FgRed,
	"green":   FgGreen,
	"yellow":  FgYellow,
	"blue":    FgBlue,
	"magenta": FgMagenta,
	"cyan":    FgCyan,
	"white":   FgWhite,
	"default": FgDefault,
}

FgColors foreground colors map

View Source
var Options = AllOptions

Options color options map

Deprecated: please use AllOptions instead.

View Source
var Styles = map[string]Style{
	"info":  {OpReset, FgGreen},
	"note":  {OpBold, FgLightCyan},
	"light": {FgLightWhite, BgRed},
	"error": {FgLightWhite, BgRed},

	"danger":  {OpBold, FgRed},
	"notice":  {OpBold, FgCyan},
	"success": {OpBold, FgGreen},
	"comment": {OpReset, FgMagenta},
	"primary": {OpReset, FgBlue},
	"warning": {OpBold, FgYellow},

	"question":  {OpReset, FgMagenta},
	"secondary": {FgDarkGray},
}

Styles internal defined styles, like bootstrap styles. Usage:

color.Styles["info"].Println("message")
View Source
var Themes = map[string]*Theme{
	"info":  Info,
	"note":  Note,
	"light": Light,
	"error": Error,

	"debug":   Debug,
	"danger":  Danger,
	"notice":  Notice,
	"success": Success,
	"comment": Comment,
	"primary": Primary,
	"warning": Warn,

	"question":  Question,
	"secondary": Secondary,
}

Themes internal defined themes. Usage:

color.Themes["info"].Println("message")

Functions

func AddStyle

func AddStyle(name string, s Style)

AddStyle add a style

func AddTheme

func AddTheme(name string, style Style)

AddTheme add a theme and style

func ApplyTag

func ApplyTag(tag string, a ...interface{}) string

ApplyTag for messages

func Basic2hex

func Basic2hex(val uint8) string

Basic2hex convert basic color to hex string.

func Basic2nameMap

func Basic2nameMap() map[uint8]string

Basic2nameMap data

func Bg2Fg

func Bg2Fg(val uint8) uint8

Bg2Fg bg color value to fg value

func Bluef

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

Bluef print message with Blue color

func Blueln

func Blueln(a ...interface{})

Blueln print message line with Blue color

func Bluep

func Bluep(a ...interface{})

Bluep print message with Blue color

func C256ToRgb

func C256ToRgb(val uint8) (rgb []uint8)

C256ToRgb convert an 256 color code to RGB numbers

func C256ToRgbV1

func C256ToRgbV1(val uint8) (rgb []uint8)

C256ToRgbV1 convert an 256 color code to RGB numbers refer https://github.com/torvalds/linux/commit/cec5b2a97a11ade56a701e83044d0a2a984c67b4

func ClearCode

func ClearCode(str string) string

ClearCode clear color codes.

eg:

"\033[36;1mText\x1b[0m" -> "Text"

func ClearTag

func ClearTag(s string) string

ClearTag clear all tag for a string

func Colors2code

func Colors2code(colors ...Color) string

Colors2code convert colors to code. return like "32;45;3"

func Cyanf

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

Cyanf print message with Cyan color

func Cyanln

func Cyanln(a ...interface{})

Cyanln print message line with Cyan color

func Cyanp

func Cyanp(a ...interface{})

Cyanp print message with Cyan color

func Disable

func Disable() bool

Disable disable color output

func Errorf

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

Errorf print message with Error style

func Errorln

func Errorln(a ...interface{})

Errorln print message with Error style

func Errorp

func Errorp(a ...interface{})

Errorp print message with Error color

func Fg2Bg

func Fg2Bg(val uint8) uint8

Fg2Bg fg color value to bg value

func ForceColor

func ForceColor() terminfo.ColorLevel

ForceColor force open color render

func ForceOpenColor

func ForceOpenColor() terminfo.ColorLevel

ForceOpenColor force open color render

func ForceSetColorLevel

func ForceSetColorLevel(level terminfo.ColorLevel) terminfo.ColorLevel

ForceSetColorLevel force open color render

func Fprint

func Fprint(w io.Writer, a ...interface{})

Fprint print rendered messages to writer

Notice: will ignore print error

func Fprintf

func Fprintf(w io.Writer, format string, a ...interface{})

Fprintf print format and rendered messages to writer. Notice: will ignore print error

func Fprintln

func Fprintln(w io.Writer, a ...interface{})

Fprintln print rendered messages line to writer Notice: will ignore print error

func GetColorTags

func GetColorTags() map[string]string

GetColorTags get all internal color tags

func GetTagCode

func GetTagCode(name string) string

GetTagCode get color code by tag name

func Grayf

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

Grayf print message with Gray color

func Grayln

func Grayln(a ...interface{})

Grayln print message line with Gray color

func Grayp

func Grayp(a ...interface{})

Grayp print message with Gray color

func Greenf

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

Greenf print message with Green color

func Greenln

func Greenln(a ...interface{})

Greenln print message line with Green color

func Greenp

func Greenp(a ...interface{})

Greenp print message with Green color

func Hex2basic

func Hex2basic(hex string, asBg ...bool) uint8

Hex2basic convert hex string to basic color code.

func Hex2rgb

func Hex2rgb(hex string) []int

Hex2rgb alias of the HexToRgb()

func HexToRGB

func HexToRGB(hex string) []int

HexToRGB alias of the HexToRgb()

func HexToRgb

func HexToRgb(hex string) (rgb []int)

HexToRgb convert hex color string to RGB numbers

Usage:

rgb := HexToRgb("ccc") // rgb: [204 204 204]
rgb := HexToRgb("aabbcc") // rgb: [170 187 204]
rgb := HexToRgb("#aabbcc") // rgb: [170 187 204]
rgb := HexToRgb("0xad99c0") // rgb: [170 187 204]

func HslIntToRgb

func HslIntToRgb(h, s, l int) (rgb []uint8)

HslIntToRgb Converts an HSL color value to RGB Assumes h: 0-360, s: 0-100, l: 0-100 returns r, g, and b in the set [0, 255].

Usage:

HslIntToRgb(0, 100, 50) // red
HslIntToRgb(120, 100, 50) // lime
HslIntToRgb(120, 100, 25) // dark green
HslIntToRgb(120, 100, 75) // light green

func HslToRgb

func HslToRgb(h, s, l float64) (rgb []uint8)

HslToRgb Converts an HSL color value to RGB. Conversion formula adapted from http://en.wikipedia.org/wiki/HSL_color_space. Assumes h, s, and l are contained in the set [0, 1] returns r, g, and b in the set [0, 255].

Usage:

rgbVals := HslToRgb(0, 1, 0.5) // red

func HsvToRgb

func HsvToRgb(h, s, v int) (rgb []uint8)

HsvToRgb Converts an HSL color value to RGB. Conversion formula adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#HSV_to_RGB Assumes h: 0-360, s: 0-100, l: 0-100 returns r, g, and b in the set [0, 255].

func Infof

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

Infof print message with Info style

func Infoln

func Infoln(a ...interface{})

Infoln print message with Info style

func Infop

func Infop(a ...interface{})

Infop print message with Info color

func InnerErrs

func InnerErrs() []error

InnerErrs info

func IsConsole

func IsConsole(w io.Writer) bool

IsConsole Determine whether w is one of stderr, stdout, stdin

func IsDefinedTag

func IsDefinedTag(name string) bool

IsDefinedTag is defined tag name

func IsLikeInCmd deprecated

func IsLikeInCmd() bool

IsLikeInCmd check result

Deprecated: please don't use

func IsMSys

func IsMSys() bool

IsMSys msys(MINGW64) environment, does not necessarily support color

func IsSupport16Color

func IsSupport16Color() bool

IsSupport16Color check current console is support color.

NOTICE: The method will detect terminal info each times,

if only want get current color level, please direct call SupportColor() or TermColorLevel()

func IsSupport256Color

func IsSupport256Color() bool

IsSupport256Color render check

NOTICE: The method will detect terminal info each times,

if only want to get current color level, please direct call SupportColor() or TermColorLevel()

func IsSupportColor

func IsSupportColor() bool

IsSupportColor check current console is support color.

NOTICE: The method will detect terminal info each times,

if only want get current color level, please direct call SupportColor() or TermColorLevel()

func IsSupportRGBColor

func IsSupportRGBColor() bool

IsSupportRGBColor check. alias of the IsSupportTrueColor()

NOTICE: The method will detect terminal info each times,

if only want get current color level, please direct call SupportColor() or TermColorLevel()

func IsSupportTrueColor

func IsSupportTrueColor() bool

IsSupportTrueColor render check.

NOTICE: The method will detect terminal info each times,

if only want get current color level, please direct call SupportColor() or TermColorLevel()

ENV: "COLORTERM=truecolor" "COLORTERM=24bit"

func IsTerminal

func IsTerminal(fd uintptr) bool

IsTerminal returns true if the given file descriptor is a terminal.

Usage:

IsTerminal(os.Stdout.Fd())

func IsWindows

func IsWindows() bool

IsWindows OS env

func Lprint

func Lprint(l *log.Logger, a ...interface{})

Lprint passes colored messages to a log.Logger for printing. Notice: should be goroutine safe

func Magentaf

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

Magentaf print message with Magenta color

func Magentaln

func Magentaln(a ...interface{})

Magentaln print message line with Magenta color

func Magentap

func Magentap(a ...interface{})

Magentap print message with Magenta color

func NotRenderTag

func NotRenderTag()

NotRenderTag on call color.Xprint, color.PrintX

func ParseCodeFromAttr

func ParseCodeFromAttr(attr string) (code string)

ParseCodeFromAttr parse color attributes.

attr format:

// VALUE please see var: FgColors, BgColors, AllOptions
"fg=VALUE;bg=VALUE;op=VALUE"

16 color:

"fg=yellow"
"bg=red"
"op=bold,underscore" // option is allow multi value
"fg=white;bg=blue;op=bold"
"fg=white;op=bold,underscore"

256 color:

"fg=167"
"fg=167;bg=23"
"fg=167;bg=23;op=bold"

True color:

// hex
"fg=fc1cac"
"fg=fc1cac;bg=c2c3c4"
// r,g,b
"fg=23,45,214"
"fg=23,45,214;bg=109,99,88"

func Print

func Print(a ...interface{})

Print render color tag and print messages

func Printf

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

Printf format and print messages

func Println

func Println(a ...interface{})

Println messages with new line

func Redf

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

Redf print message with Red color

func Redln

func Redln(a ...interface{})

Redln print message line with Red color

func Redp

func Redp(a ...interface{})

Redp print message with Red color

func Render

func Render(a ...interface{}) string

Render parse color tags, return rendered string.

Usage:

text := Render("<info>hello</> <cyan>world</>!")
fmt.Println(text)

func RenderCode

func RenderCode(code string, args ...interface{}) string

RenderCode render message by color code.

Usage:

msg := RenderCode("3;32;45", "some", "message")

func RenderString

func RenderString(code string, str string) string

RenderString render a string with color code.

Usage:

msg := RenderString("3;32;45", "a message")

func RenderWithSpaces

func RenderWithSpaces(code string, args ...interface{}) string

RenderWithSpaces Render code with spaces. If the number of args is > 1, a space will be added between the args

func ReplaceTag

func ReplaceTag(str string) string

ReplaceTag parse string, replace color tag and return rendered string

func Reset

func Reset() (int, error)

Reset reset console color attributes

func ResetOptions

func ResetOptions()

ResetOptions reset all package option setting

func ResetOutput

func ResetOutput()

ResetOutput reset output

func ResetTerminal

func ResetTerminal() error

ResetTerminal terminal setting.

func Rgb2ansi

func Rgb2ansi(r, g, b uint8, isBg bool) uint8

Rgb2ansi convert RGB-code to 16-code, alias of the RgbToAnsi()

func Rgb2basic

func Rgb2basic(r, g, b uint8, isBg bool) uint8

Rgb2basic alias of the RgbToAnsi()

func Rgb2hex

func Rgb2hex(rgb []int) string

Rgb2hex alias of the RgbToHex()

func Rgb2short

func Rgb2short(r, g, b uint8) uint8

Rgb2short convert RGB-code to 256-code

func RgbTo256

func RgbTo256(r, g, b uint8) uint8

RgbTo256 convert RGB-code to 256-code

func RgbTo256Table

func RgbTo256Table() map[string]uint8

RgbTo256Table mapping data

func RgbToAnsi

func RgbToAnsi(r, g, b uint8, isBg bool) uint8

RgbToAnsi convert RGB-code to 16-code refer https://github.com/radareorg/radare2/blob/master/libr/cons/rgb.c#L249-L271

func RgbToHex

func RgbToHex(rgb []int) string

RgbToHex convert RGB-code to hex-code

Usage:

hex := RgbToHex([]int{170, 187, 204}) // hex: "aabbcc"

func RgbToHsl

func RgbToHsl(r, g, b uint8) []float64

RgbToHsl Converts an RGB color value to HSL. Conversion formula

adapted from http://en.wikipedia.org/wiki/HSL_color_space.

Assumes r, g, and b are contained in the set [0, 255] and returns h, s, and l in the set [0, 1].

func RgbToHslInt

func RgbToHslInt(r, g, b uint8) []int

RgbToHslInt Converts an RGB color value to HSL. Conversion formula Assumes r, g, and b are contained in the set [0, 255] and returns [h,s,l] h: 0-360, s: 0-100, l: 0-100.

func Set

func Set(colors ...Color) (int, error)

Set console color attributes

func SetOutput

func SetOutput(w io.Writer)

SetOutput set default colored text output

func SetTerminal

func SetTerminal(code string) error

SetTerminal by given code.

func Sprint

func Sprint(a ...interface{}) string

Sprint parse color tags, return rendered string

func Sprintf

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

Sprintf format and return rendered string

func String

func String(s string) string

String alias of the ReplaceTag

func Successf

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

Successf print message with success style

func Successln

func Successln(a ...interface{})

Successln print message with success style

func Successp

func Successp(a ...interface{})

Successp print message with success color

func Support256Color

func Support256Color() bool

Support256Color Whether the current environment supports 256-color output

func SupportColor

func SupportColor() bool

SupportColor Whether the current environment supports color output

func SupportTrueColor

func SupportTrueColor() bool

SupportTrueColor Whether the current environment supports (RGB)True-color output

func Text

func Text(s string) string

Text alias of the ReplaceTag

func Warnf

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

Warnf print message with Warn style

func Warnln

func Warnln(a ...interface{})

Warnln print message with Warn style

func Warnp

func Warnp(a ...interface{})

Warnp print message with Warn color

func WrapTag

func WrapTag(s string, tag string) string

WrapTag wrap a tag for a string "<tag>content</>"

func Yellowf

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

Yellowf print message with Yellow color

func Yellowln

func Yellowln(a ...interface{})

Yellowln print message line with Yellow color

func Yellowp

func Yellowp(a ...interface{})

Yellowp print message with Yellow color

Types

type Basic

type Basic = Color // alias of Color

type Bit8Color

type Bit8Color = Color256 // alias

type Color

type Color uint8

Color Color16, 16 color value type 3(2^3=8) OR 4(2^4=16) bite color.

const (
	FgBlack Color = iota + 30
	FgRed
	FgGreen
	FgYellow
	FgBlue
	FgMagenta // 品红
	FgCyan    // 青色
	FgWhite
	// FgDefault revert default FG
	FgDefault Color = 39
)

Foreground colors. basic foreground colors 30 - 37

const (
	FgDarkGray Color = iota + 90 // 亮黑(灰)
	FgLightRed
	FgLightGreen
	FgLightYellow
	FgLightBlue
	FgLightMagenta
	FgLightCyan
	FgLightWhite
	// FgGray is alias of FgDarkGray
	FgGray Color = 90 // 亮黑(灰)
)

Extra foreground color 90 - 97(非标准)

const (
	BgBlack Color = iota + 40
	BgRed
	BgGreen
	BgYellow // BgBrown like yellow
	BgBlue
	BgMagenta
	BgCyan
	BgWhite
	// BgDefault revert default BG
	BgDefault Color = 49
)

Background colors. basic background colors 40 - 47

const (
	BgDarkGray Color = iota + 100
	BgLightRed
	BgLightGreen
	BgLightYellow
	BgLightBlue
	BgLightMagenta
	BgLightCyan
	BgLightWhite
	// BgGray is alias of BgDarkGray
	BgGray Color = 100
)

Extra background color 100 - 107(非标准)

const (
	OpReset         Color = iota // 0 重置所有设置
	OpBold                       // 1 加粗
	OpFuzzy                      // 2 模糊(不是所有的终端仿真器都支持)
	OpItalic                     // 3 斜体(不是所有的终端仿真器都支持)
	OpUnderscore                 // 4 下划线
	OpBlink                      // 5 闪烁
	OpFastBlink                  // 6 快速闪烁(未广泛支持)
	OpReverse                    // 7 颠倒的 交换背景色与前景色
	OpConcealed                  // 8 隐匿的
	OpStrikethrough              // 9 删除的,删除线(未广泛支持)
)

Option settings

func Bit4

func Bit4(code uint8) Color

Bit4 a method for create Color

func (Color) C256

func (c Color) C256() Color256

C256 convert 16 color to 256-color code.

func (Color) Code

func (c Color) Code() string

Code convert to code string. eg "35"

func (Color) Darken

func (c Color) Darken() Color

Darken current color. eg. 96(FgLightCyan) -> 36(FgCyan)

Usage:

cyan := LightCyan.Darken()
cyan.Print("message")

func (Color) IsValid

func (c Color) IsValid() bool

IsValid color value

func (Color) Light

func (c Color) Light() Color

Light current color. eg: 36(FgCyan) -> 96(FgLightCyan).

Usage:

lightCyan := Cyan.Light()
lightCyan.Print("message")

func (Color) Name

func (c Color) Name() string

Name get color code name.

func (Color) Print

func (c Color) Print(args ...interface{})

Print messages.

Usage:

color.Green.Print("message")

OR:

green := color.FgGreen.Print
green("message")

func (Color) Printf

func (c Color) Printf(format string, a ...interface{})

Printf format and print messages.

Usage:

color.Cyan.Printf("string %s", "arg0")

func (Color) Println

func (c Color) Println(a ...interface{})

Println messages with new line

func (Color) RGB

func (c Color) RGB() RGBColor

RGB convert 16 color to 256-color code.

func (Color) Render

func (c Color) Render(a ...interface{}) string

Render messages by color setting

Usage:

green := color.FgGreen.Render
fmt.Println(green("message"))

func (Color) Renderln

func (c Color) Renderln(a ...interface{}) string

Renderln messages by color setting. like Println, will add spaces for each argument

Usage:

green := color.FgGreen.Renderln
fmt.Println(green("message"))

func (Color) Sprint

func (c Color) Sprint(a ...interface{}) string

Sprint render messages by color setting. is alias of the Render()

func (Color) Sprintf

func (c Color) Sprintf(format string, args ...interface{}) string

Sprintf format and render message.

Usage:

	green := color.Green.Sprintf
 colored := green("message")

func (Color) String

func (c Color) String() string

String convert to code string. eg "35"

func (Color) Text

func (c Color) Text(message string) string

Text render a text message

func (Color) ToBg

func (c Color) ToBg() Color

ToBg always convert bg

func (Color) ToFg

func (c Color) ToFg() Color

ToFg always convert fg

type Color256

type Color256 [2]uint8

Color256 256 color (8 bit), uint8 range at 0 - 255

颜色值使用10进制和16进制都可 0x98 = 152

The color consists of two uint8:

0: color value
1: color type; Fg=0, Bg=1, >1: unset value

example:

	fg color: [152, 0]
 bg color: [152, 1]

NOTICE: now support 256 color on windows CMD, PowerShell lint warn - Name starts with package name

func Bit8

func Bit8(val uint8, isBg ...bool) Color256

Bit8 create a color256

func C256

func C256(val uint8, isBg ...bool) Color256

C256 create a color256

func (Color256) Basic

func (c Color256) Basic() Color

Basic convert color-256 to basic 16 color.

func (Color256) C16

func (c Color256) C16() Color

C16 convert color-256 to 16 color.

func (Color256) Code

func (c Color256) Code() string

Code convert to color code string. eg: "12"

func (Color256) FullCode

func (c Color256) FullCode() string

FullCode convert to color code string with prefix. eg: "38;5;12"

func (Color256) IsBg

func (c Color256) IsBg() bool

IsBg color

func (Color256) IsEmpty

func (c Color256) IsEmpty() bool

IsEmpty value

func (Color256) IsFg

func (c Color256) IsFg() bool

IsFg color

func (Color256) Print

func (c Color256) Print(a ...interface{})

Print print message

func (Color256) Printf

func (c Color256) Printf(format string, a ...interface{})

Printf format and print message

func (Color256) Println

func (c Color256) Println(a ...interface{})

Println print message with newline

func (Color256) RGB

func (c Color256) RGB() RGBColor

RGB convert color-256 to RGB color.

func (Color256) RGBColor

func (c Color256) RGBColor() RGBColor

RGBColor convert color-256 to RGB color.

func (Color256) Reset

func (c Color256) Reset() error

Reset terminal. alias of the ResetTerminal()

func (Color256) Set

func (c Color256) Set() error

Set terminal by 256 color code

func (Color256) Sprint

func (c Color256) Sprint(a ...interface{}) string

Sprint returns rendered message

func (Color256) Sprintf

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

Sprintf returns format and rendered message

func (Color256) String

func (c Color256) String() string

String convert to color code string with prefix. eg: "38;5;12"

func (Color256) ToBg

func (c Color256) ToBg() Color256

ToBg 256 color

func (Color256) ToFg

func (c Color256) ToFg() Color256

ToFg 256 color

func (Color256) Value

func (c Color256) Value() uint8

Value return color value

type Level

type Level = terminfo.ColorLevel

Level is the color level supported by a terminal.

func DetectColorLevel

func DetectColorLevel() Level

DetectColorLevel for current env

NOTICE: The method will detect terminal info each times,

if only want to get current color level, please direct call SupportColor() or TermColorLevel()

func TermColorLevel

func TermColorLevel() Level

TermColorLevel Get the currently supported color level

type Opts

type Opts []Color

Opts basic color options. code: 0 - 9

func (*Opts) Add

func (o *Opts) Add(ops ...Color)

Add option value

func (Opts) IsEmpty

func (o Opts) IsEmpty() bool

IsEmpty options

func (Opts) IsValid

func (o Opts) IsValid() bool

IsValid options

func (Opts) String

func (o Opts) String() string

String options to string. eg: "1;3"

type Printer

type Printer struct {
	// NoColor disable color.
	NoColor bool
	// Code color code string. eg "32;45;3"
	Code string
}

Printer a generic color message printer.

Usage:

p := &Printer{Code: "32;45;3"}
p.Print("message")

func NewPrinter

func NewPrinter(colorCode string) *Printer

NewPrinter instance

func (*Printer) IsEmpty

func (p *Printer) IsEmpty() bool

IsEmpty color code

func (*Printer) Print

func (p *Printer) Print(a ...interface{})

Print rendering colored messages

func (*Printer) Printf

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

Printf format and rendering colored messages

func (*Printer) Println

func (p *Printer) Println(a ...interface{})

Println rendering colored messages with newline

func (*Printer) Sprint

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

Sprint returns rendering colored messages

func (*Printer) Sprintf

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

Sprintf returns format and rendering colored messages

func (*Printer) String

func (p *Printer) String() string

String returns color code string. eg: "32;45;3"

type PrinterFace

type PrinterFace interface {
	fmt.Stringer
	Sprint(a ...interface{}) string
	Sprintf(format string, a ...interface{}) string
	Print(a ...interface{})
	Printf(format string, a ...interface{})
	Println(a ...interface{})
}

PrinterFace interface

type RGBColor

type RGBColor [4]uint8

RGBColor definition.

The first to third digits represent the color value. The last digit represents the foreground(0), background(1), >1 is unset value

Usage:

// 0, 1, 2 is R,G,B.
// 3rd: Fg=0, Bg=1, >1: unset value
RGBColor{30,144,255, 0}
RGBColor{30,144,255, 1}

NOTICE: now support RGB color on Windows CMD, PowerShell

func Bit24

func Bit24(r, g, b uint8, isBg ...bool) RGBColor

Bit24 alias of the RGB()

func HEX

func HEX(hex string, isBg ...bool) RGBColor

HEX create RGB color from a HEX color string.

Usage:

c := HEX("ccc") // rgb: [204 204 204]
c := HEX("aabbcc") // rgb: [170 187 204]
c := HEX("#aabbcc")
c := HEX("0xaabbcc")
c.Print("message")

func HSL

func HSL(h, s, l float64, isBg ...bool) RGBColor

HSL create RGB color from a hsl value. more see HslToRgb()

func HSLInt

func HSLInt(h, s, l int, isBg ...bool) RGBColor

HSLInt create RGB color from a hsl int value. more see HslIntToRgb()

func Hex

func Hex(hex string, isBg ...bool) RGBColor

Hex alias of the HEX()

func Hsl

func Hsl(h, s, l float64, isBg ...bool) RGBColor

Hsl alias of the HSL()

func HslInt

func HslInt(h, s, l int, isBg ...bool) RGBColor

HslInt alias of the HSLInt()

func RGB

func RGB(r, g, b uint8, isBg ...bool) RGBColor

RGB color create.

Usage:

c := RGB(30,144,255)
c := RGB(30,144,255, true)
c.Print("message")

func RGBFromHEX

func RGBFromHEX(hex string, isBg ...bool) RGBColor

RGBFromHEX quick RGBColor from hex string, alias of HEX()

func RGBFromSlice

func RGBFromSlice(rgb []uint8, isBg ...bool) RGBColor

RGBFromSlice quick RGBColor from slice

func RGBFromString

func RGBFromString(rgb string, isBg ...bool) RGBColor

RGBFromString create RGB color from a string. Support use color name in the {namedRgbMap}

Usage:

c := RGBFromString("170,187,204")
c.Print("message")

c := RGBFromString("brown")
c.Print("message with color brown")

func Rgb

func Rgb(r, g, b uint8, isBg ...bool) RGBColor

Rgb alias of the RGB()

func RgbFromInt

func RgbFromInt(r, g, b int, isBg ...bool) RGBColor

RgbFromInt create instance from int r,g,b value

func RgbFromInts

func RgbFromInts(rgb []int, isBg ...bool) RGBColor

RgbFromInts create instance from []int r,g,b value

func (RGBColor) Basic

func (c RGBColor) Basic() Color

Basic returns the closest approximate 16 (4 bit) color

func (RGBColor) C16

func (c RGBColor) C16() Color

C16 returns the closest approximate 16 (4 bit) color

func (RGBColor) C256

func (c RGBColor) C256() Color256

C256 returns the closest approximate 256 (8 bit) color

func (RGBColor) Code

func (c RGBColor) Code() string

Code to color code string without prefix. eg: "204;123;56"

func (RGBColor) Color

func (c RGBColor) Color() Color

Color returns the closest approximate 16 (4 bit) color

func (RGBColor) FullCode

func (c RGBColor) FullCode() string

FullCode to color code string with prefix

func (RGBColor) Hex

func (c RGBColor) Hex() string

Hex color rgb to hex string. as in "ff0080".

func (RGBColor) IsEmpty

func (c RGBColor) IsEmpty() bool

IsEmpty value

func (RGBColor) Print

func (c RGBColor) Print(a ...interface{})

Print print message

func (RGBColor) Printf

func (c RGBColor) Printf(format string, a ...interface{})

Printf format and print message

func (RGBColor) Println

func (c RGBColor) Println(a ...interface{})

Println print message with newline

func (RGBColor) Reset

func (c RGBColor) Reset() error

Reset terminal. alias of the ResetTerminal()

func (RGBColor) RgbString

func (c RGBColor) RgbString() string

RgbString to color code string without prefix. eg: "204,123,56"

func (RGBColor) Set

func (c RGBColor) Set() error

Set terminal by rgb/true color code

func (RGBColor) Sprint

func (c RGBColor) Sprint(a ...interface{}) string

Sprint returns rendered message

func (RGBColor) Sprintf

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

Sprintf returns format and rendered message

func (RGBColor) String

func (c RGBColor) String() string

String to color code string with prefix. eg: "38;2;204;123;56"

func (RGBColor) Values

func (c RGBColor) Values() []int

Values to RGB values

type RGBStyle

type RGBStyle struct {
	// Name of the style
	Name string
	// contains filtered or unexported fields
}

RGBStyle supports set foreground and background color

All are composed of 4 digits uint8, the first three digits are the color value; The last bit is different from RGBColor, here it indicates whether the value is set.

1    Has been set
^1   Not set

func HEXStyle

func HEXStyle(fg string, bg ...string) *RGBStyle

HEXStyle create a RGBStyle from HEX color string.

Usage:

s := HEXStyle("aabbcc", "eee")
s.Print("message")

func NewRGBStyle

func NewRGBStyle(fg RGBColor, bg ...RGBColor) *RGBStyle

NewRGBStyle create a RGBStyle.

func RGBStyleFromString

func RGBStyleFromString(fg string, bg ...string) *RGBStyle

RGBStyleFromString create a RGBStyle from color value string.

Usage:

s := RGBStyleFromString("170,187,204", "70,87,4")
s.Print("message")

func (*RGBStyle) AddOpts

func (s *RGBStyle) AddOpts(opts ...Color) *RGBStyle

AddOpts add options

func (*RGBStyle) Code

func (s *RGBStyle) Code() string

Code convert to color code string

func (*RGBStyle) FullCode

func (s *RGBStyle) FullCode() string

FullCode convert to color code string

func (*RGBStyle) IsEmpty

func (s *RGBStyle) IsEmpty() bool

IsEmpty style

func (*RGBStyle) Print

func (s *RGBStyle) Print(a ...interface{})

Print print message

func (*RGBStyle) Printf

func (s *RGBStyle) Printf(format string, a ...interface{})

Printf format and print message

func (*RGBStyle) Println

func (s *RGBStyle) Println(a ...interface{})

Println print message with newline

func (*RGBStyle) Set

func (s *RGBStyle) Set(fg, bg RGBColor, opts ...Color) *RGBStyle

Set fg and bg color, can also with color options

func (*RGBStyle) SetBg

func (s *RGBStyle) SetBg(bg RGBColor) *RGBStyle

SetBg set bg color

func (*RGBStyle) SetFg

func (s *RGBStyle) SetFg(fg RGBColor) *RGBStyle

SetFg set fg color

func (*RGBStyle) SetOpts

func (s *RGBStyle) SetOpts(opts Opts) *RGBStyle

SetOpts set color options

func (*RGBStyle) Sprint

func (s *RGBStyle) Sprint(a ...interface{}) string

Sprint returns rendered message

func (*RGBStyle) Sprintf

func (s *RGBStyle) Sprintf(format string, a ...interface{}) string

Sprintf returns format and rendered message

func (*RGBStyle) String

func (s *RGBStyle) String() string

String convert to color code string

type Scheme

type Scheme struct {
	Name   string
	Styles map[string]Style
}

Scheme struct

func NewDefaultScheme

func NewDefaultScheme(name string) *Scheme

NewDefaultScheme create an defuault color Scheme

func NewScheme

func NewScheme(name string, styles map[string]Style) *Scheme

NewScheme create new Scheme

func (*Scheme) Errorf

func (s *Scheme) Errorf(format string, a ...interface{})

Errorf message print

func (*Scheme) Errorln

func (s *Scheme) Errorln(v ...interface{})

Errorln message print

func (*Scheme) Infof

func (s *Scheme) Infof(format string, a ...interface{})

Infof message print

func (*Scheme) Infoln

func (s *Scheme) Infoln(v ...interface{})

Infoln message print

func (*Scheme) Style

func (s *Scheme) Style(name string) Style

Style get by name

func (*Scheme) Warnf

func (s *Scheme) Warnf(format string, a ...interface{})

Warnf message print

func (*Scheme) Warnln

func (s *Scheme) Warnln(v ...interface{})

Warnln message print

type SimplePrinter

type SimplePrinter struct{}

SimplePrinter use for quick use color print on inject to struct

func (*SimplePrinter) Errorf

func (s *SimplePrinter) Errorf(format string, a ...interface{})

Errorf message

func (*SimplePrinter) Errorln

func (s *SimplePrinter) Errorln(a ...interface{})

Errorln message

func (*SimplePrinter) Infof

func (s *SimplePrinter) Infof(format string, a ...interface{})

Infof message

func (*SimplePrinter) Infoln

func (s *SimplePrinter) Infoln(a ...interface{})

Infoln message

func (*SimplePrinter) Print

func (s *SimplePrinter) Print(v ...interface{})

Print message

func (*SimplePrinter) Printf

func (s *SimplePrinter) Printf(format string, v ...interface{})

Printf message

func (*SimplePrinter) Println

func (s *SimplePrinter) Println(v ...interface{})

Println message

func (*SimplePrinter) Warnf

func (s *SimplePrinter) Warnf(format string, a ...interface{})

Warnf message

func (*SimplePrinter) Warnln

func (s *SimplePrinter) Warnln(a ...interface{})

Warnln message

type Style

type Style []Color

Style a 16 color style. can add: fg color, bg color, color options

Example:

color.Style{color.FgGreen}.Print("message")

func GetStyle

func GetStyle(name string) Style

GetStyle get defined style by name

func New

func New(colors ...Color) Style

New create a custom style

Usage:

color.New(color.FgGreen).Print("message")
equals to:
color.Style{color.FgGreen}.Print("message")

func (*Style) Add

func (s *Style) Add(cs ...Color)

Add to global styles map

func (Style) Code

func (s Style) Code() string

Code convert to code string. returns like "32;45;3"

func (Style) IsEmpty

func (s Style) IsEmpty() bool

IsEmpty style

func (Style) Print

func (s Style) Print(a ...interface{})

Print render and Print text

func (Style) Printf

func (s Style) Printf(format string, a ...interface{})

Printf render and print text

func (Style) Println

func (s Style) Println(a ...interface{})

Println render and print text line

func (Style) Render

func (s Style) Render(a ...interface{}) string

Render render text Usage:

color.New(color.FgGreen).Render("text")
color.New(color.FgGreen, color.BgBlack, color.OpBold).Render("text")

func (Style) Renderln

func (s Style) Renderln(a ...interface{}) string

Renderln render text line. like Println, will add spaces for each argument Usage:

color.New(color.FgGreen).Renderln("text", "more")
color.New(color.FgGreen, color.BgBlack, color.OpBold).Render("text", "more")

func (Style) Save

func (s Style) Save(name string)

Save to global styles map

func (Style) Sprint

func (s Style) Sprint(a ...interface{}) string

Sprint is alias of the 'Render'

func (Style) Sprintf

func (s Style) Sprintf(format string, a ...interface{}) string

Sprintf format and render message.

func (Style) String

func (s Style) String() string

String convert to code string. returns like "32;45;3"

type Style256

type Style256 struct {
	// Name of the style
	Name string
	// contains filtered or unexported fields
}

Style256 definition

前/背景色 都是由两位uint8组成, 第一位是色彩值; 第二位与 Bit8Color 不一样的是,在这里表示是否设置了值 0 未设置 !=0 已设置

func S256

func S256(fgAndBg ...uint8) *Style256

S256 create a color256 style

Usage:

s := color.S256()
s := color.S256(132) // fg
s := color.S256(132, 203) // fg and bg

func (*Style256) AddOpts

func (s *Style256) AddOpts(opts ...Color) *Style256

AddOpts add options

func (*Style256) Code

func (s *Style256) Code() string

Code convert to color code string

func (*Style256) Print

func (s *Style256) Print(a ...interface{})

Print message

func (*Style256) Printf

func (s *Style256) Printf(format string, a ...interface{})

Printf format and print message

func (*Style256) Println

func (s *Style256) Println(a ...interface{})

Println print message with newline

func (*Style256) Set

func (s *Style256) Set(fgVal, bgVal uint8, opts ...Color) *Style256

Set fg and bg color value, can also with color options

func (*Style256) SetBg

func (s *Style256) SetBg(bgVal uint8) *Style256

SetBg set bg color value

func (*Style256) SetFg

func (s *Style256) SetFg(fgVal uint8) *Style256

SetFg set fg color value

func (*Style256) SetOpts

func (s *Style256) SetOpts(opts Opts) *Style256

SetOpts set options

func (*Style256) Sprint

func (s *Style256) Sprint(a ...interface{}) string

Sprint returns rendered message

func (*Style256) Sprintf

func (s *Style256) Sprintf(format string, a ...interface{}) string

Sprintf returns format and rendered message

func (*Style256) String

func (s *Style256) String() string

String convert to color code string

type Tag

type Tag string

Tag value is a defined style name Usage:

Tag("info").Println("message")

func (Tag) Print

func (tg Tag) Print(a ...interface{})

Print messages

func (Tag) Printf

func (tg Tag) Printf(format string, a ...interface{})

Printf format and print messages

func (Tag) Println

func (tg Tag) Println(a ...interface{})

Println messages line

func (Tag) Sprint

func (tg Tag) Sprint(a ...interface{}) string

Sprint render messages

func (Tag) Sprintf

func (tg Tag) Sprintf(format string, a ...interface{}) string

Sprintf format and render messages

type TagParser

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

TagParser struct

func NewTagParser

func NewTagParser() *TagParser

NewTagParser create

func (*TagParser) Parse

func (tp *TagParser) Parse(str string) string

Parse parse given string, replace color tag and return rendered string

Use built in tags:

<TAG_NAME>CONTENT</>
// e.g: `<info>message</>`

Custom tag attributes:

`<fg=VALUE;bg=VALUE;op=VALUES>CONTENT</>`
// e.g: `<fg=167;bg=232>wel</>`

func (*TagParser) ParseByEnv

func (tp *TagParser) ParseByEnv(str string) string

ParseByEnv parse given string. will check package setting.

type Theme

type Theme struct {
	// Name theme name
	Name string
	// Style for the theme
	Style
}

Theme definition. extends from Style

func GetTheme

func GetTheme(name string) *Theme

GetTheme get defined theme by name

func NewTheme

func NewTheme(name string, style Style) *Theme

NewTheme instance

func (*Theme) Block

func (t *Theme) Block(format string, a ...interface{})

Block like Prompt, but will wrap a empty line

func (*Theme) Prompt

func (t *Theme) Prompt(format string, a ...interface{})

Prompt use name as title, and apply style for message

func (*Theme) Save

func (t *Theme) Save()

Save to themes map

func (*Theme) Tips

func (t *Theme) Tips(format string, a ...interface{})

Tips use name as title, only apply style for name

Jump to

Keyboard shortcuts

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