color

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2018 License: MIT Imports: 5 Imported by: 2,164

README

cli color

Command line color library, written using golang

中文说明

Features

  • Easy to use
  • supports rich color output
  • supports html tab-style color rendering
  • compatible with Windows

Install

  • use dep
dep ensure -add gopkg.in/gookit/color.v1 // is recommended
// OR
dep ensure -add github.com/gookit/color
  • go get
go get gopkg.in/gookit/color.v1 // is recommended
// OR
go get -u github.com/gookit/color
  • git clone
git clone https://github.com/gookit/color

Godoc

Quick start

import "gopkg.in/gookit/color.v1" // is recommended
// or
import "github.com/gookit/color"
package main

import (
	"fmt"
	"github.com/gookit/color"
)

func main() {
	// simple usage
	color.Cyan.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 style:
	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")

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

	// use info style tips
	color.Tips("info").Print("tips style text")

	// use info style blocked tips
	color.LiteTips("info").Print("blocked tips style text")
}

run demo: go run ./_examples/app.go

Color output display

colored-out

More usage
Basic color usage

support on windows cmd.exe

  • color.Bold
  • color.Black
  • color.White
  • color.Gray
  • color.Red
  • color.Green
  • color.Yellow
  • color.Blue
  • color.Magenta
  • color.Cyan
color.Bold.Println("bold message")
color.Yellow.Println("yellow message")
Extra styles

support on windows cmd.exe

  • color.Info
  • color.Note
  • color.Light
  • color.Error
  • color.Danger
  • color.Notice
  • color.Success
  • color.Comment
  • color.Primary
  • color.Warning
  • color.Question
  • color.Secondary
color.Info.Print("Info message")
color.Success.Print("Success message")
Use like html tag

not support on windows cmd.exe

// 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")
  • color.Tag
// 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")
Internal color tags
// Some internal defined style tags
// usage: <tag>content text</>

// basic tags
- red
- blue
- cyan
- black
- green
- brown
- white
- default  // no color
- normal// no color
- yellow  
- magenta 

// alert tags like bootstrap's alert
- suc // same "green" and "bold"
- success 
- info // same "green"
- comment  // same "brown"
- note 
- notice  
- warn
- warning 
- primary 
- danger // same "red"
- err 
- error

// more tags
- lightRed
- light_red
- lightGreen
- light_green
- lightBlue 
- light_blue
- lightCyan
- light_cyan
- lightDray
- light_gray
- gray
- darkGray
- dark_gray
- lightYellow
- light_yellow  
- lightMagenta  
- light_magenta 

// extra
- lightRedEx
- light_red_ex
- lightGreenEx
- light_green_ex 
- lightBlueEx
- light_blue_ex  
- lightCyanEx
- light_cyan_ex  
- whiteEx
- white_ex

// option
- bold
- underscore 
- reverse

Ref

License

MIT

Documentation

Overview

Example
// simple usage
Cyan.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 style:
Info.Println("message")
Warn.Println("message")
Error.Println("message")

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

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

// use info style tips
Tips("info").Print("tips style text")

// use info style blocked tips
LiteTips("info").Print("blocked tips style text")
Output:

Index

Examples

Constants

View Source
const (
	// Bold use bold for message
	Bold = OpBold
	// Red color for message
	Red = FgRed
	// Cyan color for message
	Cyan = FgCyan
	// Gray color for message
	Gray = FgDarkGray
	// Blue color for message
	Blue = FgBlue
	// Black color for message
	Black = FgBlack
	// Green color for message
	Green = FgGreen
	// White color for message
	White = FgWhite
	// Normal color for message
	Normal = FgDefault
	// Yellow color for message
	Yellow = FgYellow
	// Magenta color for message
	Magenta = FgMagenta
)
View Source
const (
	// Regex to match color tags
	// golang 不支持反向引用.  即不支持使用 \1 引用第一个匹配 ([a-z=;]+)
	// TagExpr = `<([a-z=;]+)>(.*?)<\/\1>`
	// 所以调整一下 统一使用 `</>` 来结束标签,例如 "<info>some text</>"
	// 支持自定义颜色属性的tag "<fg=white;bg=blue;op=bold>content</>"
	// (?s:...) s - 让 "." 匹配换行
	TagExpr = `<([a-zA-Z_=,;]+)>(?s:(.*?))<\/>`

	// Regex to match color attributes
	AttrExpr = `(fg|bg|op)=([a-z,]+);?`

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

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

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

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

View Source
const FullColorTpl = "\x1b[%sm%s\x1b[0m"
View Source
const ResetCode = "\x1b[0m"

ESC 操作的表示 "\033"(Octal 8进制) = "\x1b"(Hexadecimal 16进制) = 27 (10进制)

View Source
const SetRgbBg = "\x1b[48;2;%d;%d;%dm"
View Source
const SetRgbFg = "\x1b[38;2;%d;%d;%dm"

24 byte 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 // 选择RGB前景色
ESC[ … 48;2;<r>;<g>;<b> … m // 选择RGB背景色

links:

https://zh.wikipedia.org/wiki/ANSI转义序列#24位
View Source
const SettingTpl = "\x1b[%sm"

CLI color template

View Source
const SingleColorTpl = "\x1b[%dm%s\x1b[0m"
View Source
const Tpl256Bg = "48;5;%d"
View Source
const Tpl256Fg = "38;5;%d"

8 byte 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转义序列#8位

Variables

View Source
var (
	// Info color style
	Info = Style{OpReset, FgGreen}
	// Note color style
	Note = Style{OpBold, FgLightCyan}
	// Warn color style
	Warn = Style{OpBold, FgYellow}
	// Light color style
	Light = Style{FgLightWhite}
	// Error color style
	Error = Style{FgLightWhite, BgRed}
	// Danger color style
	Danger = Style{OpBold, FgRed}
	// Notice color style
	Notice = Style{OpBold, FgCyan}
	// Comment color style
	Comment = Style{OpReset, FgMagenta}
	// Success color style
	Success = Style{OpBold, FgGreen}
	// Primary color style
	Primary = Style{OpReset, FgBlue}
	// Question color style
	Question = Style{OpReset, FgMagenta}
	// Secondary color style
	Secondary = Style{FgDarkGray}
)

internal styles(like bootstrap style) usage:

color.Info.Print("message")
color.Info.Println("new line")
color.Info.Printf("a %s message", "test")
color.Warn.Println("message")
color.Error.Println("message")
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,
}

Background colors map

View Source
var Enable = true

switch color display

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,
}

Foreground colors map

View Source
var Options = map[string]Color{
	"reset":      OpReset,
	"bold":       OpBold,
	"fuzzy":      OpFuzzy,
	"italic":     OpItalic,
	"underscore": OpUnderscore,
	"blink":      OpBlink,
	"reverse":    OpReverse,
	"concealed":  OpConcealed,
}

color options map

View Source
var Styles = map[string]Style{
	"info":  Info,
	"note":  Note,
	"light": Light,
	"error": Error,

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

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

Some defined styles, like bootstrap styles

Functions

func AddStyle

func AddStyle(name string, s Style)

AddStyle add a style

func Apply

func Apply(str string, colors ...Color) string

Apply custom colors. usage:

		// (string, fg-color,bg-color, options...)
 	color.Apply("text", color.FgGreen)
 	color.Apply("text", color.FgGreen, color.BgBlack, color.OpBold)

func ApplyTag

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

ApplyTag

func Byte24Color

func Byte24Color(str string)

Byte24Color use RGB color

func Byte8Color

func Byte8Color(str string, val Bt8Color)

Byte8Color use 8 byte, 0 - 255 color

func ClearCode

func ClearCode(str string) string

ClearCode clear color codes eg:

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

func ClearTag

func ClearTag(str string) string

ClearTag clear all tag for a string

func Disable

func Disable()

Disable disable color output

func Fprint

func Fprint(w io.Writer, args ...interface{}) (int, error)

Fprint print rendered messages to writer

func Fprintf

func Fprintf(w io.Writer, format string, args ...interface{}) (int, error)

Fprintf print format and rendered messages to writer

func Fprintln

func Fprintln(w io.Writer, args ...interface{}) (int, error)

Fprintln print rendered messages line to writer

func GetColorTags

func GetColorTags() map[string]string

GetColorTags

func GetStyleCode

func GetStyleCode(name string) string

GetStyleCode get color code by tag name

func GetStyleName

func GetStyleName(name string) string

GetStyleName

func IsBgColor

func IsBgColor(name string) bool

IsBgColor

func IsDefinedTag

func IsDefinedTag(name string) bool

IsDefinedTag is defined tag name

func IsDisabled

func IsDisabled() bool

IsDisabled color

func IsFgColor

func IsFgColor(name string) bool

IsFgColor

func IsOption

func IsOption(name string) bool

IsOption

func ParseCodeFromAttr

func ParseCodeFromAttr(attr string) (code string)

ParseCodeFromAttr parse color attributes. attr like:

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

eg:

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

func Print

func Print(args ...interface{}) (int, error)

Print messages

func Printf

func Printf(format string, args ...interface{}) (int, error)

Printf format and print messages

func Println

func Println(args ...interface{}) (int, error)

Println messages line

func Render

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

Render return rendered string

func RenderCodes

func RenderCodes(code string, str string) string

RenderCodes render by color code "3;32;45"

func RenderStr

func RenderStr(str string) string

RenderStr alias of the ReplaceTag

func ReplaceTag

func ReplaceTag(str string, dumpIt ...bool) string

ReplaceTag parse string, replace tag and return rendered string

func Reset

func Reset() (int, error)

Reset reset console color attributes

func Set

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

Set set console color attributes

func TrueColor

func TrueColor(str string, rgb RgbColor)

Byte24Color use RGB color

func WrapTag

func WrapTag(str string, tag string) string

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

Types

type Bt8Color

type Bt8Color uint8

uint8 at 0 - 255 10进制和16进制都可 0x98 = 152 use 8 byte, 0 - 255 color

type Bt8Style

type Bt8Style struct {
	Fg, Bg Bt8Color
}

func (*Bt8Style) Print

func (s *Bt8Style) Print(args ...interface{}) (n int, err error)

func (*Bt8Style) String

func (s *Bt8Style) String() string

type Color

type Color uint8

Color represents a text color.

const (
	// basic Foreground colors 30 - 37
	FgBlack Color = iota + 30
	FgRed
	FgGreen
	FgYellow
	FgBlue
	FgMagenta // 品红
	FgCyan    // 青色
	FgWhite

	// revert default FG
	FgDefault Color = 39

	// extra Foreground color 90 - 97(非标准)
	FgGray     Color = 90        // 亮黑(灰)
	FgDarkGray Color = iota + 90 // 亮黑(灰)
	FgLightRed
	FgLightGreen
	FgLightYellow
	FgLightBlue
	FgLightMagenta
	FgLightCyan
	FgLightWhite
)

Foreground colors.

const (
	// basic Background colors 40 - 47
	BgBlack Color = iota + 40
	BgRed
	BgGreen
	BgYellow // BgBrown like yellow
	BgBlue
	BgMagenta
	BgCyan
	BgWhite

	// revert default BG
	BgDefault Color = 49

	// extra Background color 100 - 107(非标准)
	BgGray     Color = 100
	BgDarkGray Color = iota + 100
	BgLightRed
	BgLightGreen
	BgLightYellow
	BgLightBlue
	BgLightMagenta
	BgLightCyan
	BgLightWhite
)

Background colors.

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

Option settings

func (Color) IsValid

func (c Color) IsValid() bool

IsValid 检测是否为一个有效的 Color 值

func (Color) Print

func (c Color) Print(args ...interface{}) (int, error)

Print messages usage:

color.FgGreen.Print("message")

or:

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

func (Color) Printf

func (c Color) Printf(format string, args ...interface{}) (int, error)

Printf format and print messages usage:

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

func (Color) Println

func (c Color) Println(args ...interface{}) (int, error)

Println messages line

func (Color) Render

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

Render messages by color setting usage:

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

func (Color) Renderf

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

Renderf format and render message usage:

	green := color.FgGreen.RenderFn()
 colored := green("message")

func (Color) String

func (c Color) String() string

String to string

type LiteTips

type LiteTips string

LiteTips will only add color for tag name value is a defined style name

func (LiteTips) Print

func (t LiteTips) Print(args ...interface{}) (int, error)

Print messages

func (LiteTips) Printf

func (t LiteTips) Printf(format string, args ...interface{}) (int, error)

Printf format and print messages

func (LiteTips) Println

func (t LiteTips) Println(args ...interface{}) (int, error)

Println messages line

type RgbColor

type RgbColor [3]uint8

type RgbStyle

type RgbStyle struct {
	Fg, Bg RgbColor
}

type Style

type Style []Color

Style a colored style can add: fg color, bg color, color options quick use:

color.Style(color.FgGreen).

func GetStyle

func GetStyle(name string) Style

GetStyle get style by name

func New

func New(colors ...Color) Style

New create a custom style

func (Style) IsEmpty added in v1.1.0

func (s Style) IsEmpty() bool

IsEmpty style

func (Style) Print

func (s Style) Print(args ...interface{}) (int, error)

Print render and Print text

func (Style) Printf

func (s Style) Printf(format string, args ...interface{}) (int, error)

Printf render and Print text

func (Style) Println

func (s Style) Println(args ...interface{}) (int, error)

Println render and print text line

func (Style) Render

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

Render render text usage:

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

func (Style) Save

func (s Style) Save(name string)

Save save to styles map

func (Style) Sprint added in v1.1.0

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

Sprint is alias of the 'Render'

type Tag

type Tag string

Tag value is a defined style name

func (Tag) Print

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

Print messages

func (Tag) Printf

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

Printf format and print messages

func (Tag) Println

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

Println messages line

func (Tag) Sprint added in v1.1.0

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

Sprint render messages

type Tips

type Tips string

Tips will add color for all text value is a defined style name

func (Tips) Print

func (t Tips) Print(args ...interface{}) (int, error)

Print messages

func (Tips) Printf

func (t Tips) Printf(format string, args ...interface{}) (int, error)

Printf format and print messages

func (Tips) Println

func (t Tips) Println(args ...interface{}) (int, error)

Println messages line

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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