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