6

Is there another way than isatty to know if cout outputs to a terminal which accepts colors properly?

I'm using this header for colors, and I'm already using if(isatty(1)) to know if the output goes to a terminal.

Unfortunately when I output colors to Xcode's console I get unescaped sequences - but it works fine when executing the app itself from Terminal.app or iTerm in OS X.

I suppose that Xcode's console identifies itself as a terminal but still ignores color sequences...

So I'd like to have a better detection - if possible.

My code itself is trivial, something like this, returning a colored string if isatty is true, then it goes to cout:

std::string Slot::description()
{
    if(isatty(1))
    {
        return FBLU("my_string");
    }
    else
    {
        return "my_string";
    }
}

Xcode's output:

enter image description here

iTerm's output:

enter image description here

Community
  • 1
  • 1
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
  • 2
    `isatty` only identifies the output as a terminal of some kind; terminals aren't necessarily in colour. When you're running in XCode, `$TERM` is null, but the more reliable solution is probably to use `ncurses`. – molbdnilo Sep 01 '16 at 15:52
  • @molbdnilo Thanks. It's a good start: maybe I can get $TERM with getenv and then check if null - if it is, I'm in Xcode's console (or any other dumb terminal I guess). I'll try that. – Eric Aya Sep 01 '16 at 16:55
  • I did `getenv("TERM")` and got null in XCode, and the configured ones in iTerm and Terminal. – molbdnilo Sep 01 '16 at 17:00
  • 1
    @molbdnilo Yep, this works, and it answers my question. If you want to post an answer I'll happily accept it. A simple if/else checking if getenv("TERM") is empty tells me if I'm in a dumb terminal, it's perfect. – Eric Aya Sep 01 '16 at 17:06

1 Answers1

3

For XCode specifically, you can check getenv("TERM"), as that will return null inside XCode and shouldn't do that if you're running in a "real" terminal.

For a more reliable way to determine whether you have a colour terminal, ncurses is probably the way to go.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82