32

我想更改一个程序以自动检测终端是否具有颜色功能,因此当我从不支持颜色的终端(例如 (X)Emacs 中的 Mx shell)中运行所述程序时,颜色会自动关闭.

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

我认为 termcap/terminfo 应该能够帮助解决这个问题,但到目前为止,我只设法拼凑了这个使用 (n) 诅咒的代码片段,当它找不到终端时,它会严重失败:

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

这是......次优的。

4

3 回答 3

23

一位朋友向我介绍了 tput(1),我提出了这个解决方案:

#!/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中,那就太好了。

于 2010-03-17T20:28:52.813 回答
10

You almost had it, except that you need to use the lower-level curses function setupterm instead of initscr. setupterm just performs enough initialization to read terminfo data, and if you pass in a pointer to an error result value (the last argument) it will return an error value instead of emitting error messages and exiting (the default behavior for 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;
}

Additional information about using setupterm is available in the curs_terminfo(3X) man page (x-man-page://3x/curs_terminfo) and Writing Programs with NCURSES.

于 2011-09-15T05:38:12.067 回答
3

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

于 2010-03-17T23:12:13.000 回答