GithubHelp home page GithubHelp logo

fatih / color Goto Github PK

View Code? Open in Web Editor NEW
7.2K 7.2K 609.0 2.02 MB

Color package for Go (golang)

Home Page: https://pkg.go.dev/github.com/fatih/color

License: MIT License

Go 100.00%
ansi color coloring go golang

color's People

Contributors

andrewaustin avatar andrii-rubtsov avatar bl-ue avatar cenkalti avatar dependabot[bot] avatar dmitris avatar drkhyz avatar edwardbetts avatar fatih avatar gregpoirson avatar hackebrot avatar hermanschaaf avatar hyunsooda avatar ilyabrin avatar jeffwillette avatar klauspost avatar martinlindhe avatar mattn avatar moorereason avatar morfu avatar msabramo avatar n10v avatar pattmax00 avatar pellared avatar rhysd avatar robnagler avatar sinan avatar tliron avatar tonkpils avatar zddhub avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

color's Issues

Does this package work good for windows 10 command propmpt?

quick shout out to you for this amazing package this truly makes my cli tools look very colorful and amazing. Sadly there is a 'But', I tried using the compiled and executable binary of the go build and there some weird I am guessing unencoded symbols surrounding the words of text that is supposed to be colored.

EX:

�[31merror cache:�[0m run `cache --help` command to see how to use cache and what commands to use.

If you could help understand that or maybe find a way to fix it that would be coolio

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

Optionally force colour output

Would it be possible to force colour output without a terminal i.e. in a pipe? This would allow grep-ing for errors while maintaining useful colourised output.

This would provide the opposite functionality to https://github.com/fatih/color#disable-color - perhaps usage could look similar

var flagForceColor = flag.Bool("force-color", false, "Force color output")

if *flagForceColor {
	color.ForceColor = true // forces colorized output, even without a terminal attached
}

As a data point, grep also implements this with a flag:

$ grep --help | grep color -A 2
  --color[=WHEN],
  --colour[=WHEN]       use markers to highlight the matching strings;
                        WHEN is 'always', 'never', or 'auto'

This feature request is spawned from a dependent project https://github.com/wercker/stern/issues/33#issuecomment-289045171

${Color}String tries to interpret percent signs

If you do:

fmt.Println(color.RedString("%"))

This is printed (in red):

%!(NOVERB)

This should be printed (in red):

%

The wrong output is displayed even when color.NoColor is set to true.

Add styling support?

Hi

I know with a name like "color" almost anything else is out of scope but I was wondering if you would consider adding support for "bold", "faint", "Italic", and "Underline".

Or perhaps they can fit in into an standalone package?

Background colors not clearing properly after newline

Background color don't properly clear if using Println or Printf

func TestLineClear(t *testing.T) {
	New(BgWhite).Printf("Printf - Solid white\n")
	fmt.Println("Line should be normal")
	fmt.Println()

	New(BgWhite).Println("Println - Solid white")
	fmt.Println("Line should be normal")
	fmt.Println()

	New(BgWhite).Print("Print - Solid white\n")
	fmt.Println("Line should be normal")
}

screen shot 2017-02-13 at 2 09 29 pm

Return objects implementing Fmt.Formatter.

Right now, if we are going to use Sprint, Sprintf, Sprintln outputs and
perform further formatting on the returned string as:

    fmt.Printf("%-10s", color.New(color.FgYellow).Sprint("hello"))

it may not give the correct padding.

To handle such cases, implement a set of functions that can return
formattable objects outside color/ package.

To begin with, I might propose the following:

Implement a set of functions similar to Sprint, Sprintf, Sprintln.
And another set of functions similar to SprintFunc, SprintfFunc SprintlnFunc
that returns an object implementing fmt.Formatter{} interface.

If it make sense, I can do a draft implementation and raise a pull request.

Thanks,

color does not work with ./...

I ran into this while upgrading some tests to check for colorized output. Tests worked fine in the package, but go test ./... fails. You can reproduce this easily in this repo.

tests pass
go test

tests fail
go test ./...

Attribute "Faint" is not faint on Windows (cmd.exe)

Hello. I've tried using the Faint attribute for normally coloured console output. On Linux it works as expected: text is greyer and harder to read. On windows surprisingly the opposite is true: FgWhite is greyer and harder to read than Faint is.

I'm not sure if I should report that issue here, or on mattn's go-colorable.

colorString() not working on Windows cmd.exe

Hi @fatih

Thanks a lot for your color package.
It works great on Linux, but there's a problem under Windows.

package main

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

func main() {

	color.Red("1. We have red")

	fmt.Println(color.RedString("2. We have red"))
}

The first line is printed in red, but not the second one:

fatih_color_error

I'm using the default shell (c:\Windows\system32\cmd.exe) on Windows 7.

Nesting colors does not work

Scenario

I'm using the color._String functions to color sub parts of a string that have already been colored.

package main                                                                                                                                                                                     
                                                                                                                                                                                                 
import (                                                                                                                                                                                         
    "fmt"                                                                                                                                                                                        
                                                                                                                                                                                                 
    "github.com/fatih/color"                                                                                                                                                                     
)                                                                                                                                                                                                
                                                                                                                                                                                                 
func main() {                                                                                                                                                                                    
    fmt.Println(color.CyanString("1" + color.RedString("2") + "3"))                                                                                                                           
}

Got

screen shot 2017-11-27 at 8 20 33 pm

Want

screen shot 2017-11-27 at 8 21 33 pm

Code

It looks like the existing behavior is probably intentional, because this piece of code clearly shows the wrap function unformating the color. I'm not sure if it would be feasible to support this scenario or even if it was if that'd be outside the intended scope of this package, so I'm not assuming this should change, but wanted to open a discussion about it. I'd be up for taking a stab at it if the consensus is this would be welcomed. Some similar packages in other languages do allow nesting of colors. e.g. https://github.com/junegunn/ansi256#nesting

color/color.go

Lines 357 to 363 in 5df930a

func (c *Color) wrap(s string) string {
if c.isNoColorSet() {
return s
}
return c.format() + s + c.unformat()
}

color/color.go

Lines 365 to 367 in 5df930a

func (c *Color) format() string {
return fmt.Sprintf("%s[%sm", escape, c.sequence())
}

color/color.go

Lines 369 to 371 in 5df930a

func (c *Color) unformat() string {
return fmt.Sprintf("%s[%dm", escape, Reset)
}

Properly decide when to disable colors

#51 and #50 are an improper method of determining whether a terminal supports color. There are many dumb terms that support color, and there are non-dumb terminals that don't support color.

I currently use a dumb terminal as my main terminal, and all apps built with faith/color don't show color, but all other applications I use seem to work fine.

The proper way to do this is to use the terminfo database, for a simple example:

tput colors shows how many colors this terminal supports.

Simple workaround to avoid loosing colors:

	if os.Getenv("TERM") == "dumb" && isatty.IsTerminal(os.Stdout.Fd()) {
		color.NoColor = false
	}

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.

Request: Add uncolorize() function.

Once a color is set to a string there is no way to undo that. It is required while writing to file. So something like this would be great.

func (c *Color) Uncolorize(str string) string {
// if str is colorized uncolorize it and return
}

Anyway to print without it always being on a new line?

It looks like the source code uses fmt.Println for everything, but what if I want things to be on the same line just in a different print statement. For example, if I wanted to use two colors on the same line.

How would I do this? Or do I have to edit the source file?

Thanks!

Race condition

I faced race condition. I think fixing this may solve:

// Set sets the SGR sequence.
func (c *Color) Set() *Color {
    c.Lock()
    if c.isNoColorSet() {
        return c
    }

    fmt.Fprintf(Output, c.format())
    return c
}

func (c *Color) unset() {
    if c.isNoColorSet() {
        return
    }

    Unset()
    c.Unlock()
}

Doesn't seem to work with go test output

I tried using this within a go test function and was not able to get the color in the terminal. It works within a regular main() function.

func Test_Color(t *testing.T) {
	color.Set(color.FgWhite, color.Bold)
	color.Cyan("Prints text in cyan.")
	fmt.Println("This is white in color")
}

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.

Respect $TERM

It would be wonderful if you could turn off color like @mjibson did in cortesi/termlog#3. I don't develop with go, but it seems like his change is a good compromise to respect $TERM without breaking backwards compatibility:

var NoColor = !isatty.IsTerminal(os.Stdout.Fd()) || os.Getenv("TERM") == "dumb"

Anybody who sets TERM=dumb is actively trying to communicate with programs that the output is not a terminal which seems in line with the IsTerminal() test.

Please tell others about how to respect $TERM, thanks!

Using color with multiwrater

Hello Fatih!
i am using code like this
`
code:

mw := io.MultiWriter(os.Stdout, file)
Trace = log.New(file,
	"TRACE: ",
	log.Ldate|log.Ltime|log.Lshortfile)

Trace.SetOutput(mw)

`
Am I able use your module in my code ?

Versioning policy

We have been using the library in https://github.com/michaelsauter/crane for a while, but a recent change you made (namely making color.Set() private) broke our build which does not use any vendoring mechanism. We worked around that with michaelsauter/crane#187, but I am concerned about potential breaking changes in the future. Do you have any policy regarding backward-compatibility?

Thanks for your work!

backspace character not working

Backspace character is not clearing previously output characters.

See screenshot:

screen shot 2017-03-06 at 10 13 10 am

I'm running zsh on OSX.

Here's the program to repro:

package main

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

func main() {
	fmt.Println("with fmt:")
	fmt.Print("Hello...")
	fmt.Println("\b\b\b, World!\n")

	fmt.Println("with color:")
	color.Cyan("Hello...")
	color.Cyan("\b\b\b, World!\n")
}

Suggestion: in string color assignments

Have a function that will read the string and it changes the color whenever inside the string there is a $ and one color. I already did this (pretty crappy and slow) but you can improve on this idea:

var awaitingColor bool
colorPrint := color.New(color.FgWhite)
for _, character := range sError {
	if awaitingColor {
		switch character {
		case 'w':
			colorPrint = color.New(color.FgWhite)
			break
		case 'r':
			colorPrint = color.New(color.FgRed)
			break
		case 'y':
			colorPrint = color.New(color.FgYellow)
			break
		case 'b':
			colorPrint = color.New(color.FgBlue)
		        break
		}
		awaitingColor = false
	} else if character == '$' {
		awaitingColor = true
	} else {
		colorPrint.Print(string(character))
	}
}

Add support for 256-color and truecolor escape codes

I'd like to use 256 color or even truecolor escape codes to create nicer-looking CLI tools, but this library only seems to support the 16 traditional ANSI colors. As terminal support for truecolor is quite good by now (including on Windows 10, in my testing), it would be useful to see support for those escape codes.

Force color

Like the color.NoColor flag it would be good to have a global flag to force color output.

use case: Currently if I pipe the output to less the color is automatically disabled because it is not detected as a tty. I would like to do something like myApp --color | less -r

Module not working for go > 1.6

I have opened the issue here
golang/go#18277

It seems like for Go v > 1.6 when i install your module by go get github.com/fatih/color it later cannot be imported in file. For Go version 1.5 it works as expected

PrintlnFunc is not compatible to fmt.Println

What do you think about PrintlnFunc returning a func compatible to fmt.Println regarding to the return params?

Something like this:

// PrintlnFunc returns a new function that prints the passed arguments as
// colorized with color.Println().
func (c *Color) PrintlnFunc() func(a ...interface{}) (int, error) {
	return func(a ...interface{}) (int, error) {
		return c.Println(a...)
	}
}```

Propose Logo

Hi @fatih . I'm a graphic designer. I wanted to contribute to your project for free, i'm waiting your feedback. Thanks .. Best Regard. Mirza Zulfan.

This package isn't working in OS X 10.11

I checked the terminal settings. ANSI colors are enabled, and other terminal utilities (bower specifically) seem to be outputting colors correctly. I've tested with SprintFunc and color.Cyan(). Nothing seems to be outputting color.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.