Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

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

Open
fanybook opened this issue Dec 26, 2022 · 3 comments
Open

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

fanybook opened this issue Dec 26, 2022 · 3 comments

Comments

@fanybook
Copy link

fanybook commented Dec 26, 2022

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
@montanaflynn
Copy link

montanaflynn commented Feb 5, 2023

Just ran into the same thing, did you end up solving it?

I tried both color.RedString and color.New(color.FgRed).SprintFunc() with no luck...

Before using color:

Screenshot 2023-02-05 at 9 01 19 PM

After:

Screenshot 2023-02-05 at 9 00 42 PM

Edit: I think this is actually a text/tabwriter problem because the same issue when just using color codes directly:

		colorReset := "\033[0m"
		colorRed := "\033[31m"
		colorGreen := "\033[32m"
		colorYellow := "\033[33m"

@rmsrob
Copy link

rmsrob commented Jun 17, 2023

for me this fix works

w.Init(os.Stdout, 0, 8, 4, ' ', 0)

@FollowTheProcess
Copy link

FollowTheProcess commented Aug 3, 2024

It's an issue with tabwriter because the escape sequences aren't always the same length, they get used as part of the cell width calculations so some cells appear wider than they are really and don't render correctly

See https://stackoverflow.com/questions/35398497/how-do-i-get-colors-to-work-with-golang-tabwriter

color could pad the escape sequences to ensure they are all the same length as per the answer in the SO thread above but I suspect it's much trickier and more nuanced than that in practice and there will be a bunch of edge cases that need to be handled

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants