ccolor

package
v0.7.2 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2025 License: MIT Imports: 8 Imported by: 7

README

CColor

CColor is a simple command-line color output library that uses ANSI color codes to output text with colors. Its main code is a partial code extracted and simplified from gookit/color, which only supports simple 16-color ANSI color output.

Tip: If you want to render with richer colors, use the github.com/gookit/color package.

Install

go get github.com/gookit/goutil/x/ccolor

Documentation

Overview

Package ccolor is a simple color render library for terminal. Its main code is the code that is extracted and simplified from gookit/color,

TIP:

If you want to render with richer colors, use the https://github.com/gookit/color package.

Index

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 (
	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 (
	// MatchExpr regex to match color tags
	//
	// Notice: golang 不支持反向引用. 即不支持使用 \1 引用第一个匹配 ([a-z=;]+)
	// MatchExpr = `<([a-z=;]+)>(.*?)<\/\1>`
	// 所以调整一下 统一使用 `</>` 来结束标签,例如 "<info>some text</>"
	//
	// - NOTE: 不支持自定义属性。如有需要请使用 gookit/color 包
	//
	// (?s:...) s - 让 "." 匹配换行
	MatchExpr = `<([0-9a-zA-Z_]+)>(?s:(.*?))<\/>`

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

output colored text like uses custom tag.

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

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

Variables

View Source
var (
	// Info color style
	Info = &Style{Fg: FgGreen}
	// Warn color style
	Warn = &Style{Fg: FgYellow}
	// Error color style
	Error = NewStyle(FgLightWhite, BgRed)
	// Debug color style
	Debug = &Style{Fg: FgCyan}
	// Success color style
	Success = &Style{Fg: FgGreen, Opts: []Color{OpBold}}
)
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

Functions

func ApplyTag

func ApplyTag(tag string, a ...any) string

ApplyTag for messages

func Bg2Fg

func Bg2Fg(val uint8) uint8

Bg2Fg bg color value to fg value

func Bluef

func Bluef(format string, a ...any)

Bluef print message with Blue color

func Blueln

func Blueln(a ...any)

Blueln print message line with Blue color

func Bluep

func Bluep(a ...any)

Bluep print message with Blue color

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 ColorTags

func ColorTags() map[string]string

ColorTags get all internal color tags

func ColorsToCode

func ColorsToCode(colors ...Color) string

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

func Cyanf

func Cyanf(format string, a ...any)

Cyanf print message with Cyan color

func Cyanln

func Cyanln(a ...any)

Cyanln print message line with Cyan color

func Cyanp

func Cyanp(a ...any)

Cyanp print message with Cyan color

func Disable

func Disable()

Disable color of current terminal.

func Errorf

func Errorf(format string, a ...any)

Errorf print message with error style

func Errorln

func Errorln(a ...any)

Errorln print message with error style

func Errorp

func Errorp(a ...any)

Errorp print message with error color

func Fg2Bg

func Fg2Bg(val uint8) uint8

Fg2Bg fg color value to bg value

func ForceEnableColor

func ForceEnableColor()

ForceEnableColor setting value. TIP: use for unit testing.

Usage:

ccolor.ForceEnableColor()
defer ccolor.RevertColorSupport()

func Fprint

func Fprint(w io.Writer, v ...any)

Fprint auto parse color-tag, print rendered messages to the writer

func Fprintf

func Fprintf(w io.Writer, format string, v ...any)

Fprintf auto parse color-tag, print rendered messages to the writer.

func Fprintln

func Fprintln(w io.Writer, v ...any)

Fprintln auto parse color-tag, print rendered messages to the writer

func GetTagCode

func GetTagCode(name string) string

GetTagCode get color code by tag name

func Grayf

func Grayf(format string, a ...any)

Grayf print message with gray color

func Grayln

func Grayln(a ...any)

Grayln print message line with gray color

func Grayp

func Grayp(a ...any)

Grayp print message with gray color

func Greenf

func Greenf(format string, a ...any)

Greenf print message with green color

func Greenln

func Greenln(a ...any)

Greenln print message line with green color

func Greenp

func Greenp(a ...any)

Greenp print message with green color

func Infof

func Infof(format string, a ...any)

Infof print message with info style

func Infoln

func Infoln(a ...any)

Infoln print message with info style

func Infop

func Infop(a ...any)

Infop print message with info color

func IsDefinedTag

func IsDefinedTag(name string) bool

IsDefinedTag is defined tag name

func IsSupport256Color

func IsSupport256Color() bool

IsSupport256Color returns true if the terminal supports 256 colors.

func IsSupportColor

func IsSupportColor() bool

IsSupportColor returns true if the terminal supports color.

func IsSupportTrueColor

func IsSupportTrueColor() bool

IsSupportTrueColor returns true if the terminal supports true color.

func LastErr

func LastErr() error

LastErr info

func Level

func Level() termenv.ColorLevel

Level value of current terminal.

func Lprint

func Lprint(l *log.Logger, v ...any)

Lprint passes colored messages to a log.Logger for printing.

func Magentaf

func Magentaf(format string, a ...any)

Magentaf print message with magenta color

func Magentaln

func Magentaln(a ...any)

Magentaln print message line with magenta color

func Magentap

func Magentap(a ...any)

Magentap print message with magenta color

func ParseTag

func ParseTag(str string) string

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

Use built in tags:

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

TIP: code is from gookit/color package

  • Not support custom attributes
  • Not support c256 or rgb color

func ParseTagByEnv

func ParseTagByEnv(str string) string

ParseTagByEnv parse given string. will check package setting.

func Print

func Print(v ...any)

Print parse color tag and print messages

func Printf

func Printf(format string, v ...any)

Printf format and print messages

func Println

func Println(v ...any)

Println messages with new line

func Redf

func Redf(format string, a ...any)

Redf print message with Red color

func Redln

func Redln(a ...any)

Redln print message line with Red color

func Redp

func Redp(a ...any)

Redp print message with Red color

func Render

func Render(a ...any) 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 ...any) 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 ...any) 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 RevertColorSupport

func RevertColorSupport()

RevertColorSupport value

func SetOutput

func SetOutput(w io.Writer)

SetOutput set output writer

func Sprint

func Sprint(v ...any) string

Sprint parse color tags, return rendered string

func Sprintf

func Sprintf(format string, a ...any) string

Sprintf format and return rendered string

func Successf

func Successf(format string, a ...any)

Successf print message with success style

func Successln

func Successln(a ...any)

Successln print message with success style

func Successp

func Successp(a ...any)

Successp print message with success color

func Warnf

func Warnf(format string, a ...any)

Warnf print message with warn style

func Warnln

func Warnln(a ...any)

Warnln print message with warn style

func Warnp

func Warnp(a ...any)

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 ...any)

Yellowf print message with yellow color

func Yellowln

func Yellowln(a ...any)

Yellowln print message line with yellow color

func Yellowp

func Yellowp(a ...any)

Yellowp print message with yellow color

Types

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 (non-standard)

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. range: 0 - 9

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) IsBg

func (c Color) IsBg() bool

IsBg check is background color

func (Color) IsFg

func (c Color) IsFg() bool

IsFg check is foreground color

func (Color) IsOption

func (c Color) IsOption() bool

IsOption check is option code: 0-9

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) Print

func (c Color) Print(args ...any)

Print messages.

Usage:

ccolor.Green.Print("message")

OR:

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

func (Color) Printf

func (c Color) Printf(format string, a ...any)

Printf format and print messages.

Usage:

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

func (Color) Println

func (c Color) Println(a ...any)

Println messages with new line

func (Color) Render

func (c Color) Render(a ...any) string

Render messages by color setting

Usage:

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

func (Color) Renderln

func (c Color) Renderln(a ...any) string

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

Usage:

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

func (Color) Sprint

func (c Color) Sprint(a ...any) string

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

func (Color) Sprintf

func (c Color) Sprintf(format string, args ...any) string

Sprintf format and render message.

Usage:

	green := ccolor.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 String

type String string

String color style string. TODO eg:

s := String("red,bold")
s.Println("some text message")

type Style

type Style struct {
	Fg   Color
	Bg   Color
	Opts []Color
}

Style for color render.

func NewStyle

func NewStyle(fg Color, bg Color, opts ...Color) *Style

NewStyle fg, bg and options

func (*Style) Fprint

func (s *Style) Fprint(w io.Writer, v ...any)

Fprint like fmt.Fprint, but with color

func (*Style) Print

func (s *Style) Print(v ...any)

Print like fmt.Print, but with color

func (*Style) Printf

func (s *Style) Printf(format string, v ...any)

Printf render and print text

func (*Style) Println

func (s *Style) Println(v ...any)

Println like fmt.Println, but with color

func (*Style) Sprint

func (s *Style) Sprint(v ...any) string

Sprint like fmt.Sprint, but with color

func (*Style) Sprintf

func (s *Style) Sprintf(format string, v ...any) string

Sprintf format and render message.

func (*Style) Sprintln

func (s *Style) Sprintln(v ...any) string

Sprintln like fmt.Sprintln, but with color

func (*Style) String

func (s *Style) String() string

String convert style setting to color code string.

Jump to

Keyboard shortcuts

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