Read the current text color in a xterm

I'm writing various utilities, and I'm really liking colorized text. Nothing fancy, just using escape sequences. I've created a simple class that has a pprint(msg, color) function. I've got it working rather easily after finding the codes here.

The problem that I'm having is that I should be able to turn off the color after printing. For example, let's say a user runs my program that prints almost everything in the default terminal color, but there is an error, and I want to print the error in red. I prefix my error message with '\033[0;32m', and the message is in red. Unfortunately, all text is red until I change it. That's generally fine while my program is running because I know what color the messages should be. However, the color remains after my program ends. Basically, I'd like to read the current color when my program starts, and restore it when finished. The same way that scripts restore the pwd when exiting.

How do I read the current escape sequence?

System: Red Hat 5.x Bash Python 2.3

Thanks for the help.

Answers


I don't believe that's possible and it's unlikely to be portable if it were. The best you can do is send sgr0 which resets all attributes to default (not previous). On xterms, sgr0 is Esc[m. If you want to reset the colors and not affect other attributes, send op which on xterms is Esc[39;49m.

These codes should not be hardcoded. You should use terminfo, termcap or [n]curses.


Rather than using obfuscated escape sequences, use the tput facility instead. Here is an excerpt from my ~/.bashrc that I use for my PS1 prompt:

BLACK=$(tput setaf 0)
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
YELLOW=$(tput setaf 3)
LIME_YELLOW=$(tput setaf 190)
POWDER_BLUE=$(tput setaf 153)
BLUE=$(tput setaf 4)
MAGENTA=$(tput setaf 5)
CYAN=$(tput setaf 6)
WHITE=$(tput setaf 7)
BRIGHT=$(tput bold)
NORMAL=$(tput sgr0)
BLINK=$(tput blink)
REVERSE=$(tput smso)
UNDERLINE=$(tput smul)

To reset the color information such that subsequent text is in the normal terminal color you would append ${NORMAL} to the end like so:

echo "${RED}this is red ${NORMAL}this is normal"


RED = 31
GREEN = 32
ESCAPE = '%s[' % chr(27)
RESET = '%s0m' % ESCAPE
FORMAT = '1;%dm'

def colorize(text, color):
    return ESCAPE + (FORMAT % (color, )) + text + RESET

This function will return a string that will print colorized, with the terminal automatically being reset afterwards.


Need Your Help

Vim: Remove mapping created by vim-plugin

vim plugins mapping

I use the Vimwiki-Plugin a lot, but remapping <Backspace> and <CR> is just anoying. If I use :nmap, the mapping is shown:

accessing child td from tr using dynamic variable

javascript jquery parent-child

I have got a problem where I need to access the <td> of <tr> using the jquery .eq() function. Below is the code mentioned please have a look.