You are not logged in.

#1 2015-08-18 09:40:51

ezzetabi
Member
Registered: 2006-08-27
Posts: 947

Is there a portable way to detect terminal escape codes in C?

I wrote a program that acts as a filter (read from stdin, writes in stdout). It works fine in most cases, but sometime it breaks in case of colored input.

So, my question is: it possible to detect portably the escape codes? Does ncurses have a function to do so?

Offline

#2 2015-08-23 12:41:33

mpan
Member
Registered: 2012-08-01
Posts: 1,206
Website

Re: Is there a portable way to detect terminal escape codes in C?

You may use terminfo database for the current terminal (see TERM environment variable and man curs_terminfo) to obtain a list of escape sequences for a pre-defined list of capabilities.

Note however that this is not what you should do. Not only you're giving yourself unneeded work, but the method is not bulletproof: you will miss some capabilities. The solution is not to pass colored output through your filter in the first place.


Sometimes I seem a bit harsh — don’t get offended too easily!

Offline

#3 2015-08-23 12:47:46

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 29,523
Website

Re: Is there a portable way to detect terminal escape codes in C?

mpan wrote:

The solution is not to pass colored output through your filter in the first place.

Depending on what it is, one cannot control what is sent to their program.  So one might argue that Postel's law would favor working around colored input.

However, there is a well established (de facto) standard, that programs should *not* be sending terminal color codes when their output is not being sent to a terminal (but is instead to a pipe).  The best solution would be to report this as a bug to the author of the program sending escape codes when they shouldn't.

From what program(s) are you getting colored output sent to a pipe?

EDIT: an additional problem with using terminfo, is your program can detect what kind of terminal it is connected to, but it is a huge assumption to believe the terminal you are connected to is the same one that the data-provider *thought* it was connected to.  If it is sending escape sequences to a pipe, we already know that the data source was wrong about what it was connected to.


"UNIX is simple and coherent..." - Dennis Ritchie, "GNU's Not UNIX" -  Richard Stallman

Offline

Board footer

Powered by FluxBB