如何确定终端是否支持彩色? [英] How do I determine if a terminal is color-capable?

查看:32
本文介绍了如何确定终端是否支持彩色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改一个程序以自动检测终端是否支持颜色,因此当我从不支持颜色的终端(例如 (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-using 代码片段,当它找不到终端:

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
" : "NO
");

 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.

这篇关于如何确定终端是否支持彩色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆