1 # Term::ANSIColor -- Color screen output using ANSI escape sequences.
2 # $Id: ANSIColor.pm,v 1.4 2001/07/10 08:52:05 eagle Exp $
4 # Copyright 1996, 1997, 1998, 2000, 2001
5 # by Russ Allbery <rra@stanford.edu> and Zenin <zenin@bawdycaste.com>
7 # This program is free software; you may redistribute it and/or modify it
8 # under the same terms as Perl itself.
10 # Ah, September, when the sysadmins turn colors and fall off the trees....
13 ############################################################################
14 # Modules and declarations
15 ############################################################################
17 package Term::ANSIColor;
21 use vars qw($AUTOLOAD $AUTORESET $EACHLINE @ISA @EXPORT @EXPORT_OK
22 %EXPORT_TAGS $VERSION %attributes %attributes_r);
26 @EXPORT = qw(color colored);
27 @EXPORT_OK = qw(uncolor);
28 %EXPORT_TAGS = (constants => [qw(CLEAR RESET BOLD UNDERLINE UNDERSCORE BLINK
29 REVERSE CONCEALED BLACK RED GREEN YELLOW
30 BLUE MAGENTA CYAN WHITE ON_BLACK ON_RED
31 ON_GREEN ON_YELLOW ON_BLUE ON_MAGENTA
33 Exporter::export_ok_tags ('constants');
35 # Don't use the CVS revision as the version, since this module is also in
36 # Perl core and too many things could munge CVS magic revision strings.
40 ############################################################################
41 # Internal data structures
42 ############################################################################
44 %attributes = ('clear' => 0,
54 'black' => 30, 'on_black' => 40,
55 'red' => 31, 'on_red' => 41,
56 'green' => 32, 'on_green' => 42,
57 'yellow' => 33, 'on_yellow' => 43,
58 'blue' => 34, 'on_blue' => 44,
59 'magenta' => 35, 'on_magenta' => 45,
60 'cyan' => 36, 'on_cyan' => 46,
61 'white' => 37, 'on_white' => 47);
63 # Reverse lookup. Alphabetically first name for a sequence is preferred.
64 for (reverse sort keys %attributes) {
65 $attributes_r{$attributes{$_}} = $_;
69 ############################################################################
70 # Implementation (constant form)
71 ############################################################################
73 # Time to have fun! We now want to define the constant subs, which are
74 # named the same as the attributes above but in all caps. Each constant sub
75 # needs to act differently depending on whether $AUTORESET is set. Without
78 # BLUE "text\n" ==> "\e[34mtext\n"
80 # If $AUTORESET is set, we should instead get:
82 # BLUE "text\n" ==> "\e[34mtext\n\e[0m"
84 # The sub also needs to handle the case where it has no arguments correctly.
85 # Maintaining all of this as separate subs would be a major nightmare, as
86 # well as duplicate the %attributes hash, so instead we define an AUTOLOAD
87 # sub to define the constant subs on demand. To do that, we check the name
88 # of the called sub against the list of attributes, and if it's an all-caps
89 # version of one of them, we define the sub on the fly and then run it.
91 # If the environment variable ANSI_COLORS_DISABLED is set, turn all of the
92 # generated subs into pass-through functions that don't add any escape
93 # sequences. This is to make it easier to write scripts that also work on
94 # systems without any ANSI support, like Windows consoles.
96 my $enable_colors = !defined $ENV{ANSI_COLORS_DISABLED};
98 ($sub = $AUTOLOAD) =~ s/^.*:://;
99 my $attr = $attributes{lc $sub};
100 if ($sub =~ /^[A-Z_]+$/ && defined $attr) {
101 $attr = $enable_colors ? "\e[" . $attr . 'm' : '';
104 if (\$AUTORESET && \@_) {
105 '$attr' . "\@_" . "\e[0m";
114 Carp::croak ("undefined subroutine &$AUTOLOAD called");
119 ############################################################################
120 # Implementation (attribute string form)
121 ############################################################################
123 # Return the escape code for a given set of color attributes.
125 return '' if defined $ENV{ANSI_COLORS_DISABLED};
126 my @codes = map { split } @_;
130 unless (defined $attributes{$_}) {
132 Carp::croak ("Invalid attribute name $_");
134 $attribute .= $attributes{$_} . ';';
137 ($attribute ne '') ? "\e[${attribute}m" : undef;
140 # Return a list of named color attributes for a given set of escape codes.
141 # Escape sequences can be given with or without enclosing "\e[" and "m".
142 # The empty escape sequence '' or "\e[m" gives an empty list of attrs.
147 $escape =~ s/^\e\[//;
149 unless ($escape =~ /^((?:\d+;)*\d*)$/) {
151 Carp::croak ("Bad escape sequence $_");
153 push (@nums, split (/;/, $1));
156 $_ += 0; # Strip leading zeroes
157 my $name = $attributes_r{$_};
158 if (!defined $name) {
160 Carp::croak ("No name for escape sequence $_" );
162 push (@result, $name);
167 # Given a string and a set of attributes, returns the string surrounded by
168 # escape codes to set those attributes and then clear them at the end of the
169 # string. The attributes can be given either as an array ref as the first
170 # argument or as a list as the second and subsequent arguments. If
171 # $EACHLINE is set, insert a reset before each occurrence of the string
172 # $EACHLINE and the starting attribute code after the string $EACHLINE, so
173 # that no attribute crosses line delimiters (this is often desirable if the
174 # output is to be piped to a pager or some other program).
176 my ($string, @codes);
179 $string = join ('', @_);
184 return $string if defined $ENV{ANSI_COLORS_DISABLED};
185 if (defined $EACHLINE) {
186 my $attr = color (@codes);
188 map { $_ && $_ ne $EACHLINE ? $attr . $_ . "\e[0m" : $_ }
189 split (/(\Q$EACHLINE\E)/, $string);
191 color (@codes) . $string . "\e[0m";
196 ############################################################################
197 # Module return value and documentation
198 ############################################################################
200 # Ensure we evaluate to true.
206 Term::ANSIColor - Color screen output using ANSI escape sequences
211 print color 'bold blue';
212 print "This text is bold blue.\n";
214 print "This text is normal.\n";
215 print colored ("Yellow on magenta.\n", 'yellow on_magenta');
216 print "This text is normal.\n";
217 print colored ['yellow on_magenta'], "Yellow on magenta.\n";
219 use Term::ANSIColor qw(uncolor);
220 print uncolor '01;31', "\n";
222 use Term::ANSIColor qw(:constants);
223 print BOLD, BLUE, "This text is in bold blue.\n", RESET;
225 use Term::ANSIColor qw(:constants);
226 $Term::ANSIColor::AUTORESET = 1;
227 print BOLD BLUE "This text is in bold blue.\n";
228 print "This text is normal.\n";
232 This module has two interfaces, one through color() and colored() and the
233 other through constants. It also offers the utility function uncolor(),
234 which has to be explicitly imported to be used (see L<SYNOPSYS>).
236 color() takes any number of strings as arguments and considers them to be
237 space-separated lists of attributes. It then forms and returns the escape
238 sequence to set those attributes. It doesn't print it out, just returns it,
239 so you'll have to print it yourself if you want to (this is so that you can
240 save it as a string, pass it to something else, send it to a file handle, or
241 do anything else with it that you might care to).
243 uncolor() performs the opposite translation, turning escape sequences
244 into a list of strings.
246 The recognized attributes (all of which should be fairly intuitive) are
247 clear, reset, dark, bold, underline, underscore, blink, reverse, concealed,
248 black, red, green, yellow, blue, magenta, on_black, on_red, on_green,
249 on_yellow, on_blue, on_magenta, on_cyan, and on_white. Case is not
250 significant. Underline and underscore are equivalent, as are clear and
251 reset, so use whichever is the most intuitive to you. The color alone sets
252 the foreground color, and on_color sets the background color.
254 Note that not all attributes are supported by all terminal types, and some
255 terminals may not support any of these sequences. Dark, blink, and
256 concealed in particular are frequently not implemented.
258 Attributes, once set, last until they are unset (by sending the attribute
259 "reset"). Be careful to do this, or otherwise your attribute will last
260 after your script is done running, and people get very annoyed at having
261 their prompt and typing changed to weird colors.
263 As an aid to help with this, colored() takes a scalar as the first argument
264 and any number of attribute strings as the second argument and returns the
265 scalar wrapped in escape codes so that the attributes will be set as
266 requested before the string and reset to normal after the string.
267 Alternately, you can pass a reference to an array as the first argument, and
268 then the contents of that array will be taken as attributes and color codes
269 and the remainder of the arguments as text to colorize.
271 Normally, colored() just puts attribute codes at the beginning and end of
272 the string, but if you set $Term::ANSIColor::EACHLINE to some string, that
273 string will be considered the line delimiter and the attribute will be set
274 at the beginning of each line of the passed string and reset at the end of
275 each line. This is often desirable if the output is being sent to a program
276 like a pager that can be confused by attributes that span lines. Normally
277 you'll want to set $Term::ANSIColor::EACHLINE to C<"\n"> to use this
280 Alternately, if you import C<:constants>, you can use the constants CLEAR,
281 RESET, BOLD, DARK, UNDERLINE, UNDERSCORE, BLINK, REVERSE, CONCEALED, BLACK,
282 RED, GREEN, YELLOW, BLUE, MAGENTA, ON_BLACK, ON_RED, ON_GREEN, ON_YELLOW,
283 ON_BLUE, ON_MAGENTA, ON_CYAN, and ON_WHITE directly. These are the same as
284 color('attribute') and can be used if you prefer typing:
286 print BOLD BLUE ON_WHITE "Text\n", RESET;
290 print colored ("Text\n", 'bold blue on_white');
292 When using the constants, if you don't want to have to remember to add the
293 C<, RESET> at the end of each print line, you can set
294 $Term::ANSIColor::AUTORESET to a true value. Then, the display mode will
295 automatically be reset if there is no comma after the constant. In other
296 words, with that variable set:
298 print BOLD BLUE "Text\n";
300 will reset the display mode afterwards, whereas:
302 print BOLD, BLUE, "Text\n";
306 The subroutine interface has the advantage over the constants interface in
307 that only two subroutines are exported into your namespace, versus
308 twenty-two in the constants interface. On the flip side, the constants
309 interface has the advantage of better compile time error checking, since
310 misspelled names of colors or attributes in calls to color() and colored()
311 won't be caught until runtime whereas misspelled names of constants will be
312 caught at compile time. So, polute your namespace with almost two dozen
313 subroutines that you may not even use that often, or risk a silly bug by
314 mistyping an attribute. Your choice, TMTOWTDI after all.
320 =item Bad escape sequence %s
322 (F) You passed an invalid ANSI escape sequence to uncolor().
324 =item Bareword "%s" not allowed while "strict subs" in use
326 (F) You probably mistyped a constant color name such as:
328 $Foobar = FOOBAR . "This line should be blue\n";
332 @Foobar = FOOBAR, "This line should be blue\n";
334 This will only show up under use strict (another good reason to run under
337 =item Invalid attribute name %s
339 (F) You passed an invalid attribute name to either color() or colored().
341 =item Name "%s" used only once: possible typo
343 (W) You probably mistyped a constant color name such as:
345 print FOOBAR "This text is color FOOBAR\n";
347 It's probably better to always use commas after constant names in order to
348 force the next error.
350 =item No comma allowed after filehandle
352 (F) You probably mistyped a constant color name such as:
354 print FOOBAR, "This text is color FOOBAR\n";
356 Generating this fatal compile error is one of the main advantages of using
357 the constants interface, since you'll immediately know if you mistype a
360 =item No name for escape sequence %s
362 (F) The ANSI escape sequence passed to uncolor() contains escapes which
363 aren't recognized and can't be translated to names.
371 =item ANSI_COLORS_DISABLED
373 If this environment variable is set, all of the functions defined by this
374 module (color(), colored(), and all of the constants not previously used in
375 the program) will not output any escape sequences and instead will just
376 return the empty string or pass through the original text as appropriate.
377 This is intended to support easy use of scripts using this module on
378 platforms that don't support ANSI escape sequences.
380 For it to have its proper effect, this environment variable must be set
381 before any color constants are used in the program.
387 It would be nice if one could leave off the commas around the constants
388 entirely and just say:
390 print BOLD BLUE ON_WHITE "Text\n" RESET;
392 but the syntax of Perl doesn't allow this. You need a comma after the
393 string. (Of course, you may consider it a bug that commas between all the
394 constants aren't required, in which case you may feel free to insert commas
395 unless you're using $Term::ANSIColor::AUTORESET.)
397 For easier debuging, you may prefer to always use the commas when not
398 setting $Term::ANSIColor::AUTORESET so that you'll get a fatal compile error
399 rather than a warning.
403 The codes generated by this module are standard terminal control codes,
404 complying with ECMA-48 and ISO 6429 (generally referred to as "ANSI color"
405 for the color codes). The non-color control codes (bold, dark, italic,
406 underline, and reverse) are part of the earlier ANSI X3.64 standard for
407 control sequences for video terminals and peripherals.
409 Note that not all displays are ISO 6429-compliant, or even X3.64-compliant
410 (or are even attempting to be so). This module will not work as expected on
411 displays that do not honor these escape sequences, such as (reportedly) the
412 "console" in at least some versions of Windows. They may just be ignored,
413 or they may display as an ESC character followed by some apparent garbage.
415 Jean Delvare provided the following table of different common terminal
416 emulators and their support for the various attributes:
418 clear bold dark under blink reverse conceal
419 ------------------------------------------------------------------------
420 xterm yes yes no yes bold yes yes
421 linux yes yes yes bold yes yes no
422 rxvt yes yes no yes bold/black yes no
423 dtterm yes yes yes yes reverse yes yes
424 teraterm yes reverse no yes rev/red yes no
425 aixterm kinda normal no yes no yes yes
427 Where the entry is other than yes or no, that emulator interpret the given
428 attribute as something else instead. Note that on an aixterm, clear doesn't
429 reset colors; you have to explicitly set the colors back to what you want.
430 More entries in this table are welcome.
432 Note that codes 3 (italic), 6 (rapid blink), and 9 (strikethrough) are
433 specified in ANSI X3.64 and ECMA-048 but are not commonly supported by most
434 displays and emulators and therefore aren't supported by this module at the
435 present time. ECMA-048 also specifies a large number of other attributes,
436 including a sequence of attributes for font changes, Fraktur characters,
437 double-underlining, framing, circling, and overlining. As none of these
438 attributes are widely supported or useful, they also aren't currently
439 supported by this module.
443 ECMA-048 is available on-line (at least at the time of this writing) at
444 E<lt>http://www.ecma.ch/ecma1/STAND/ECMA-048.HTME<gt>.
446 ISO 6429 is available from ISO for a charge; the author of this module does
447 not own a copy of it. Since the source material for ISO 6429 was ECMA-048
448 and the latter is available for free, there seems little reason to obtain
453 Original idea (using constants) by Zenin, reimplemented using subs by Russ
454 Allbery E<lt>rra@stanford.eduE<gt>, and then combined with the original idea
455 by Russ with input from Zenin. Russ Allbery now maintains this module.
459 Copyright 1996, 1997, 1998, 2000, 2001 Russ Allbery <rra@stanford.edu> and
460 Zenin <zenin@bawdycaste.org>. This program is free software; you may
461 redistribute it and/or modify it under the same terms as Perl itself.