Terminal string styling for go done right, with full and painless Windows 10 support.

GChalk

PkgGoDev Build Status Go Report Card Release

GChalk is a library heavily inspired by chalk, the popular Node.js terminal color library, and using go ports of supports-color and ansi-styles.

Features

Feature Comparison

Feature gchalk aurora fatih/color mgutz/ansi
TTY Detection (1)
Color Detection
Windows 10 (2)
Nested Styles (3)
256 Color Support (4) (4)
16.7m Color Support
Speed 60ns 196ns 420ns 40ns
  1. fatih/color supports automatic TTY detection, but assumes that if stdout is not a TTY, then stderr is also not a TTY, which may not be true.
  2. fatih/color supports Windows 10, but you need to write to a special stream.
  3. aurora supports nested styles via its custom Sprintf(), but you can't convert things to a string first - need to keep everything as aurora Values.
  4. aurora and mgutz/ansi both support 256 color output, but they don't detect whether the terminal supports it or not, and won't automatically convert 256 color output to 16 color output if it doesn't.

Install

go get github.com/jwalton/gchalk

Usage

package main

import (
    "fmt"
    "github.com/jwalton/gchalk"
)

func main() {
    fmt.Println(gchalk.Blue("This line is blue"))
}

Note that this works on all platforms - there's no need to write to a special stream or use a special print function to get color on Windows 10.

GChalk uses a chainable syntax for composing styles together, which should be instantly familiar if you've ever used chalk or similar libraries. To style a string blue, for example, you"d call gchalk.Blue("hello"). To style it blue with a red background, you can use gchalk.WithBgRed().Blue("hello").

// Combine styled and normal strings
fmt.Println(gchalk.Blue("Hello") + " World" + gchalk.Red("!"))

// Compose multiple styles using the chainable API
fmt.Println(gchalk.WithBlue().WithBgRed().Bold("Hello world!"))

// Pass in multiple arguments
fmt.Println(gchalk.Blue("Hello", "World!", "Foo", "bar", "biz", "baz"))

// Nest styles
fmt.Println(gchalk.Green(
    "I am a green line " +
    gchalk.WithBlue().WithUnderline().Bold("with a blue substring") +
    " that becomes green again!"
))

// Use RGB colors in terminal emulators that support it.
fmt.Println(gchalk.WithRGB(123, 45, 67).Underline("Underlined reddish color"))
fmt.Println(gchalk.WihHex("#DEADED").Bold("Bold gray!"))

// Use color name strings
fmt.Println(gchalk.StyleMust("blue")("Hello World!"))


// Write to stderr:
os.Stderr.WriteString(gchalk.Stderr.Red("Ohs noes!\n"))

You can easily define your own themes:

var error = gchalk.WithBold().Red
var warning = gchalk.Yellow

fmt.Println(error("Error!"))
fmt.Println(warning("Warning!"))

API

gchalk[.With<style>][.with<style>...].<style>(string [, string...])

Example:

fmt.Println(gchalk.WithRed().WithBold().Underline("Hello", "world"))

Chain styles and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. Multiple arguments will be separated by a space.

You can also obtain a Builder instance and then use the Paint() function, similar to Rust's ansi_term crate, or use the Sprintf() convenience function:

fmt.Println(gchalk.WithRed().Paint("Hello", "world"))
fmt.Println(gchalk.WithRed().Sprintf("Hello %v", "world"))

gchalk.Style(style [, style...])(string [, string...])

Example:

styler, err := gchalk.Style("bold", "red")
if err == nil {
    fmt.Println(styler("This is bold and red"))
}

fmt.Println(gchalk.StyleMust("bold", "red")("This is also bold and red."))

Style and StyleMust allow styling a string based on the names of colors and modifiers. There's also a WithStyle and WithStyleMust for chaining named styles with other styles.

gchalk.SetLevel(level) and gchalk.GetLevel()

Specifies the level of color support. See the section on color detection for details about how gchalk auto-detects color support. You can override the detected level by calling SetLevel(). You should however only do this in your own application, as it applies globally to all gchalk consumers. If you need to change this in a library, create a new instance:

var myGChalk = gchalk.New(gchalk.ForceLevel(gchalk.LevelNone))
Level Description
LevelNone = 0 All colors disabled
LevelBasic = 1 Basic color support (16 colors)
LevelAnsi256 = 2 256 color support
LevelAnsi16m = 3 Truecolor support (16 million colors)

gchalk.Stderr

gchalk.Stderr contains a separate instance configured with color support detected for stderr stream instead of stdout.

Stdout and stderr can be different in cases where the user is piping output. For example, if a user runs:

myprogram > out.txt

then stdout will not be a TTY, so by default gchalk will not emit any color, however stderr will be a TTY, so gchalk.Stderr.Red(...) will still generate colored output.

gchalk.New(options...)

Creates a new instance of gchalk. Options include:

  • gchalk.ForceLevel(level) - Force the color level. If not specified, will be autodetected from stdout.

Styles

Modifiers

  • Reset - Resets the current color chain.
  • Bold - Make text bold.
  • Dim - Emitting only a small amount of light.
  • Italic - Make text italic. (Not widely supported)
  • Underline - Make text underline. (Not widely supported)
  • Inverse- Inverse background and foreground colors.
  • Hidden - Prints the text, but makes it invisible.
  • Strikethrough - Puts a horizontal line through the center of the text. (Not widely supported)
  • Visible- Prints the text only when Chalk has a color level > 0. Can be useful for things that are purely cosmetic.

Colors

  • Black
  • Red
  • Green
  • Yellow
  • Blue
  • Magenta
  • Cyan
  • White
  • BrightBlack (alias: gray, grey)
  • BrightRed
  • BrightGreen
  • BrightYellow
  • BrightBlue
  • BrightMagenta
  • BrightCyan
  • BrightWhite

Background colors

  • BgBlack
  • BgRed
  • BgGreen
  • BgYellow
  • BgBlue
  • BgMagenta
  • BgCyan
  • BgWhite
  • BgBrightBlack (alias: BgGray, BgGrey)
  • BgBrightRed
  • BgBrightGreen
  • BgBrightYellow
  • BgBrightBlue
  • BgBrightMagenta
  • BgBrightCyan
  • BgBrightWhite

256 and Truecolor color support

GChalk supports 256 colors and Truecolor (16 million colors) on supported terminal apps, including Windows 10.

Colors are downsampled from 16 million RGB values to an ANSI color format that is supported by the terminal emulator (or by specifying {level: n} as a Chalk option). For example, GChalk configured to run at level 1 (basic color support) will downsample an RGB value of #FF0000 (red) to 91 (ANSI escape for bright-red).

Examples:

  • gchalk.WithHex('#DEADED').Underline('Hello, world!')
  • gchalk.WithRGB(15, 100, 204).Inverse('Hello!')

Background versions of these models are prefixed with Bg and the first level of the module capitalized:

  • gchalk.WithBgHex('#DEADED').Underline('Hello, world!')
  • gchalk.WithBgRgb(15, 100, 204).Unverse('Hello!')

The following color models can be used:

  • rgb - Example: gchalk.RGB(255, 136, 0)('Orange!')
  • hex - Example: gchalk.Hex('#FF8800')('Orange!')
  • ansi256 - Example: gchalk.BgAnsi256(194)('Honeydew, more or less')
  • ansi - Example: gchalk.WithAnsi(31).BgAnsi(93)('red on bright yellow')

Windows 10 Support

GChalk is cross-platform, and will work on Linux and MacOS systems, but will also work on Windows 10, and without the need for writing to a special stream or using ansicon.

Many ANSI color libraries for Go do a poor job of handling colors in Windows. This is because historically, Windows has not supported ANSI color codes, so hacks like ansicon or go-colorable were required. However, Windows 10 has supported ANSI escape codes since 2017 (build 10586 for 256 color support, and build 14931 for 16.7 million true color support). In Windows Terminal this is enabled by default, but in CMD.EXE or PowerShell, ANSI support must be enabled via ENABLE_VIRTUAL_TERMINAL_PROCESSING. GChalk, of course, takes care of all of this for you. This functionality is also availabile in the supportscolor library if you're an ANSI library author and you'd like to add this functionality to your own project.

Color Detection

Color support is automatically detected using supportscolor, and flags and command line arguments supported by supportscolor are also supported here. GChalk will automatically obey all the recommendations from Command Line Interface Guidelines. The following will disable color:

  • stdout is not a TTY. (Or, for gchalk.Stderr, stderr is not a TTY.)
  • The NO_COLOR environment variable is set.
  • The TERM variable has the value dumb.
  • The user passes the option --no-color, --no-colors, --color=false, or --color=never.
  • The FORCE_COLOR environment variable is 0.

Color support will be forcefully enabled if:

  • The FORCE_COLOR environment variable is set to 1, 2, or 3 (for 16 color, 256 color, and 16.7m color support, respectively).
  • The FORCE_COLOR environment variable is set with no value, or with true.
  • The uses passes the option --color, --colors, --color=true, or --color=always.

GChalk will also support colored output when run from popular CI environments, including Travis, CircleCI, Appveyor, GitlabCI, GitHub Actions, Buildkite, Drone, and TeamCity.

Related

Similar Resources

A go library to improve readability in terminal apps using tabular data

uitable uitable is a go library for representing data as tables for terminal applications. It provides primitives for sizing and wrapping columns to i

Dec 30, 2022

✨ #PTerm is a modern go module to beautify console output. Featuring charts, progressbars, tables, trees, and many more 🚀 It's completely configurable and 100% cross-platform compatible.

✨ #PTerm is a modern go module to beautify console output. Featuring charts, progressbars, tables, trees, and many more 🚀 It's completely configurable and 100% cross-platform compatible.

💻 PTerm | Pretty Terminal Printer A golang module to print pretty text Show Demo Code PTerm.sh | Installation | Documentation | Quick Start | Example

Dec 27, 2022

Small library for simple and convenient formatted stylized output to the console.

Small library for simple and convenient formatted stylized output to the console.

cfmt cfmt is a small library for simple and convenient formatted stylized output to the console, providing an interface that is exactly the same as th

Jan 7, 2023

Hierarchical errors reporting done right in Golang

Hierarchical errors made right Hate seeing error: exit status 128 in the output of programs without actual explanation what is going wrong? Or, maybe,

Nov 9, 2021

Flagr is an open source Go service that delivers the right experience to the right entity and monitors the impact.

Flagr is an open source Go service that delivers the right experience to the right entity and monitors the impact.

Flagr is an open source Go service that delivers the right experience to the right entity and monitors the impact. It provides feature flags, experimentation (A/B testing), and dynamic configuration. It has clear swagger REST APIs for flags management and flag evaluation.

Dec 25, 2022

Qalam - An easy to use terminal styling library

Qalam - An easy to use terminal styling library

Qalam ✏️ Qalam is a Go library for easy terminal styling. Installation go get gi

Jan 6, 2023

🎨 Terminal color rendering library, support 8/16 colors, 256 colors, RGB color rendering output, support Print/Sprintf methods, compatible with Windows.

🎨 Terminal color rendering library, support 8/16 colors, 256 colors, RGB color rendering output, support Print/Sprintf methods, compatible with Windows.

🎨 Terminal color rendering library, support 8/16 colors, 256 colors, RGB color rendering output, support Print/Sprintf methods, compatible with Windows. GO CLI 控制台颜色渲染工具库,支持16色,256色,RGB色彩渲染输出,使用类似于 Print/Sprintf,兼容并支持 Windows 环境的色彩渲染

Dec 30, 2022

A golang library for building interactive prompts with full support for windows and posix terminals.

A golang library for building interactive prompts with full support for windows and posix terminals.

Survey A library for building interactive prompts on terminals supporting ANSI escape sequences. package main import ( "fmt" "github.com/Alec

Jan 6, 2023

Inline styling for html mail in golang

go-premailer Inline styling for HTML mail in golang Document install go get github.com/vanng822/go-premailer/premailer Example import ( "fmt" "gith

Nov 30, 2022

Pi-hole data right from your terminal. Live updating view, query history extraction and more!

Pi-hole data right from your terminal. Live updating view, query history extraction and more!

Pi-CLI Pi-CLI is a command line program used to view data from a Pi-Hole instance directly in your terminal.

Dec 12, 2022

🎄 A Christmas tree right from your terminal!

🎄 A Christmas tree right from your terminal!

ctree 🎄 A Christmas tree right from your terminal! 👀 Demo ⌛ No Refresh Don't want the tree to refresh every 2 seconds? Easy! Just add the --no-refre

Dec 20, 2022

Check your internet speed right from your terminal. Built on GOlang using chromedp

Check your internet speed right from your terminal. Built on GOlang using chromedp

adhocore/fast A GO lang command line tool to check internet speed right from the terminal. Uses fast.com through headless chrome. Prerequistie Chrome

Dec 26, 2022

Get live cricket score right in your terminal.

Get live cricket score right in your terminal.

cric Get cricket score right in your terminal. How to use?! Make sure you have Node.js installed on your machine and just type the following command w

Feb 4, 2022

Painless middleware chaining for Go

Alice Alice provides a convenient way to chain your HTTP middleware functions and the app handler. In short, it transforms Middleware1(Middleware2(Mid

Dec 26, 2022

Git with a cup of tea, painless self-hosted git service

Git with a cup of tea, painless self-hosted git service

Gitea - Git with a cup of tea View the chinese version of this document Purpose The goal of this project is to make the easiest, fastest, and most pai

Jan 2, 2023

Git with a cup of tea, painless self-hosted git service

Git with a cup of tea, painless self-hosted git service

Gitea - Git with a cup of tea View the chinese version of this document Purpose The goal of this project is to make the easiest, fastest, and most pai

Jan 2, 2023

Gogs is a painless self-hosted Git service

Gogs is a painless self-hosted Git service

Gogs - A painless self-hosted Git service 简体中文 🔮 Vision The Gogs (/gɑgz/) project aims to build a simple, stable and extensible self-hosted Git servi

Jan 9, 2023

Git with a cup of tea, painless self-hosted git service

Git with a cup of tea, painless self-hosted git service

Gitea - Git with a cup of tea View the chinese version of this document Purpose The goal of this project is to make the easiest, fastest, and most pai

Jan 2, 2023
Comments
  • formatted printing

    formatted printing

    Should this work?

    fmt.Printf("colors: %-16s  %-16s %-16s\n", "default", gchalk.Yellow("yellow"), gchalk.Red("red"))
    
  • Color as type

    Color as type

    Hi,

    Is it an option to add Color as a type. Like

    type Color func(s ...string) string
    

    So it can be used like.

    package main
    
    import (
    	"fmt"
    	"github.com/jwalton/gchalk"
    )
    
    type Message struct {
    	message string
    	color gchalk.Color
    }
    
    func printMessage(m Message) {
    	fmt.Println(m.color(m.message))
    }
    
    func main() {
    	warning := Message{
    		message: "Warning",
    		color: gchalk.Yellow,
    	}
    	printMessage(warning)
    	error := Message{
    		message: "Error",
    		color: gchalk.Red,
    	}
    	printMessage(error)
    }
    

    Else the user has to add the type itself. It's just convince but I think it is beter.

    Regards, Marcel

  • NO_COLOR is not respected

    NO_COLOR is not respected

    Trying to use this as a replacement for fatih/color, but it seems that NO_COLOR is not respected.

    In the screencast below, the yellow lines are styled with gchalk, while the rest is fatih/color

    The style i'm using is roughly like this:

    styleHeading, err := gchalk.Style("yellow", "bold")
    
    var sb = strings.Builder{}
    sb.WriteString(styleHeading("some text"))
    fmt.Println(sb.String())
    

    https://user-images.githubusercontent.com/1460122/136246826-13f7d1fe-0579-47ab-976f-98224a329cd8.mp4

go-colorable - Colorable writer for windows.
go-colorable - Colorable writer for windows.

go-colorable Colorable writer for windows. For example, most of logger packages doesn't show colors on windows. (I know we can do it with ansicon. But

Dec 30, 2022
Yet Another CLi Spinner; providing over 70 easy to use and customizable terminal spinners for multiple OSes
Yet Another CLi Spinner; providing over 70 easy to use and customizable terminal spinners for multiple OSes

Yet Another CLi Spinner (for Go) Package yacspin provides yet another CLi spinner for Go, taking inspiration (and some utility code) from the https://

Dec 25, 2022
Intuitive package for prettifying terminal/console output. http://godoc.org/github.com/ttacon/chalk
Intuitive package for prettifying terminal/console output. http://godoc.org/github.com/ttacon/chalk

chalk Chalk is a go package for styling console/terminal output. Check out godoc for some example usage: http://godoc.org/github.com/ttacon/chalk The

Dec 23, 2022
An ANSI colour terminal package for Go

colourize An ANSI colour terminal package for Go. Supports all ANSI colours and emphasis. Not compatible with Windows systems. Installation go get gi

Sep 26, 2022
Console Text Colors - The non-invasive cross-platform terminal color library does not need to modify the Print method

ctc - Console Text Colors The non-invasive cross-platform terminal color library does not need to modify the Print method Virtual unix-like environmen

Nov 9, 2022
Simple tables in terminal with Go

Simple tables in terminal with Go This package allows to generate and display ascii tables in the terminal, f.e.: +----+------------------+-----------

Dec 29, 2022
Terminal based dashboard.
Terminal based dashboard.

Termdash is a cross-platform customizable terminal based dashboard. The feature set is inspired by the gizak/termui project, which in turn was inspire

Dec 28, 2022
Golang terminal dashboard
Golang terminal dashboard

termui termui is a cross-platform and fully-customizable terminal dashboard and widget library built on top of termbox-go. It is inspired by blessed-c

Dec 27, 2022
uilive is a go library for updating terminal output in realtime
uilive is a go library for updating terminal output in realtime

uilive uilive is a go library for updating terminal output in realtime. It provides a buffered io.Writer that is flushed at a timed interval. uilive p

Dec 28, 2022
A go library to render progress bars in terminal applications
A go library to render progress bars in terminal applications

uiprogress A Go library to render progress bars in terminal applications. It provides a set of flexible features with a customizable API. Progress bar

Dec 29, 2022