fatih/color

failed to display color when piped to custom pager

Opened this issue · 4 comments

Hi,
I need to invoke pager in my app to display long text. Here is the sample code:

package main

import (
	"fmt"
	"os"
	"os/exec"
	"strings"

	"github.com/fatih/color"
)

func main() {
    var Yellow = color.New(color.FgYellow).SprintfFunc()
    fmt.Println(Yellow("from fmt.Println"))

    var pager = exec.Command("less", "-F")
	pager.Stdin = strings.NewReader(Yellow("from pager"))
	pager.Stdout = os.Stdout

	err := pager.Run()
	if err != nil {
            fmt.Println(err)
	}
}

It worked on Archlinux:
image

but failed on Debian (bookworm, on rasberrypi) and latest MacOS:
image

I don't think this was caused by your package but I wonder if you have any idea how to fix it.
Thanks very much.

Did you solve this? I'm having this same issue, on ArchLinux.

@sentientmachin3 Unfortunately no. But it doesn't happen on my Archlinux. I'm using i3wm with xorg.

@sentientmachin3 @Karmenzind I had this same issue on Mac as well. If you're using less or more (which it seems like you are), run this with the -R command. That is, change var pager = exec.Command("less", "-F") to

var pager = exec.Command("less", "-RF")

From the man pages for less,

       -R or --RAW-CONTROL-CHARS
              Like -r, but only ANSI "color" escape sequences and OSC 8
              hyperlink sequences are output in "raw" form.  Unlike -r, the
              screen appearance is maintained correctly, provided that there
              are no escape sequences in the file other than these types of
              escape sequences.  Color escape sequences are only supported
              when the color is changed within one line, not across lines.  In
              other words, the beginning of each line is assumed to be normal
              (non-colored), regardless of any escape sequences in previous
              lines.  For the purpose of keeping track of screen appearance,
              these escape sequences are assumed to not move the cursor.

Found this out while looking at #157. Hope this helps! :)

Thanks a lot! I tried less -RF on Ubuntu 20 and it fixed the color. I'll do more test on other distros.
@tararoshan