This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Move all mro:: XS functions from mro.c to ext/mro/mro.xs, except for
[perl5.git] / lib / Term / ANSIColor.pm
1 # Term::ANSIColor -- Color screen output using ANSI escape sequences.
2 # $Id: ANSIColor.pm 64 2007-03-23 17:58:18Z eagle $
3 #
4 # Copyright 1996, 1997, 1998, 2000, 2001, 2002, 2005, 2006
5 #   by Russ Allbery <rra@stanford.edu> and Zenin
6 #
7 # This program is free software; you may redistribute it and/or modify it
8 # under the same terms as Perl itself.
9 #
10 # Ah, September, when the sysadmins turn colors and fall off the trees....
11 #                               -- Dave Van Domelen
12
13 ##############################################################################
14 # Modules and declarations
15 ##############################################################################
16
17 package Term::ANSIColor;
18 require 5.001;
19
20 use strict;
21 use vars qw($AUTOLOAD $AUTORESET $EACHLINE @ISA @EXPORT @EXPORT_OK
22             %EXPORT_TAGS $VERSION %attributes %attributes_r);
23
24 use Exporter ();
25 @ISA         = qw(Exporter);
26 @EXPORT      = qw(color colored);
27 @EXPORT_OK   = qw(uncolor);
28 %EXPORT_TAGS = (constants => [qw(CLEAR RESET BOLD DARK UNDERLINE UNDERSCORE
29                                  BLINK REVERSE CONCEALED BLACK RED GREEN
30                                  YELLOW BLUE MAGENTA CYAN WHITE ON_BLACK
31                                  ON_RED ON_GREEN ON_YELLOW ON_BLUE ON_MAGENTA
32                                  ON_CYAN ON_WHITE)]);
33 Exporter::export_ok_tags ('constants');
34
35 $VERSION = '1.12';
36
37 ##############################################################################
38 # Internal data structures
39 ##############################################################################
40
41 %attributes = ('clear'      => 0,
42                'reset'      => 0,
43                'bold'       => 1,
44                'dark'       => 2,
45                'underline'  => 4,
46                'underscore' => 4,
47                'blink'      => 5,
48                'reverse'    => 7,
49                'concealed'  => 8,
50
51                'black'      => 30,   'on_black'   => 40,
52                'red'        => 31,   'on_red'     => 41,
53                'green'      => 32,   'on_green'   => 42,
54                'yellow'     => 33,   'on_yellow'  => 43,
55                'blue'       => 34,   'on_blue'    => 44,
56                'magenta'    => 35,   'on_magenta' => 45,
57                'cyan'       => 36,   'on_cyan'    => 46,
58                'white'      => 37,   'on_white'   => 47);
59
60 # Reverse lookup.  Alphabetically first name for a sequence is preferred.
61 for (reverse sort keys %attributes) {
62     $attributes_r{$attributes{$_}} = $_;
63 }
64
65 ##############################################################################
66 # Implementation (constant form)
67 ##############################################################################
68
69 # Time to have fun!  We now want to define the constant subs, which are named
70 # the same as the attributes above but in all caps.  Each constant sub needs
71 # to act differently depending on whether $AUTORESET is set.  Without
72 # autoreset:
73 #
74 #     BLUE "text\n"  ==>  "\e[34mtext\n"
75 #
76 # If $AUTORESET is set, we should instead get:
77 #
78 #     BLUE "text\n"  ==>  "\e[34mtext\n\e[0m"
79 #
80 # The sub also needs to handle the case where it has no arguments correctly.
81 # Maintaining all of this as separate subs would be a major nightmare, as well
82 # as duplicate the %attributes hash, so instead we define an AUTOLOAD sub to
83 # define the constant subs on demand.  To do that, we check the name of the
84 # called sub against the list of attributes, and if it's an all-caps version
85 # of one of them, we define the sub on the fly and then run it.
86 #
87 # If the environment variable ANSI_COLORS_DISABLED is set, turn all of the
88 # generated subs into pass-through functions that don't add any escape
89 # sequences.  This is to make it easier to write scripts that also work on
90 # systems without any ANSI support, like Windows consoles.
91 sub AUTOLOAD {
92     my $enable_colors = !defined $ENV{ANSI_COLORS_DISABLED};
93     my $sub;
94     ($sub = $AUTOLOAD) =~ s/^.*:://;
95     my $attr = $attributes{lc $sub};
96     if ($sub =~ /^[A-Z_]+$/ && defined $attr) {
97         $attr = $enable_colors ? "\e[" . $attr . 'm' : '';
98         eval qq {
99             sub $AUTOLOAD {
100                 if (\$AUTORESET && \@_) {
101                     '$attr' . "\@_" . "\e[0m";
102                 } else {
103                     ('$attr' . "\@_");
104                 }
105             }
106         };
107         goto &$AUTOLOAD;
108     } else {
109         require Carp;
110         Carp::croak ("undefined subroutine &$AUTOLOAD called");
111     }
112 }
113
114 ##############################################################################
115 # Implementation (attribute string form)
116 ##############################################################################
117
118 # Return the escape code for a given set of color attributes.
119 sub color {
120     return '' if defined $ENV{ANSI_COLORS_DISABLED};
121     my @codes = map { split } @_;
122     my $attribute = '';
123     foreach (@codes) {
124         $_ = lc $_;
125         unless (defined $attributes{$_}) {
126             require Carp;
127             Carp::croak ("Invalid attribute name $_");
128         }
129         $attribute .= $attributes{$_} . ';';
130     }
131     chop $attribute;
132     ($attribute ne '') ? "\e[${attribute}m" : undef;
133 }
134
135 # Return a list of named color attributes for a given set of escape codes.
136 # Escape sequences can be given with or without enclosing "\e[" and "m".  The
137 # empty escape sequence '' or "\e[m" gives an empty list of attrs.
138 sub uncolor {
139     my (@nums, @result);
140     for (@_) {
141         my $escape = $_;
142         $escape =~ s/^\e\[//;
143         $escape =~ s/m$//;
144         unless ($escape =~ /^((?:\d+;)*\d*)$/) {
145             require Carp;
146             Carp::croak ("Bad escape sequence $_");
147         }
148         push (@nums, split (/;/, $1));
149     }
150     for (@nums) {
151         $_ += 0; # Strip leading zeroes
152         my $name = $attributes_r{$_};
153         if (!defined $name) {
154             require Carp;
155             Carp::croak ("No name for escape sequence $_" );
156         }
157         push (@result, $name);
158     }
159     @result;
160 }
161
162 # Given a string and a set of attributes, returns the string surrounded by
163 # escape codes to set those attributes and then clear them at the end of the
164 # string.  The attributes can be given either as an array ref as the first
165 # argument or as a list as the second and subsequent arguments.  If $EACHLINE
166 # is set, insert a reset before each occurrence of the string $EACHLINE and
167 # the starting attribute code after the string $EACHLINE, so that no attribute
168 # crosses line delimiters (this is often desirable if the output is to be
169 # piped to a pager or some other program).
170 sub colored {
171     my ($string, @codes);
172     if (ref $_[0]) {
173         @codes = @{+shift};
174         $string = join ('', @_);
175     } else {
176         $string = shift;
177         @codes = @_;
178     }
179     return $string if defined $ENV{ANSI_COLORS_DISABLED};
180     if (defined $EACHLINE) {
181         my $attr = color (@codes);
182         join '',
183             map { $_ ne $EACHLINE ? $attr . $_ . "\e[0m" : $_ }
184                 grep { length ($_) > 0 }
185                     split (/(\Q$EACHLINE\E)/, $string);
186     } else {
187         color (@codes) . $string . "\e[0m";
188     }
189 }
190
191 ##############################################################################
192 # Module return value and documentation
193 ##############################################################################
194
195 # Ensure we evaluate to true.
196 1;
197 __END__
198
199 =head1 NAME
200
201 Term::ANSIColor - Color screen output using ANSI escape sequences
202
203 =head1 SYNOPSIS
204
205     use Term::ANSIColor;
206     print color 'bold blue';
207     print "This text is bold blue.\n";
208     print color 'reset';
209     print "This text is normal.\n";
210     print colored ("Yellow on magenta.", 'yellow on_magenta'), "\n";
211     print "This text is normal.\n";
212     print colored ['yellow on_magenta'], 'Yellow on magenta.';
213     print "\n";
214
215     use Term::ANSIColor qw(uncolor);
216     print uncolor '01;31', "\n";
217
218     use Term::ANSIColor qw(:constants);
219     print BOLD, BLUE, "This text is in bold blue.\n", RESET;
220
221     use Term::ANSIColor qw(:constants);
222     $Term::ANSIColor::AUTORESET = 1;
223     print BOLD BLUE "This text is in bold blue.\n";
224     print "This text is normal.\n";
225
226 =head1 DESCRIPTION
227
228 This module has two interfaces, one through color() and colored() and the
229 other through constants.  It also offers the utility function uncolor(),
230 which has to be explicitly imported to be used (see L</SYNOPSIS>).
231
232 color() takes any number of strings as arguments and considers them to be
233 space-separated lists of attributes.  It then forms and returns the escape
234 sequence to set those attributes.  It doesn't print it out, just returns it,
235 so you'll have to print it yourself if you want to (this is so that you can
236 save it as a string, pass it to something else, send it to a file handle, or
237 do anything else with it that you might care to).
238
239 uncolor() performs the opposite translation, turning escape sequences
240 into a list of strings.
241
242 The recognized attributes (all of which should be fairly intuitive) are clear,
243 reset, dark, bold, underline, underscore, blink, reverse, concealed, black,
244 red, green, yellow, blue, magenta, cyan, white, on_black, on_red, on_green,
245 on_yellow, on_blue, on_magenta, on_cyan, and on_white.  Case is not
246 significant.  Underline and underscore are equivalent, as are clear and reset,
247 so use whichever is the most intuitive to you.  The color alone sets the
248 foreground color, and on_color sets the background color.
249
250 Note that not all attributes are supported by all terminal types, and some
251 terminals may not support any of these sequences.  Dark, blink, and
252 concealed in particular are frequently not implemented.
253
254 Attributes, once set, last until they are unset (by sending the attribute
255 "reset").  Be careful to do this, or otherwise your attribute will last
256 after your script is done running, and people get very annoyed at having
257 their prompt and typing changed to weird colors.
258
259 As an aid to help with this, colored() takes a scalar as the first argument
260 and any number of attribute strings as the second argument and returns the
261 scalar wrapped in escape codes so that the attributes will be set as
262 requested before the string and reset to normal after the string.
263 Alternately, you can pass a reference to an array as the first argument, and
264 then the contents of that array will be taken as attributes and color codes
265 and the remainder of the arguments as text to colorize.
266
267 Normally, colored() just puts attribute codes at the beginning and end of
268 the string, but if you set $Term::ANSIColor::EACHLINE to some string, that
269 string will be considered the line delimiter and the attribute will be set
270 at the beginning of each line of the passed string and reset at the end of
271 each line.  This is often desirable if the output contains newlines and
272 you're using background colors, since a background color that persists
273 across a newline is often interpreted by the terminal as providing the
274 default background color for the next line.  Programs like pagers can also
275 be confused by attributes that span lines.  Normally you'll want to set
276 $Term::ANSIColor::EACHLINE to C<"\n"> to use this feature.
277
278 Alternately, if you import C<:constants>, you can use the constants CLEAR,
279 RESET, BOLD, DARK, UNDERLINE, UNDERSCORE, BLINK, REVERSE, CONCEALED, BLACK,
280 RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, ON_BLACK, ON_RED, ON_GREEN,
281 ON_YELLOW, ON_BLUE, ON_MAGENTA, ON_CYAN, and ON_WHITE directly.  These are
282 the same as color('attribute') and can be used if you prefer typing:
283
284     print BOLD BLUE ON_WHITE "Text", RESET, "\n";
285
286 to
287
288     print colored ("Text", 'bold blue on_white'), "\n";
289
290 (Note that the newline is kept separate to avoid confusing the terminal as
291 described above since a background color is being used.)
292
293 When using the constants, if you don't want to have to remember to add the
294 C<, RESET> at the end of each print line, you can set
295 $Term::ANSIColor::AUTORESET to a true value.  Then, the display mode will
296 automatically be reset if there is no comma after the constant.  In other
297 words, with that variable set:
298
299     print BOLD BLUE "Text\n";
300
301 will reset the display mode afterwards, whereas:
302
303     print BOLD, BLUE, "Text\n";
304
305 will not.  If you are using background colors, you will probably want to
306 print the newline with a separate print statement to avoid confusing the
307 terminal.
308
309 The subroutine interface has the advantage over the constants interface in
310 that only two subroutines are exported into your namespace, versus
311 twenty-two in the constants interface.  On the flip side, the constants
312 interface has the advantage of better compile time error checking, since
313 misspelled names of colors or attributes in calls to color() and colored()
314 won't be caught until runtime whereas misspelled names of constants will be
315 caught at compile time.  So, pollute your namespace with almost two dozen
316 subroutines that you may not even use that often, or risk a silly bug by
317 mistyping an attribute.  Your choice, TMTOWTDI after all.
318
319 =head1 DIAGNOSTICS
320
321 =over 4
322
323 =item Bad escape sequence %s
324
325 (F) You passed an invalid ANSI escape sequence to uncolor().
326
327 =item Bareword "%s" not allowed while "strict subs" in use
328
329 (F) You probably mistyped a constant color name such as:
330
331     $Foobar = FOOBAR . "This line should be blue\n";
332
333 or:
334
335     @Foobar = FOOBAR, "This line should be blue\n";
336
337 This will only show up under use strict (another good reason to run under
338 use strict).
339
340 =item Invalid attribute name %s
341
342 (F) You passed an invalid attribute name to either color() or colored().
343
344 =item Name "%s" used only once: possible typo
345
346 (W) You probably mistyped a constant color name such as:
347
348     print FOOBAR "This text is color FOOBAR\n";
349
350 It's probably better to always use commas after constant names in order to
351 force the next error.
352
353 =item No comma allowed after filehandle
354
355 (F) You probably mistyped a constant color name such as:
356
357     print FOOBAR, "This text is color FOOBAR\n";
358
359 Generating this fatal compile error is one of the main advantages of using
360 the constants interface, since you'll immediately know if you mistype a
361 color name.
362
363 =item No name for escape sequence %s
364
365 (F) The ANSI escape sequence passed to uncolor() contains escapes which
366 aren't recognized and can't be translated to names.
367
368 =back
369
370 =head1 ENVIRONMENT
371
372 =over 4
373
374 =item ANSI_COLORS_DISABLED
375
376 If this environment variable is set, all of the functions defined by this
377 module (color(), colored(), and all of the constants not previously used in
378 the program) will not output any escape sequences and instead will just
379 return the empty string or pass through the original text as appropriate.
380 This is intended to support easy use of scripts using this module on
381 platforms that don't support ANSI escape sequences.
382
383 For it to have its proper effect, this environment variable must be set
384 before any color constants are used in the program.
385
386 =back
387
388 =head1 RESTRICTIONS
389
390 It would be nice if one could leave off the commas around the constants
391 entirely and just say:
392
393     print BOLD BLUE ON_WHITE "Text\n" RESET;
394
395 but the syntax of Perl doesn't allow this.  You need a comma after the
396 string.  (Of course, you may consider it a bug that commas between all the
397 constants aren't required, in which case you may feel free to insert commas
398 unless you're using $Term::ANSIColor::AUTORESET.)
399
400 For easier debugging, you may prefer to always use the commas when not
401 setting $Term::ANSIColor::AUTORESET so that you'll get a fatal compile error
402 rather than a warning.
403
404 =head1 NOTES
405
406 The codes generated by this module are standard terminal control codes,
407 complying with ECMA-48 and ISO 6429 (generally referred to as "ANSI color"
408 for the color codes).  The non-color control codes (bold, dark, italic,
409 underline, and reverse) are part of the earlier ANSI X3.64 standard for
410 control sequences for video terminals and peripherals.
411
412 Note that not all displays are ISO 6429-compliant, or even X3.64-compliant
413 (or are even attempting to be so).  This module will not work as expected on
414 displays that do not honor these escape sequences, such as cmd.exe, 4nt.exe,
415 and command.com under either Windows NT or Windows 2000.  They may just be
416 ignored, or they may display as an ESC character followed by some apparent
417 garbage.
418
419 Jean Delvare provided the following table of different common terminal
420 emulators and their support for the various attributes and others have helped
421 me flesh it out:
422
423               clear    bold     dark    under    blink   reverse  conceal
424  ------------------------------------------------------------------------
425  xterm         yes      yes      no      yes     bold      yes      yes
426  linux         yes      yes      yes    bold      yes      yes      no
427  rxvt          yes      yes      no      yes  bold/black   yes      no
428  dtterm        yes      yes      yes     yes    reverse    yes      yes
429  teraterm      yes    reverse    no      yes    rev/red    yes      no
430  aixterm      kinda   normal     no      yes      no       yes      yes
431  PuTTY         yes     color     no      yes      no       yes      no
432  Windows       yes      no       no      no       no       yes      no
433  Cygwin SSH    yes      yes      no     color    color    color     yes
434  Mac Terminal  yes      yes      no      yes      yes      yes      yes
435
436 Windows is Windows telnet, Cygwin SSH is the OpenSSH implementation under
437 Cygwin on Windows NT, and Mac Terminal is the Terminal application in Mac OS
438 X.  Where the entry is other than yes or no, that emulator displays the
439 given attribute as something else instead.  Note that on an aixterm, clear
440 doesn't reset colors; you have to explicitly set the colors back to what you
441 want.  More entries in this table are welcome.
442
443 Note that codes 3 (italic), 6 (rapid blink), and 9 (strikethrough) are
444 specified in ANSI X3.64 and ECMA-048 but are not commonly supported by most
445 displays and emulators and therefore aren't supported by this module at the
446 present time.  ECMA-048 also specifies a large number of other attributes,
447 including a sequence of attributes for font changes, Fraktur characters,
448 double-underlining, framing, circling, and overlining.  As none of these
449 attributes are widely supported or useful, they also aren't currently
450 supported by this module.
451
452 =head1 SEE ALSO
453
454 ECMA-048 is available on-line (at least at the time of this writing) at
455 L<http://www.ecma-international.org/publications/standards/ECMA-048.HTM>.
456
457 ISO 6429 is available from ISO for a charge; the author of this module does
458 not own a copy of it.  Since the source material for ISO 6429 was ECMA-048
459 and the latter is available for free, there seems little reason to obtain
460 the ISO standard.
461
462 The current version of this module is always available from its web site at
463 L<http://www.eyrie.org/~eagle/software/ansicolor/>.  It is also part of the
464 Perl core distribution as of 5.6.0.
465
466 =head1 AUTHORS
467
468 Original idea (using constants) by Zenin, reimplemented using subs by Russ
469 Allbery <rra@stanford.edu>, and then combined with the original idea by Russ
470 with input from Zenin.  Russ Allbery now maintains this module.
471
472 =head1 COPYRIGHT AND LICENSE
473
474 Copyright 1996, 1997, 1998, 2000, 2001, 2002, 2005, 2006 Russ Allbery
475 <rra@stanford.edu> and Zenin.  This program is free software; you may
476 redistribute it and/or modify it under the same terms as Perl itself.
477
478 =cut