Color package for Go (golang)

Overview

color PkgGoDev

Color lets you use colorized outputs in terms of ANSI Escape Codes in Go (Golang). It has support for Windows too! The API can be used in several ways, pick one that suits you.

Color

Install

go get github.com/fatih/color

Examples

Standard colors

// Print with default helper functions
color.Cyan("Prints text in cyan.")

// A newline will be appended automatically
color.Blue("Prints %s in blue.", "text")

// These are using the default foreground colors
color.Red("We have red")
color.Magenta("And many others ..")

Mix and reuse colors

// Create a new color object
c := color.New(color.FgCyan).Add(color.Underline)
c.Println("Prints cyan text with an underline.")

// Or just add them to New()
d := color.New(color.FgCyan, color.Bold)
d.Printf("This prints bold cyan %s\n", "too!.")

// Mix up foreground and background colors, create new mixes!
red := color.New(color.FgRed)

boldRed := red.Add(color.Bold)
boldRed.Println("This will print text in bold red.")

whiteBackground := red.Add(color.BgWhite)
whiteBackground.Println("Red text with white background.")

Use your own output (io.Writer)

// Use your own io.Writer output
color.New(color.FgBlue).Fprintln(myWriter, "blue color!")

blue := color.New(color.FgBlue)
blue.Fprint(writer, "This will print text in blue.")

Custom print functions (PrintFunc)

// Create a custom print function for convenience
red := color.New(color.FgRed).PrintfFunc()
red("Warning")
red("Error: %s", err)

// Mix up multiple attributes
notice := color.New(color.Bold, color.FgGreen).PrintlnFunc()
notice("Don't forget this...")

Custom fprint functions (FprintFunc)

blue := color.New(FgBlue).FprintfFunc()
blue(myWriter, "important notice: %s", stars)

// Mix up with multiple attributes
success := color.New(color.Bold, color.FgGreen).FprintlnFunc()
success(myWriter, "Don't forget this...")

Insert into noncolor strings (SprintFunc)

// Create SprintXxx functions to mix strings with other non-colorized strings:
yellow := color.New(color.FgYellow).SprintFunc()
red := color.New(color.FgRed).SprintFunc()
fmt.Printf("This is a %s and this is %s.\n", yellow("warning"), red("error"))

info := color.New(color.FgWhite, color.BgGreen).SprintFunc()
fmt.Printf("This %s rocks!\n", info("package"))

// Use helper functions
fmt.Println("This", color.RedString("warning"), "should be not neglected.")
fmt.Printf("%v %v\n", color.GreenString("Info:"), "an important message.")

// Windows supported too! Just don't forget to change the output to color.Output
fmt.Fprintf(color.Output, "Windows support: %s", color.GreenString("PASS"))

Plug into existing code

// Use handy standard colors
color.Set(color.FgYellow)

fmt.Println("Existing text will now be in yellow")
fmt.Printf("This one %s\n", "too")

color.Unset() // Don't forget to unset

// You can mix up parameters
color.Set(color.FgMagenta, color.Bold)
defer color.Unset() // Use it in your function

fmt.Println("All text will now be bold magenta.")

Disable/Enable color

There might be a case where you want to explicitly disable/enable color output. the go-isatty package will automatically disable color output for non-tty output streams (for example if the output were piped directly to less)

Color has support to disable/enable colors both globally and for single color definitions. For example suppose you have a CLI app and a --no-color bool flag. You can easily disable the color output with:

var flagNoColor = flag.Bool("no-color", false, "Disable color output")

if *flagNoColor {
	color.NoColor = true // disables colorized output
}

It also has support for single color definitions (local). You can disable/enable color output on the fly:

c := color.New(color.FgCyan)
c.Println("Prints cyan text")

c.DisableColor()
c.Println("This is printed without any color")

c.EnableColor()
c.Println("This prints again cyan...")

GitHub Actions

To output color in GitHub Actions (or other CI systems that support ANSI colors), make sure to set color.NoColor = false so that it bypasses the check for non-tty output streams.

Todo

  • Save/Return previous values
  • Evaluate fmt.Formatter interface

Credits

License

The MIT License (MIT) - see LICENSE.md for more details

Comments
  • it does't working on window7(64bit)

    it does't working on window7(64bit)

    I get wrong when run pure-go on windows.

    package main

    import("github.com/fatih/color")

    func main() { color.Red("we are red") }

    1: window7 64bit 2: git bash

    output: image

    opened by liyu4 28
  • feature request: Add Color merge functionality

    feature request: Add Color merge functionality

    I have two color objects that I'd like to "merge" together. A quick example would be:

    func foo(a color.Color, b color.Color) {
    	a.Merge(b).Println("hello world")
    }
    
    func main() {
    	color1 := color.New(color.BgRed)
    	color2 := color.New(color.FgGreen)
    
    	modifier1 := color.New(color.Underline)
    	modifier2 := color.New(color.Bold)
    
    	foo(color1, modifier1)
    	foo(color1, modifier2)
    	foo(color2, modifier1)
    	foo(color2, modifier2)
    }
    

    This could follow the same semantics as Color.Add in terms of overwriting non-compatible attributes.

    Alternatively, exposing the current attributes of a color object would allow me to do a.Add(b.Attributes...) to achieve the same effect.

    If this seems reasonable I can submit a PR

    opened by apexskier 9
  • Latest version linking to go-colorable/go-isatty failing in Windows 10

    Latest version linking to go-colorable/go-isatty failing in Windows 10

    Windows 10 usage of color that utilizes go-colorable/go-isatty is failing in Windows 10.

    fmt.Print(color.RedString("This is a test of Color"))

    color-fail

    opened by pathaugen 9
  • Not working in Git Bash on Windows

    Not working in Git Bash on Windows

    I am using Git Bash and wanted to color the output of my program, but I'm getting this: ?[36mMSathieu C:\Users\MSathieu\go\src\github.com\MSathieu\Gosh $?[0m.

    opened by msathieu 8
  • Add Hi* helpers for hi-intensity colors

    Add Hi* helpers for hi-intensity colors

    Hi,

    I added Hi*() helpers (like HiRed()) for hi-intensity colors as well as normal colors.

    I added them because only 8 of 16 colors have helpers. I feel hi-intensity colors are as popular as normal colors and used in many places. At least, I wanted to use hi-black for making a text not stand out, and hi-white for making a text be noticeable.

    opened by rhysd 7
  • Is not available as a dependency: IsCygwinTerminal

    Is not available as a dependency: IsCygwinTerminal

    Hello.

    I'm trying to use color library v1.4.0 as a dependency via dep tool. It resolves dependencies well, but there is an issue with go-isatty dependency.

    undefined: isatty.IsCygwinTerminal
    

    As I understand, isatty is released with a tag which does not have the latest changes. https://github.com/mattn/go-isatty/tree/v0.0.1

    opened by NicolasSiver 7
  • Please use semantic versioning

    Please use semantic versioning

    Please use semantic versioning:

    • http://semver.org/
    • https://en.wikipedia.org/wiki/Software_versioning
    • https://wiki.debian.org/UpstreamGuide#Releases_and_Versions
    opened by petercolberg 7
  • Update vendor

    Update vendor

    We are facing an issue while using this package while golang.org/x/sys/unix is pinned to a really old version.

    # go build
    # [hidden]/vendor/golang.org/x/crypto/ssh/terminal
    vendor/golang.org/x/crypto/ssh/terminal/util.go:30: undefined: unix.IoctlGetTermios
    vendor/golang.org/x/crypto/ssh/terminal/util.go:38: undefined: unix.IoctlGetTermios
    vendor/golang.org/x/crypto/ssh/terminal/util.go:54: undefined: unix.IoctlSetTermios
    vendor/golang.org/x/crypto/ssh/terminal/util.go:64: undefined: unix.IoctlGetTermios
    vendor/golang.org/x/crypto/ssh/terminal/util.go:75: undefined: unix.IoctlSetTermios
    vendor/golang.org/x/crypto/ssh/terminal/util.go:80: undefined: unix.IoctlGetWinsize
    vendor/golang.org/x/crypto/ssh/terminal/util.go:98: undefined: unix.IoctlGetTermios
    vendor/golang.org/x/crypto/ssh/terminal/util.go:107: undefined: unix.IoctlSetTermios
    vendor/golang.org/x/crypto/ssh/terminal/util.go:112: undefined: unix.IoctlSetTermios
    

    So we've pinned the package golang.org/x/sys/unix to latest version and our project builds. The reason for this issue is that your version to old to provide the needed methods and glide resolves the versions listed in the manifests of packages.

    Maybe you need to check if it is possible to update your manifest to newer versions of your packages.

    opened by joconcepts 6
  • Use color cache map

    Use color cache map

    printColor and printString create new Color object on every call. If user calls these functions more than one time, Color objects with the same Attribute are created. That consumes memory. I offer to cache already created objects and reuse them.

    And this is strange, what these two functions are between print and string functions, so I place them in a top of these functions.

    opened by bogem 6
  • Suggest using method value instead of Print*Func

    Suggest using method value instead of Print*Func

    The Print*Func methods can be replaced with a method value in most cases. Method values are supported since Go 1.1:

    https://golang.org/doc/go1.1#method_values

    opened by mgeisler 6
  • Simplify Print*Func methods

    Simplify Print*Func methods

    The methods can simply return a method value instead of making a closure. This is supported since Go 1.1:

    https://golang.org/doc/go1.1#method_values

    The methods now return (int, error) to match the underlying Print* methods. This should be backwards compatible since old code will ignore the new return values.

    opened by mgeisler 6
  • Bump github.com/mattn/go-isatty from 0.0.16 to 0.0.17

    Bump github.com/mattn/go-isatty from 0.0.16 to 0.0.17

    Bumps github.com/mattn/go-isatty from 0.0.16 to 0.0.17.

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    dependencies 
    opened by dependabot[bot] 0
  • [bug] yellow color does not take effect in powershell

    [bug] yellow color does not take effect in powershell

    Env: OS: windows 10 go: 1.17.2 bash: powershell

    Demonstration effect picture: https://gitee.com/fanybook/thirdparty-bugs/blob/master/github.com/fatih/color/yellow_powershell_bug_20221227140205.png

    opened by fanybook 0
  • [bug] color.Output  has indent error when using tabwriter.Writer

    [bug] color.Output has indent error when using tabwriter.Writer

    Env: OS: windows 10 go: 1.17.2 bash: cmd powershell gitbash

    package main
    
    import (
        "fmt"
        "github.com/fatih/color"
        "io"
        "text/tabwriter"
    )
    
    func main() {
        tabOut := getTabOutWithWriter(color.Output)
        fmt.Fprint(tabOut, "\x1b[0;32m  demo\t\tStart the server\n\x1b[0m")
        fmt.Fprint(tabOut, "\x1b[0;32m  help\t\tHelp about any command\n\x1b[0m")
        fmt.Fprint(tabOut, "\x1b[0;32m  server:start\t\tStart the server\n\x1b[0m")
        tabOut.Flush()
    }
    
    func getTabOutWithWriter(writer io.Writer) *tabwriter.Writer {
        aTabOut := new(tabwriter.Writer)
        aTabOut.Init(writer, 0, 8, 1, '\t', 0)
        return aTabOut
    }
    

    Output:

      demo                          Start the server
      help                  Help about any command
      server:start          Start the server
    
    opened by fanybook 0
  • `NO_COLOR` and empty string value

    `NO_COLOR` and empty string value

    The https://no-color.org/ requires handling empty value in way as if the value was not set.

    should check for a NO_COLOR environment variable that, when present and not an empty string (regardless of its value), prevents the addition of ANSI color

    I find it a lot better for several reasons.

    The problem is that not all languages/OSes/shells are handling an empty value in the same way.

    In .NET (C# etc) setting an empty value unsets the environmental variable (sic!). See: https://docs.microsoft.com/en-us/dotnet/api/system.environment.setenvironmentvariable?view=net-5.0

    On Windows setting an empty env var is VERY tricky. I suspect 95% of Windows IT users may have real problems doing it. You cannot do it in the command prompt. not via PowerShell, not via GUI. It is possible via Windows Registry or WinAPI, but it is VERY inconvenient and hacky.

    Also from a pure usability point of view, echo $SOMEVAR does not allow to distinguish between empty and unset.

    Having a different interpretation of an empty and unset environment variable can be seen as a kind of "billion-dollar mistake" 😉

    Reference: https://unix.stackexchange.com/questions/27708/is-there-a-difference-between-setting-an-environment-variable-to-the-empty-strin

    At last, many software see empty env vars as though as it they are not set e.g. https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/sdk-environment-variables.md#parsing-empty-value

    opened by pellared 0
  • NO_COLOR requires a non-empty string

    NO_COLOR requires a non-empty string

    Fixes https://github.com/fatih/color/issues/172

    1. Change the handling of NO_COLOR so that the empty string value as equivalent to being unset
    2. Some opportunistic fixes
    opened by pellared 0
  • Colors not working in Powershell env

    Colors not working in Powershell env

    Using the Cluster API CLI clusterctl prints the output with color on linux and mac environments, but the same does not work for Windows PowerShell and cmd. The output includes the Raw ANSI codes instead making it unreadable. The current workaround is to set the NO_COLOR env variable to turn off color completely, resulting in a readable, but colorless output.

    Is there a way to configure the library to get the correctly colored output on Windows environments?

    Related issue: https://github.com/kubernetes-sigs/cluster-api/issues/7381

    opened by killianmuldoon 4
Releases(v1.13.0)
Owner
Fatih Arslan
Software Engineer. Gopher and Coffee geek. Creator of vim-go. Tool maker.
Fatih Arslan
Color package for Go (golang)

color Color lets you use colorized outputs in terms of ANSI Escape Codes in Go (Golang). It has support for Windows too! The API can be used in severa

Fatih Arslan 5.9k Dec 31, 2022
Color quantization experiment for golang

bitcrush Color quantization experiment, version 4 Build git clone https://github

Sapphire Cat 0 Jun 15, 2022
A simple logging interface that supports cross-platform color and concurrency.

WLog Package wlog creates simple to use UI structure. The UI is used to simply print to the screen. There a wrappers that will wrap each other to crea

Will Dixon 59 Sep 26, 2022
Draw images in your ANSI terminal with true color

___ _____ ____ / _ \/ _/ |/_/ /____ ______ _ Made with love by Eliuk Blau / ___// /_> </ __/ -_) __/ ' \ https://github.com/eliukblau/pix

Eliuk Blau 898 Dec 14, 2022
Advanced ANSI style & color support for your terminal applications

termenv lets you safely use advanced styling options on the terminal. It gathers information about the terminal environment in terms of its ANSI & col

Christian Muehlhaeuser 1.3k Dec 31, 2022
A Go library for terminal background color detection

go-termbg A Go library for terminal background color detection. The detected color is provided by RGB or theme ( dark or light ). Based on https://git

Anders Björklund 1 Jan 4, 2022
Go (golang) package with 70+ configurable terminal spinner/progress indicators.

Spinner spinner is a simple package to add a spinner / progress indicator to any terminal application. Examples can be found below as well as full exa

Brian Downs 1.9k Dec 26, 2022
Got: Simple golang package and CLI tool to download large files faster 🏃 than cURL and Wget!

Got. Simple and fast concurrent downloader. Installation ❘ CLI Usage ❘ Module Usage ❘ License Comparison Comparison in cloud server: [root@centos-nyc-

Mohamed El Bahja 620 Dec 29, 2022
Golang package with functionality to add colors to your logs to the terminal.

colrz It's a set of funcs and constants to provide basic colors to your terminal app. How to use Get it go get github.com/unnamedxaer/colrz Use it pac

Kamil 0 Sep 15, 2022
Go / Golang package for picking random items from a list

Go / Golang package for picking random items from a list

Mitch Allen 0 Jan 16, 2022
CLI - A package for building command line app with go

Command line interface Screenshot Key features Lightweight and easy to use. Defines flag by tag, e.g. flag name(short or/and long), description, defau

王仕晋 678 Dec 23, 2022
The standard library flag package with its missing features

cmd Package cmd is a minimalistic library that enables easy sub commands with the standard flag library. This library extends the standard library fla

Eyal Posener 35 Oct 4, 2022
Idiomatic Go input parsing with subcommands, positional values, and flags at any position. No required project or package layout and no external dependencies.

Sensible and fast command-line flag parsing with excellent support for subcommands and positional values. Flags can be at any position. Flaggy has no

Eric Greer 815 Jan 1, 2023
A collection of CLI argument types for the Go `flag` package.

flagvar A collection of CLI argument types for the flag package. import "github.com/sgreben/flagvar" Or just copy & paste what you need. It's public d

Sergey Grebenshchikov 41 Sep 26, 2022
Drop-in replacement for Go's flag package, implementing POSIX/GNU-style --flags.

Description pflag is a drop-in replacement for Go's flag package, implementing POSIX/GNU-style --flags. pflag is compatible with the GNU extensions to

Steve Francia 2k Dec 30, 2022
Package for creating interpreters

sand sand is for creating interpreters, like the Python interpreter and Haskell interpreter. It can also be used for creating text based games and CLI

null 19 Sep 26, 2022
A simple, fast, and fun package for building command line apps in Go

cli cli is a simple, fast, and fun package for building command line apps in Go. The goal is to enable developers to write fast and distributable comm

null 19.5k Dec 31, 2022
Go package to make lightweight ASCII line graph ╭┈╯ in command line apps with no other dependencies.

asciigraph Go package to make lightweight ASCII line graphs ╭┈╯. Installation go get github.com/guptarohit/asciigraph Usage Basic graph package main

Rohit Gupta 2.1k Jan 8, 2023
Fonts is a package that provides helpers to access font details and easily retrive font bytes with ZERO dependencies

Fonts Fonts is a package that provides helpers to access font details and easily retrieve font bytes. This package has ZERO 3rd-party dependencies. Fo

Go Swiss 10 Mar 3, 2022