I would like to change a program to automatically detect whether a terminal is color-capable or not, so when I run said program from within a non-color capable terminal (say M-x shell in (X)Emacs), color is automatically turned off.
I don't want to hardcode the program to detect TERM={emacs,dumb}.
I am thinking that termcap/terminfo should be able to help with this, but so far I've only managed to cobble together this (n)curses-using snippet of code, which fails badly when it can't find the terminal:
#include <stdlib.h> #include <curses.h> int main(void) { int colors=0; initscr(); start_color(); colors=has_colors() ? 1 : 0; endwin(); printf(colors ? "YES\n" : "NO\n"); exit(0); }
I.e. I get this:
$ gcc -Wall -lncurses -o hep hep.c $ echo $TERM xterm $ ./hep YES $ export TERM=dumb $ ./hep NO $ export TERM=emacs $ ./hep Error opening terminal: emacs. $
which is... suboptimal.
Terminals traditionally take an input of bytes and display them as white text on a black background.
Open any new terminal and open Preferences dialog box by selecting Edit and Preferences menu item. Click on the Colors tab of the Preferences dialog box. There is an option for text and background color and that is “Use color from system theme”. This option is enabled by default.
Modern terminal emulators, including the Linux console itself, allows you to specify the precise RGB values that the colors translate to. This mode is supported by almost all terminal emulators. With the advent of 256-color displays came the 256-color escape.
A friend pointed me towards tput(1), and I cooked up this solution:
#!/bin/sh # ack-wrapper - use tput to try and detect whether the terminal is # color-capable, and call ack-grep accordingly. OPTION='--nocolor' COLORS=$(tput colors 2> /dev/null) if [ $? = 0 ] && [ $COLORS -gt 2 ]; then OPTION='' fi exec ack-grep $OPTION "$@"
which works for me. It would be great if I had a way to integrate it into ack, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With