Recipe 21.9. Changing Text ColorProblemYou want to display SolutionThe simplest solution is to use HighLine. It lets you enclose
Some of these features (particularly the blinking and underlining) aren't supported on all terminals. DiscussionThe
These are ANSI escape sequences. Instead of displaying the string "\e[32m", an ANSI-compatible terminal treats it as a command: in this case, a command to start printing characters in green-on-black. The string "\e[0m" tells the terminal to go back to white-on-black. Most modern Unix terminals support ANSI escape sequences, including the Mac OS X terminal. You should be able to get green text in your irb session just by calling puts "\e[32mHello\e[0m" (try it!), but HighLine makes it easy to get color without having to remember the ANSI sequences. Windows terminals don't support ANSI by default, but you can get it to work by loading ANSI.SYS (see below for a relevant Microsoft support article). An alternative to HighLine is the Ncurses library.[4] It supports color terminals that use a means other than ANSI, but these days, most color terminals get their color support through ANSI. Since Ncurses is much more complex than HighLine, and not available as a gem, you should only use Ncurses for color if you're already using it for its other features.
Here's a rough equivalent of the HighLine program given above. This program uses the Ncurses::program wrapper described in Recipe 21.5. The wrapper sets up Ncurses and initializes some default color pairs:
An Ncurses program can draw from a palette of color pairscombinations of foreground and background colors. Ncurses::program sets up a default palette of the seven basic ncurses colors (red, green, yellow, blue, magenta, cyan, and white), each on a black background. You can change this around if you like, or define additional color pairs (like the red-on-blue defined in the example). The following Ncurses program prints out a color chart of all foreground-background pairs. It makes the text of the chart bold, so that the text doesn't become invisible when the background is the same color.
You can modify a color pair by combining it with an Ncurses constant. The most useful constants are Ncurses::A_BOLD, Ncurses::A_BLINK, and Ncurses::A_UNDERLINE. This works the same way (and, on an ANSI system, uses the same ANSI codes) as HighLine's BOLD, BLINK, and UNDERLINE constants. The only difference is that you modify an Ncurses color with the OR operator (|), and you modify a HighLine color with the addition operator. See Also
|
Monday, October 26, 2009
Recipe 21.9. Changing Text Color
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment