문제

터미널이 색상을 사용할 수 있는지 여부를 자동으로 감지하기 위해 프로그램을 변경하고 싶습니다. 따라서 컬러 유능한 터미널 내에서 상기 프로그램을 실행할 때 (x) EMACS의 MX Shell)에서 색상이 자동으로 꺼집니다. .

용어 = {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.
$ 

그것은 ... 차선책입니다.

도움이 되었습니까?

해결책

친구가 나를 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, 그렇지만.

다른 팁

하위 레벨 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) man page (x-man-page : // curs_terminfo) 및 ncures와 함께 프로그램 작성.

터미널 유형의 TermInfo (5) 항목을 찾아 CO (Max_Colors) 항목을 확인하십시오. 그것이 터미널이 지원하는 몇 가지 색상입니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top