问题描述
我想更改一个程序以自动检测终端是否支持颜色,所以当我从不支持颜色的终端(例如(X)Emacs中的Mx shell)运行该程序时,颜色为自动关闭.
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.
我不想对程序进行硬编码以检测TERM = {emacs,dumb}.
I don't want to hardcode the program to detect TERM={emacs,dumb}.
我认为termcap/terminfo应该可以解决这个问题,但到目前为止,我仅设法使用代码片段将这(n)个curses拼凑在一起,当找不到该代码时,该方法将严重失败终端:
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);
}
即我明白了:
$ 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(1),我准备了以下解决方案:
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 "$@"
对我有用.不过,如果我有办法将其集成到 ack 中,那将是很好的.
which works for me. It would be great if I had a way to integrate it into ack, though.
这篇关于如何确定终端是否支持颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!