All Projects → jwalton → Gchalk

jwalton / Gchalk

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

Programming Languages

go
31211 projects - #10 most used programming language
golang
3204 projects

Labels

Projects that are alternatives of or similar to Gchalk

Progress.c
Progress display lib for c
Stars: ✭ 67 (-60.12%)
Mutual labels:  ansi
Monolog Colored Line Formatter
Colored/ANSI Line Formatter for Monolog
Stars: ✭ 108 (-35.71%)
Mutual labels:  ansi
Ololog
A better console.log for the log-driven debugging junkies
Stars: ✭ 141 (-16.07%)
Mutual labels:  ansi
Antsy Alien Attack
A game, written in Bash, that is a somewhat retro-a-like shoot 'em up. Hopefully.
Stars: ✭ 86 (-48.81%)
Mutual labels:  ansi
Blockzone
A faithful recreation of the original DOS font.
Stars: ✭ 100 (-40.48%)
Mutual labels:  ansi
Tendo
Official repository of python tendo library, always welcoming new contributions.
Stars: ✭ 113 (-32.74%)
Mutual labels:  ansi
Genann
simple neural network library in ANSI C
Stars: ✭ 1,088 (+547.62%)
Mutual labels:  ansi
Reflow
A collection of (ANSI-sequence aware) text reflow operations & algorithms
Stars: ✭ 172 (+2.38%)
Mutual labels:  ansi
Pansies
Powershell ANSI Escape Sequences, functions for colored output, etc.
Stars: ✭ 101 (-39.88%)
Mutual labels:  ansi
Ansiweather
Weather in terminal, with ANSI colors and Unicode symbols
Stars: ✭ 1,663 (+889.88%)
Mutual labels:  ansi
Gvcci
color extraction to turn images into 16 color palettes
Stars: ✭ 86 (-48.81%)
Mutual labels:  ansi
Retrotxt
RetroTxt is the WebExtension that turns ANSI, ASCII, NFO text into in-browser HTML
Stars: ✭ 93 (-44.64%)
Mutual labels:  ansi
Sdefl
Small inflate/deflate implementation in ~300 LoC of ANSI C
Stars: ✭ 120 (-28.57%)
Mutual labels:  ansi
Ansi Econsole
Eclipse plugin that understands ANSI escape sequences to color the Eclipse console output.
Stars: ✭ 72 (-57.14%)
Mutual labels:  ansi
Ascension
ANSI/ASCII art viewer for Mac OS X
Stars: ✭ 143 (-14.88%)
Mutual labels:  ansi
Asciichart
Nice-looking lightweight console ASCII line charts ╭┈╯ for NodeJS, browsers and terminal, no dependencies
Stars: ✭ 1,107 (+558.93%)
Mutual labels:  ansi
Strings
A set of useful functions for transforming strings.
Stars: ✭ 111 (-33.93%)
Mutual labels:  ansi
Ansilove
ANSI and ASCII art to PNG converter in C
Stars: ✭ 207 (+23.21%)
Mutual labels:  ansi
Tinn
A tiny neural network library
Stars: ✭ 1,944 (+1057.14%)
Mutual labels:  ansi
Terminal Canvas
Manipulate the cursor in your terminal via high-performant, low-level, canvas-like API
Stars: ✭ 125 (-25.6%)
Mutual labels:  ansi

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 70ns 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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].