Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine if a terminal is color-capable?

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.

like image 668
asjo Avatar asked Mar 17 '10 19:03

asjo


People also ask

What is the Colour of the terminal?

Terminals traditionally take an input of bytes and display them as white text on a black background.

How do I change the color of text in terminal?

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.

How many colors are in terminal?

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.


1 Answers

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.

like image 115
asjo Avatar answered Sep 20 '22 05:09

asjo