如何确定terminal是否具有色彩function?

我想改变一个程序来自动检测一个terminal是否有颜色能力,所以当我从一个非彩色terminal(例如(X)Emacs中的Mx shell)运行所述程序时,颜色会自动closures。

我不想硬编码程序来检测TERM = {emacs,dumb}。

我在想,termcap / terminfo应该能够帮助这个,但到目前为止,我只是设法凑齐这(n)curses使用的代码片段,当它找不到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); } 

即我得到这个:

 $ 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. $ 

这是…不理想。

一个朋友指着我(tput),我制作了这个解决方案:

 #!/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 "$@" 

这对我有用。 但是,如果我有办法将它整合到ack中 ,那将是非常棒的。

除了需要使用低级别的curses函数setupterm而不是initscr之外,您几乎已经拥有了它。 setupterm只是执行足够的初始化来读取terminfo数据,如果你传入一个指向错误结果值(最后一个参数)的指针,它将返回一个错误值,而不是发出错误信息并退出( initscr的默认行为)。

 #include <stdlib.h> #include <curses.h> int main(void) { char *term = getenv("TERM"); int erret = 0; if (setupterm(NULL, 1, &erret) == ERR) { char *errmsg = "unknown error"; switch (erret) { case 1: errmsg = "terminal is hardcopy, cannot be used for curses applications"; break; case 0: errmsg = "terminal could not be found, or not enough information for curses applications"; break; case -1: errmsg = "terminfo entry could not be found"; break; } printf("Color support for terminal \"%s\" unknown (error %d: %s).\n", term, erret, errmsg); exit(1); } bool colors = has_colors(); printf("Terminal \"%s\" %s colors.\n", term, colors ? "has" : "does not have"); return 0; } 

有关使用setupterm更多信息,请参见curs_terminfo(3X)手册页(x-man-page:// 3x / curs_terminfo)和使用NCURSES编写程序 。

查找终端类型的terminfo(5)条目并检查Co(max_colors)条目。 这就是终端支持的颜色。