fatih / color

Color package for Go (golang)
https://pkg.go.dev/github.com/fatih/color
MIT License
7.3k stars 615 forks source link

Broken escape codes on Windows 10 using cmd.exe #154

Closed Integralist closed 2 years ago

Integralist commented 2 years ago

👋🏻

I'm testing the following code:

package main

import (
    "fmt"
    "os"

    "github.com/fatih/color"
)

var Bold = color.New(color.Bold).SprintFunc()

func main() {
    s := fmt.Sprintf("Name: [%s] ", "default name")
    fmt.Fprint(os.Stdout, Bold(s))
}

On macOS the output is correctly bolded (as expected), while the output on Windows 10 cmd.exe displays:

←[1mName: [default name] ←[0m

I've noticed old issues like https://github.com/fatih/color/issues/91 where it mentions certain functions aren't supported by cmd.exe and so I'm not sure if there's a similar resolution here?

Any feedback/guidance appreciated.

Thanks.

fatih commented 2 years ago

Hi @Integralist

If you use color.Output, it should work for both macOS and Windows:

fmt.Fprint(color.Output, Bold(s))

This makes sure to use the correct parser. You can also use the handy Printxxx methods of the color instance you created, which use the correct stdout under the hood:

Bold.Print(s)
Integralist commented 2 years ago

Thanks I'll take a look at this 👍🏻

Integralist commented 2 years ago

@fatih Thanks for the feedback, this appears to work but I'm just noting for future travellers that I was initially still seeing an issue with escape codes being displayed rather than rendered.

For example, using your suggestion...

fmt.Fprint(color.Output, Bold(s))

This printed fine on macOS but on Windows, although the text was 'bolded' I was seeing it prefixed with ←[0m...

Screenshot 2022-01-06 at 09 54 09

Turns out this was because before that line I still had...

fmt.Fprint(os.Stdout, Bold(s))

And so I'm guessing that was not closing off the ANSI escape code properly. So doing the following would make Windows render correctly...

fmt.Fprint(os.Stdout, Bold(s))
fmt.Println("---")
fmt.Fprintf(color.Output, bold(s))
Screenshot 2022-01-06 at 10 24 49
Integralist commented 2 years ago

Oh! and for anyone using os.Stderr, the equivalent to use is color.Error.

Hipska commented 2 years ago

@fatih sorry to hijack this issue, but quick question, should this be working on Windows?