1 # Color screen output using ANSI escape sequences.
3 # Copyright 1996, 1997, 1998, 2000, 2001, 2002, 2005, 2006, 2008, 2009, 2010,
4 # 2011, 2012, 2013, 2014, 2015, 2016 Russ Allbery <rra@cpan.org>
6 # Copyright 2012 Kurt Starsinic <kstarsinic@gmail.com>
8 # This program is free software; you may redistribute it and/or modify it
9 # under the same terms as Perl itself.
11 # PUSH/POP support submitted 2007 by openmethods.com voice solutions
13 # Ah, September, when the sysadmins turn colors and fall off the trees....
16 ##############################################################################
17 # Modules and declarations
18 ##############################################################################
20 package Term::ANSIColor;
26 # Also uses Carp but loads it on demand to reduce memory usage.
30 # use Exporter plus @ISA instead of use base for 5.6 compatibility.
31 ## no critic (ClassHierarchies::ProhibitExplicitISA)
33 # Declare variables that should be set in BEGIN for robustness.
34 ## no critic (Modules::ProhibitAutomaticExportation)
35 our (@EXPORT, @EXPORT_OK, %EXPORT_TAGS, @ISA, $VERSION);
37 # We use autoloading, which sets this variable to the name of the called sub.
40 # Set $VERSION and everything export-related in a BEGIN block for robustness
41 # against circular module loading (not that we load any modules, but
42 # consistency is good).
46 # All of the basic supported constants, used in %EXPORT_TAGS.
49 FAINT ITALIC UNDERLINE UNDERSCORE
50 BLINK REVERSE CONCEALED
52 BLACK RED GREEN YELLOW
53 BLUE MAGENTA CYAN WHITE
54 ON_BLACK ON_RED ON_GREEN ON_YELLOW
55 ON_BLUE ON_MAGENTA ON_CYAN ON_WHITE
57 BRIGHT_BLACK BRIGHT_RED BRIGHT_GREEN BRIGHT_YELLOW
58 BRIGHT_BLUE BRIGHT_MAGENTA BRIGHT_CYAN BRIGHT_WHITE
59 ON_BRIGHT_BLACK ON_BRIGHT_RED ON_BRIGHT_GREEN ON_BRIGHT_YELLOW
60 ON_BRIGHT_BLUE ON_BRIGHT_MAGENTA ON_BRIGHT_CYAN ON_BRIGHT_WHITE
63 # 256-color constants, used in %EXPORT_TAGS.
65 (map { ("ANSI$_", "ON_ANSI$_") } 0 .. 15),
66 (map { ("GREY$_", "ON_GREY$_") } 0 .. 23),
70 push(@colorlist256, map { ("RGB$r$g$_", "ON_RGB$r$g$_") } 0 .. 5);
74 # Exported symbol configuration.
76 @EXPORT = qw(color colored);
77 @EXPORT_OK = qw(uncolor colorstrip colorvalid coloralias);
79 constants => \@colorlist,
80 constants256 => \@colorlist256,
81 pushpop => [@colorlist, qw(PUSHCOLOR POPCOLOR LOCALCOLOR)],
83 Exporter::export_ok_tags('pushpop', 'constants256');
86 ##############################################################################
88 ##############################################################################
90 # If this is set, any color changes will implicitly push the current color
91 # onto the stack and then pop it at the end of the constant sequence, just as
92 # if LOCALCOLOR were used.
95 # Caller sets this to force a reset at the end of each constant sequence.
98 # Caller sets this to force colors to be reset at the end of each line.
101 ##############################################################################
102 # Internal data structures
103 ##############################################################################
105 # This module does quite a bit of initialization at the time it is first
106 # loaded, primarily to set up the package-global %ATTRIBUTES hash. The
107 # entries for 256-color names are easier to handle programmatically, and
108 # custom colors are also imported from the environment if any are set.
110 # All basic supported attributes, including aliases.
125 'black' => 30, 'on_black' => 40,
126 'red' => 31, 'on_red' => 41,
127 'green' => 32, 'on_green' => 42,
128 'yellow' => 33, 'on_yellow' => 43,
129 'blue' => 34, 'on_blue' => 44,
130 'magenta' => 35, 'on_magenta' => 45,
131 'cyan' => 36, 'on_cyan' => 46,
132 'white' => 37, 'on_white' => 47,
134 'bright_black' => 90, 'on_bright_black' => 100,
135 'bright_red' => 91, 'on_bright_red' => 101,
136 'bright_green' => 92, 'on_bright_green' => 102,
137 'bright_yellow' => 93, 'on_bright_yellow' => 103,
138 'bright_blue' => 94, 'on_bright_blue' => 104,
139 'bright_magenta' => 95, 'on_bright_magenta' => 105,
140 'bright_cyan' => 96, 'on_bright_cyan' => 106,
141 'bright_white' => 97, 'on_bright_white' => 107,
145 # Generating the 256-color codes involves a lot of codes and offsets that are
146 # not helped by turning them into constants.
148 # The first 16 256-color codes are duplicates of the 16 ANSI colors,
149 # included for completeness.
150 for my $code (0 .. 15) {
151 $ATTRIBUTES{"ansi$code"} = "38;5;$code";
152 $ATTRIBUTES{"on_ansi$code"} = "48;5;$code";
155 # 256-color RGB colors. Red, green, and blue can each be values 0 through 5,
156 # and the resulting 216 colors start with color 16.
160 my $code = 16 + (6 * 6 * $r) + (6 * $g) + $b;
161 $ATTRIBUTES{"rgb$r$g$b"} = "38;5;$code";
162 $ATTRIBUTES{"on_rgb$r$g$b"} = "48;5;$code";
167 # The last 256-color codes are 24 shades of grey.
168 for my $n (0 .. 23) {
170 $ATTRIBUTES{"grey$n"} = "38;5;$code";
171 $ATTRIBUTES{"on_grey$n"} = "48;5;$code";
174 # Reverse lookup. Alphabetically first name for a sequence is preferred.
176 for my $attr (reverse sort keys %ATTRIBUTES) {
177 $ATTRIBUTES_R{ $ATTRIBUTES{$attr} } = $attr;
180 # Import any custom colors set in the environment.
182 if (exists $ENV{ANSI_COLORS_ALIASES}) {
183 my $spec = $ENV{ANSI_COLORS_ALIASES};
184 $spec =~ s{\s+}{}xmsg;
186 # Error reporting here is an interesting question. Use warn rather than
187 # carp because carp would report the line of the use or require, which
188 # doesn't help anyone understand what's going on, whereas seeing this code
189 # will be more helpful.
190 ## no critic (ErrorHandling::RequireCarping)
191 for my $definition (split m{,}xms, $spec) {
192 my ($new, $old) = split m{=}xms, $definition, 2;
193 if (!$new || !$old) {
194 warn qq{Bad color mapping "$definition"};
196 my $result = eval { coloralias($new, $old) };
199 $error =~ s{ [ ] at [ ] .* }{}xms;
200 warn qq{$error in "$definition"};
206 # Stores the current color stack maintained by PUSHCOLOR and POPCOLOR. This
207 # is global and therefore not threadsafe.
210 ##############################################################################
212 ##############################################################################
214 # Stub to load the Carp module on demand.
221 ##############################################################################
222 # Implementation (constant form)
223 ##############################################################################
225 # Time to have fun! We now want to define the constant subs, which are named
226 # the same as the attributes above but in all caps. Each constant sub needs
227 # to act differently depending on whether $AUTORESET is set. Without
230 # BLUE "text\n" ==> "\e[34mtext\n"
232 # If $AUTORESET is set, we should instead get:
234 # BLUE "text\n" ==> "\e[34mtext\n\e[0m"
236 # The sub also needs to handle the case where it has no arguments correctly.
237 # Maintaining all of this as separate subs would be a major nightmare, as well
238 # as duplicate the %ATTRIBUTES hash, so instead we define an AUTOLOAD sub to
239 # define the constant subs on demand. To do that, we check the name of the
240 # called sub against the list of attributes, and if it's an all-caps version
241 # of one of them, we define the sub on the fly and then run it.
243 # If the environment variable ANSI_COLORS_DISABLED is set to a true value,
244 # just return the arguments without adding any escape sequences. This is to
245 # make it easier to write scripts that also work on systems without any ANSI
246 # support, like Windows consoles.
248 # Avoid using character classes like [:upper:] and \w here, since they load
249 # Unicode character tables and consume a ton of memory. All of our constants
250 # only use ASCII characters.
252 ## no critic (ClassHierarchies::ProhibitAutoloading)
253 ## no critic (Subroutines::RequireArgUnpacking)
254 ## no critic (RegularExpressions::ProhibitEnumeratedClasses)
256 my ($sub, $attr) = $AUTOLOAD =~ m{
257 \A ( [a-zA-Z0-9:]* :: ([A-Z0-9_]+) ) \z
260 # Check if we were called with something that doesn't look like an
262 if (!($attr && defined($ATTRIBUTES{ lc $attr }))) {
263 croak("undefined subroutine &$AUTOLOAD called");
266 # If colors are disabled, just return the input. Do this without
267 # installing a sub for (marginal, unbenchmarked) speed.
268 if ($ENV{ANSI_COLORS_DISABLED}) {
269 return join(q{}, @_);
272 # We've untainted the name of the sub.
275 # Figure out the ANSI string to set the desired attribute.
276 my $escape = "\e[" . $ATTRIBUTES{ lc $attr } . 'm';
278 # Save the current value of $@. We can't just use local since we want to
279 # restore it before dispatching to the newly-created sub. (The caller may
280 # be colorizing output that includes $@.)
283 # Generate the constant sub, which should still recognize some of our
284 # package variables. Use string eval to avoid a dependency on
285 # Sub::Install, even though it makes it somewhat less readable.
286 ## no critic (BuiltinFunctions::ProhibitStringyEval)
287 ## no critic (ValuesAndExpressions::ProhibitImplicitNewlines)
288 my $eval_result = eval qq{
290 if (\$ENV{ANSI_COLORS_DISABLED}) {
291 return join(q{}, \@_);
292 } elsif (\$AUTOLOCAL && \@_) {
293 return PUSHCOLOR('$escape') . join(q{}, \@_) . POPCOLOR;
294 } elsif (\$AUTORESET && \@_) {
295 return '$escape' . join(q{}, \@_) . "\e[0m";
297 return '$escape' . join(q{}, \@_);
303 # Failure is an internal error, not a problem with the caller.
304 ## no critic (ErrorHandling::RequireCarping)
306 die "failed to generate constant $attr: $@";
310 ## no critic (Variables::RequireLocalizedPunctuationVars)
313 # Dispatch to the newly-created sub.
314 ## no critic (References::ProhibitDoubleSigils)
319 # Append a new color to the top of the color stack and return the top of
322 # $text - Any text we're applying colors to, with color escapes prepended
324 # Returns: The text passed in
327 my $text = join(q{}, @text);
329 # Extract any number of color-setting escape sequences from the start of
331 my ($color) = $text =~ m{ \A ( (?:\e\[ [\d;]+ m)+ ) }xms;
333 # If we already have a stack, append these escapes to the set from the top
334 # of the stack. This way, each position in the stack stores the complete
335 # enabled colors for that stage, at the cost of some potential
338 $color = $COLORSTACK[-1] . $color;
341 # Push the color onto the stack.
342 push(@COLORSTACK, $color);
346 # Pop the color stack and return the new top of the stack (or reset, if
347 # the stack is empty).
349 # @text - Any text we're applying colors to
351 # Returns: The concatenation of @text prepended with the new stack color
356 return $COLORSTACK[-1] . join(q{}, @text);
362 # Surround arguments with a push and a pop. The effect will be to reset the
363 # colors to whatever was on the color stack before this sequence of colors was
366 # @text - Any text we're applying colors to
368 # Returns: The concatenation of the text and the proper color reset sequence.
371 return PUSHCOLOR(join(q{}, @text)) . POPCOLOR();
374 ##############################################################################
375 # Implementation (attribute string form)
376 ##############################################################################
378 # Return the escape code for a given set of color attributes.
380 # @codes - A list of possibly space-separated color attributes
382 # Returns: The escape sequence setting those color attributes
383 # undef if no escape sequences were given
384 # Throws: Text exception for any invalid attribute
387 @codes = map { split } @codes;
389 # Return the empty string if colors are disabled.
390 if ($ENV{ANSI_COLORS_DISABLED}) {
394 # Build the attribute string from semicolon-separated numbers.
396 for my $code (@codes) {
398 if (defined($ATTRIBUTES{$code})) {
399 $attribute .= $ATTRIBUTES{$code} . q{;};
400 } elsif (defined($ALIASES{$code})) {
401 $attribute .= $ALIASES{$code} . q{;};
403 croak("Invalid attribute name $code");
407 # We added one too many semicolons for simplicity. Remove the last one.
410 # Return undef if there were no attributes.
411 return ($attribute ne q{}) ? "\e[${attribute}m" : undef;
414 # Return a list of named color attributes for a given set of escape codes.
415 # Escape sequences can be given with or without enclosing "\e[" and "m". The
416 # empty escape sequence '' or "\e[m" gives an empty list of attrs.
418 # There is one special case. 256-color codes start with 38 or 48, followed by
419 # a 5 and then the 256-color code.
421 # @escapes - A list of escape sequences or escape sequence numbers
423 # Returns: An array of attribute names corresponding to those sequences
424 # Throws: Text exceptions on invalid escape sequences or unknown colors
429 # Walk the list of escapes and build a list of attribute numbers.
430 for my $escape (@escapes) {
431 $escape =~ s{ \A \e\[ }{}xms;
432 $escape =~ s{ m \z } {}xms;
433 my ($attrs) = $escape =~ m{ \A ((?:\d+;)* \d*) \z }xms;
434 if (!defined($attrs)) {
435 croak("Bad escape sequence $escape");
438 # Pull off 256-color codes (38;5;n or 48;5;n) as a unit.
439 push(@nums, $attrs =~ m{ ( 0*[34]8;0*5;\d+ | \d+ ) (?: ; | \z ) }xmsg);
442 # Now, walk the list of numbers and convert them to attribute names.
443 # Strip leading zeroes from any of the numbers. (xterm, at least, allows
444 # leading zeroes to be added to any number in an escape sequence.)
445 for my $num (@nums) {
446 $num =~ s{ ( \A | ; ) 0+ (\d) }{$1$2}xmsg;
447 my $name = $ATTRIBUTES_R{$num};
448 if (!defined($name)) {
449 croak("No name for escape sequence $num");
451 push(@result, $name);
454 # Return the attribute names.
458 # Given a string and a set of attributes, returns the string surrounded by
459 # escape codes to set those attributes and then clear them at the end of the
460 # string. The attributes can be given either as an array ref as the first
461 # argument or as a list as the second and subsequent arguments.
463 # If $EACHLINE is set, insert a reset before each occurrence of the string
464 # $EACHLINE and the starting attribute code after the string $EACHLINE, so
465 # that no attribute crosses line delimiters (this is often desirable if the
466 # output is to be piped to a pager or some other program).
468 # $first - An anonymous array of attributes or the text to color
469 # @rest - The text to color or the list of attributes
471 # Returns: The text, concatenated if necessary, surrounded by escapes to set
472 # the desired colors and reset them afterwards
473 # Throws: Text exception on invalid attributes
475 my ($first, @rest) = @_;
476 my ($string, @codes);
477 if (ref($first) && ref($first) eq 'ARRAY') {
479 $string = join(q{}, @rest);
485 # Return the string unmolested if colors are disabled.
486 if ($ENV{ANSI_COLORS_DISABLED}) {
490 # Find the attribute string for our colors.
491 my $attr = color(@codes);
493 # If $EACHLINE is defined, split the string on line boundaries, suppress
494 # empty segments, and then colorize each of the line sections.
495 if (defined($EACHLINE)) {
496 my @text = map { ($_ ne $EACHLINE) ? $attr . $_ . "\e[0m" : $_ }
498 split(m{ (\Q$EACHLINE\E) }xms, $string);
499 return join(q{}, @text);
501 return $attr . $string . "\e[0m";
505 # Define a new color alias, or return the value of an existing alias.
507 # $alias - The color alias to define
508 # $color - The standard color the alias will correspond to (optional)
510 # Returns: The standard color value of the alias
511 # undef if one argument was given and the alias was not recognized
512 # Throws: Text exceptions for invalid alias names, attempts to use a
513 # standard color name as an alias, or an unknown standard color name
515 my ($alias, $color) = @_;
516 if (!defined($color)) {
517 if (!exists $ALIASES{$alias}) {
520 return $ATTRIBUTES_R{ $ALIASES{$alias} };
524 # Avoid \w here to not load Unicode character tables, which increases the
525 # memory footprint of this module considerably.
527 ## no critic (RegularExpressions::ProhibitEnumeratedClasses)
528 if ($alias !~ m{ \A [a-zA-Z0-9._-]+ \z }xms) {
529 croak(qq{Invalid alias name "$alias"});
530 } elsif ($ATTRIBUTES{$alias}) {
531 croak(qq{Cannot alias standard color "$alias"});
532 } elsif (!exists $ATTRIBUTES{$color}) {
533 croak(qq{Invalid attribute name "$color"});
537 # Set the alias and return.
538 $ALIASES{$alias} = $ATTRIBUTES{$color};
542 # Given a string, strip the ANSI color codes out of that string and return the
543 # result. This removes only ANSI color codes, not movement codes and other
546 # @string - The list of strings to sanitize
548 # Returns: (array) The strings stripped of ANSI color escape sequences
549 # (scalar) The same, concatenated
552 for my $string (@string) {
553 $string =~ s{ \e\[ [\d;]* m }{}xmsg;
555 return wantarray ? @string : join(q{}, @string);
558 # Given a list of color attributes (arguments for color, for instance), return
559 # true if they're all valid or false if any of them are invalid.
561 # @codes - A list of color attributes, possibly space-separated
563 # Returns: True if all the attributes are valid, false otherwise.
566 @codes = map { split(q{ }, lc) } @codes;
567 for my $code (@codes) {
568 if (!(defined($ATTRIBUTES{$code}) || defined($ALIASES{$code}))) {
575 ##############################################################################
576 # Module return value and documentation
577 ##############################################################################
579 # Ensure we evaluate to true.
585 Term::ANSIColor - Color screen output using ANSI escape sequences
588 cyan colorize namespace runtime TMTOWTDI cmd.exe cmd.exe. 4nt.exe. 4nt.exe
589 command.com NT ESC Delvare SSH OpenSSH aixterm ECMA-048 Fraktur overlining
590 Zenin reimplemented Allbery PUSHCOLOR POPCOLOR LOCALCOLOR openmethods.com
591 openmethods.com. grey ATTR urxvt mistyped prepending Bareword filehandle
592 Cygwin Starsinic aterm rxvt CPAN RGB Solarized Whitespace alphanumerics
598 print color('bold blue');
599 print "This text is bold blue.\n";
600 print color('reset');
601 print "This text is normal.\n";
602 print colored("Yellow on magenta.", 'yellow on_magenta'), "\n";
603 print "This text is normal.\n";
604 print colored(['yellow on_magenta'], 'Yellow on magenta.', "\n");
605 print colored(['red on_bright_yellow'], 'Red on bright yellow.', "\n");
606 print colored(['bright_red on_black'], 'Bright red on black.', "\n");
609 # Map escape sequences back to color names.
610 use Term::ANSIColor 1.04 qw(uncolor);
611 my $names = uncolor('01;31');
612 print join(q{ }, @{$names}), "\n";
614 # Strip all color escape sequences.
615 use Term::ANSIColor 2.01 qw(colorstrip);
616 print colorstrip("\e[1mThis is bold\e[0m"), "\n";
618 # Determine whether a color is valid.
619 use Term::ANSIColor 2.02 qw(colorvalid);
620 my $valid = colorvalid('blue bold', 'on_magenta');
621 print "Color string is ", $valid ? "valid\n" : "invalid\n";
623 # Create new aliases for colors.
624 use Term::ANSIColor 4.00 qw(coloralias);
625 coloralias('alert', 'red');
626 print "Alert is ", coloralias('alert'), "\n";
627 print colored("This is in red.", 'alert'), "\n";
629 use Term::ANSIColor qw(:constants);
630 print BOLD, BLUE, "This text is in bold blue.\n", RESET;
632 use Term::ANSIColor qw(:constants);
634 local $Term::ANSIColor::AUTORESET = 1;
635 print BOLD BLUE "This text is in bold blue.\n";
636 print "This text is normal.\n";
639 use Term::ANSIColor 2.00 qw(:pushpop);
640 print PUSHCOLOR RED ON_GREEN "This text is red on green.\n";
641 print PUSHCOLOR BRIGHT_BLUE "This text is bright blue on green.\n";
642 print RESET BRIGHT_BLUE "This text is just bright blue.\n";
643 print POPCOLOR "Back to red on green.\n";
644 print LOCALCOLOR GREEN ON_BLUE "This text is green on blue.\n";
645 print "This text is red on green.\n";
647 local $Term::ANSIColor::AUTOLOCAL = 1;
648 print ON_BLUE "This text is red on blue.\n";
649 print "This text is red on green.\n";
651 print POPCOLOR "Back to whatever we started as.\n";
655 This module has two interfaces, one through color() and colored() and the
656 other through constants. It also offers the utility functions uncolor(),
657 colorstrip(), colorvalid(), and coloralias(), which have to be explicitly
658 imported to be used (see L</SYNOPSIS>).
660 See L</COMPATIBILITY> for the versions of Term::ANSIColor that introduced
661 particular features and the versions of Perl that included them.
663 =head2 Supported Colors
665 Terminal emulators that support color divide into three types: ones that
666 support only eight colors, ones that support sixteen, and ones that
667 support 256. This module provides the ANSI escape codes for all of them.
668 These colors are referred to as ANSI colors 0 through 7 (normal), 8
669 through 15 (16-color), and 16 through 255 (256-color).
671 Unfortunately, interpretation of colors 0 through 7 often depends on
672 whether the emulator supports eight colors or sixteen colors. Emulators
673 that only support eight colors (such as the Linux console) will display
674 colors 0 through 7 with normal brightness and ignore colors 8 through 15,
675 treating them the same as white. Emulators that support 16 colors, such
676 as gnome-terminal, normally display colors 0 through 7 as dim or darker
677 versions and colors 8 through 15 as normal brightness. On such emulators,
678 the "normal" white (color 7) usually is shown as pale grey, requiring
679 bright white (15) to be used to get a real white color. Bright black
680 usually is a dark grey color, although some terminals display it as pure
681 black. Some sixteen-color terminal emulators also treat normal yellow
682 (color 3) as orange or brown, and bright yellow (color 11) as yellow.
684 Following the normal convention of sixteen-color emulators, this module
685 provides a pair of attributes for each color. For every normal color (0
686 through 7), the corresponding bright color (8 through 15) is obtained by
687 prepending the string C<bright_> to the normal color name. For example,
688 C<red> is color 1 and C<bright_red> is color 9. The same applies for
689 background colors: C<on_red> is the normal color and C<on_bright_red> is
690 the bright color. Capitalize these strings for the constant interface.
692 For 256-color emulators, this module additionally provides C<ansi0>
693 through C<ansi15>, which are the same as colors 0 through 15 in
694 sixteen-color emulators but use the 256-color escape syntax, C<grey0>
695 through C<grey23> ranging from nearly black to nearly white, and a set of
696 RGB colors. The RGB colors are of the form C<rgbI<RGB>> where I<R>, I<G>,
697 and I<B> are numbers from 0 to 5 giving the intensity of red, green, and
698 blue. C<on_> variants of all of these colors are also provided. These
699 colors may be ignored completely on non-256-color terminals or may be
700 misinterpreted and produce random behavior. Additional attributes such as
701 blink, italic, or bold may not work with the 256-color palette.
703 There is unfortunately no way to know whether the current emulator
704 supports more than eight colors, which makes the choice of colors
705 difficult. The most conservative choice is to use only the regular
706 colors, which are at least displayed on all emulators. However, they will
707 appear dark in sixteen-color terminal emulators, including most common
708 emulators in UNIX X environments. If you know the display is one of those
709 emulators, you may wish to use the bright variants instead. Even better,
710 offer the user a way to configure the colors for a given application to
711 fit their terminal emulator.
713 =head2 Function Interface
715 The function interface uses attribute strings to describe the colors and
716 text attributes to assign to text. The recognized non-color attributes
717 are clear, reset, bold, dark, faint, italic, underline, underscore, blink,
718 reverse, and concealed. Clear and reset (reset to default attributes),
719 dark and faint (dim and saturated), and underline and underscore are
720 equivalent, so use whichever is the most intuitive to you.
722 Note that not all attributes are supported by all terminal types, and some
723 terminals may not support any of these sequences. Dark and faint, italic,
724 blink, and concealed in particular are frequently not implemented.
726 The recognized normal foreground color attributes (colors 0 to 7) are:
728 black red green yellow blue magenta cyan white
730 The corresponding bright foreground color attributes (colors 8 to 15) are:
732 bright_black bright_red bright_green bright_yellow
733 bright_blue bright_magenta bright_cyan bright_white
735 The recognized normal background color attributes (colors 0 to 7) are:
737 on_black on_red on_green on yellow
738 on_blue on_magenta on_cyan on_white
740 The recognized bright background color attributes (colors 8 to 15) are:
742 on_bright_black on_bright_red on_bright_green on_bright_yellow
743 on_bright_blue on_bright_magenta on_bright_cyan on_bright_white
745 For 256-color terminals, the recognized foreground colors are:
750 plus C<rgbI<RGB>> for I<R>, I<G>, and I<B> values from 0 to 5, such as
751 C<rgb000> or C<rgb515>. Similarly, the recognized background colors are:
753 on_ansi0 .. on_ansi15
754 on_grey0 .. on_grey23
756 plus C<on_rgbI<RGB>> for I<R>, I<G>, and I<B> values from 0 to 5.
758 For any of the above listed attributes, case is not significant.
760 Attributes, once set, last until they are unset (by printing the attribute
761 C<clear> or C<reset>). Be careful to do this, or otherwise your attribute
762 will last after your script is done running, and people get very annoyed
763 at having their prompt and typing changed to weird colors.
767 =item color(ATTR[, ATTR ...])
769 color() takes any number of strings as arguments and considers them to be
770 space-separated lists of attributes. It then forms and returns the escape
771 sequence to set those attributes. It doesn't print it out, just returns
772 it, so you'll have to print it yourself if you want to. This is so that
773 you can save it as a string, pass it to something else, send it to a file
774 handle, or do anything else with it that you might care to. color()
775 throws an exception if given an invalid attribute.
777 =item colored(STRING, ATTR[, ATTR ...])
779 =item colored(ATTR-REF, STRING[, STRING...])
781 As an aid in resetting colors, colored() takes a scalar as the first
782 argument and any number of attribute strings as the second argument and
783 returns the scalar wrapped in escape codes so that the attributes will be
784 set as requested before the string and reset to normal after the string.
785 Alternately, you can pass a reference to an array as the first argument,
786 and then the contents of that array will be taken as attributes and color
787 codes and the remainder of the arguments as text to colorize.
789 Normally, colored() just puts attribute codes at the beginning and end of
790 the string, but if you set $Term::ANSIColor::EACHLINE to some string, that
791 string will be considered the line delimiter and the attribute will be set
792 at the beginning of each line of the passed string and reset at the end of
793 each line. This is often desirable if the output contains newlines and
794 you're using background colors, since a background color that persists
795 across a newline is often interpreted by the terminal as providing the
796 default background color for the next line. Programs like pagers can also
797 be confused by attributes that span lines. Normally you'll want to set
798 $Term::ANSIColor::EACHLINE to C<"\n"> to use this feature.
800 =item uncolor(ESCAPE)
802 uncolor() performs the opposite translation as color(), turning escape
803 sequences into a list of strings corresponding to the attributes being set
806 =item colorstrip(STRING[, STRING ...])
808 colorstrip() removes all color escape sequences from the provided strings,
809 returning the modified strings separately in array context or joined
810 together in scalar context. Its arguments are not modified.
812 =item colorvalid(ATTR[, ATTR ...])
814 colorvalid() takes attribute strings the same as color() and returns true
815 if all attributes are known and false otherwise.
817 =item coloralias(ALIAS[, ATTR])
819 If ATTR is specified, coloralias() sets up an alias of ALIAS for the
820 standard color ATTR. From that point forward, ALIAS can be passed into
821 color(), colored(), and colorvalid() and will have the same meaning as
822 ATTR. One possible use of this facility is to give more meaningful names
823 to the 256-color RGB colors. Only ASCII alphanumerics, C<.>, C<_>, and
824 C<-> are allowed in alias names.
826 If ATTR is not specified, coloralias() returns the standard color name to
827 which ALIAS is aliased, if any, or undef if ALIAS does not exist.
829 This is the same facility used by the ANSI_COLORS_ALIASES environment
830 variable (see L</ENVIRONMENT> below) but can be used at runtime, not just
831 when the module is loaded.
833 Later invocations of coloralias() with the same ALIAS will override
834 earlier aliases. There is no way to remove an alias.
836 Aliases have no effect on the return value of uncolor().
838 B<WARNING>: Aliases are global and affect all callers in the same process.
839 There is no way to set an alias limited to a particular block of code or a
844 =head2 Constant Interface
846 Alternately, if you import C<:constants>, you can use the following
849 CLEAR RESET BOLD DARK
850 FAINT ITALIC UNDERLINE UNDERSCORE
851 BLINK REVERSE CONCEALED
853 BLACK RED GREEN YELLOW
854 BLUE MAGENTA CYAN WHITE
855 BRIGHT_BLACK BRIGHT_RED BRIGHT_GREEN BRIGHT_YELLOW
856 BRIGHT_BLUE BRIGHT_MAGENTA BRIGHT_CYAN BRIGHT_WHITE
858 ON_BLACK ON_RED ON_GREEN ON_YELLOW
859 ON_BLUE ON_MAGENTA ON_CYAN ON_WHITE
860 ON_BRIGHT_BLACK ON_BRIGHT_RED ON_BRIGHT_GREEN ON_BRIGHT_YELLOW
861 ON_BRIGHT_BLUE ON_BRIGHT_MAGENTA ON_BRIGHT_CYAN ON_BRIGHT_WHITE
863 These are the same as color('attribute') and can be used if you prefer
866 print BOLD BLUE ON_WHITE "Text", RESET, "\n";
870 print colored ("Text", 'bold blue on_white'), "\n";
872 (Note that the newline is kept separate to avoid confusing the terminal as
873 described above since a background color is being used.)
875 If you import C<:constants256>, you can use the following constants
881 RGBXYZ (for X, Y, and Z values from 0 to 5, like RGB000 or RGB515)
883 ON_ANSI0 .. ON_ANSI15
884 ON_GREY0 .. ON_GREY23
886 ON_RGBXYZ (for X, Y, and Z values from 0 to 5)
888 Note that C<:constants256> does not include the other constants, so if you
889 want to mix both, you need to include C<:constants> as well. You may want
890 to explicitly import at least C<RESET>, as in:
892 use Term::ANSIColor 4.00 qw(RESET :constants256);
894 When using the constants, if you don't want to have to remember to add the
895 C<, RESET> at the end of each print line, you can set
896 $Term::ANSIColor::AUTORESET to a true value. Then, the display mode will
897 automatically be reset if there is no comma after the constant. In other
898 words, with that variable set:
900 print BOLD BLUE "Text\n";
902 will reset the display mode afterward, whereas:
904 print BOLD, BLUE, "Text\n";
906 will not. If you are using background colors, you will probably want to
907 either use say() (in newer versions of Perl) or print the newline with a
908 separate print statement to avoid confusing the terminal.
910 If $Term::ANSIColor::AUTOLOCAL is set (see below), it takes precedence
911 over $Term::ANSIColor::AUTORESET, and the latter is ignored.
913 The subroutine interface has the advantage over the constants interface in
914 that only two subroutines are exported into your namespace, versus
915 thirty-eight in the constants interface. On the flip side, the constants
916 interface has the advantage of better compile time error checking, since
917 misspelled names of colors or attributes in calls to color() and colored()
918 won't be caught until runtime whereas misspelled names of constants will
919 be caught at compile time. So, pollute your namespace with almost two
920 dozen subroutines that you may not even use that often, or risk a silly
921 bug by mistyping an attribute. Your choice, TMTOWTDI after all.
923 =head2 The Color Stack
925 You can import C<:pushpop> and maintain a stack of colors using PUSHCOLOR,
926 POPCOLOR, and LOCALCOLOR. PUSHCOLOR takes the attribute string that
927 starts its argument and pushes it onto a stack of attributes. POPCOLOR
928 removes the top of the stack and restores the previous attributes set by
929 the argument of a prior PUSHCOLOR. LOCALCOLOR surrounds its argument in a
930 PUSHCOLOR and POPCOLOR so that the color resets afterward.
932 If $Term::ANSIColor::AUTOLOCAL is set, each sequence of color constants
933 will be implicitly preceded by LOCALCOLOR. In other words, the following:
936 local $Term::ANSIColor::AUTOLOCAL = 1;
942 print LOCALCOLOR BLUE "Text\n";
944 If $Term::ANSIColor::AUTOLOCAL is set, it takes precedence over
945 $Term::ANSIColor::AUTORESET, and the latter is ignored.
947 When using PUSHCOLOR, POPCOLOR, and LOCALCOLOR, it's particularly
948 important to not put commas between the constants.
950 print PUSHCOLOR BLUE "Text\n";
952 will correctly push BLUE onto the top of the stack.
954 print PUSHCOLOR, BLUE, "Text\n"; # wrong!
956 will not, and a subsequent pop won't restore the correct attributes.
957 PUSHCOLOR pushes the attributes set by its argument, which is normally a
958 string of color constants. It can't ask the terminal what the current
965 =item Bad color mapping %s
967 (W) The specified color mapping from ANSI_COLORS_ALIASES is not valid and
968 could not be parsed. It was ignored.
970 =item Bad escape sequence %s
972 (F) You passed an invalid ANSI escape sequence to uncolor().
974 =item Bareword "%s" not allowed while "strict subs" in use
976 (F) You probably mistyped a constant color name such as:
978 $Foobar = FOOBAR . "This line should be blue\n";
982 @Foobar = FOOBAR, "This line should be blue\n";
984 This will only show up under use strict (another good reason to run under
987 =item Cannot alias standard color %s
989 (F) The alias name passed to coloralias() matches a standard color name.
990 Standard color names cannot be aliased.
992 =item Cannot alias standard color %s in %s
994 (W) The same, but in ANSI_COLORS_ALIASES. The color mapping was ignored.
996 =item Invalid alias name %s
998 (F) You passed an invalid alias name to coloralias(). Alias names must
999 consist only of alphanumerics, C<.>, C<->, and C<_>.
1001 =item Invalid alias name %s in %s
1003 (W) You specified an invalid alias name on the left hand of the equal sign
1004 in a color mapping in ANSI_COLORS_ALIASES. The color mapping was ignored.
1006 =item Invalid attribute name %s
1008 (F) You passed an invalid attribute name to color(), colored(), or
1011 =item Invalid attribute name %s in %s
1013 (W) You specified an invalid attribute name on the right hand of the equal
1014 sign in a color mapping in ANSI_COLORS_ALIASES. The color mapping was
1017 =item Name "%s" used only once: possible typo
1019 (W) You probably mistyped a constant color name such as:
1021 print FOOBAR "This text is color FOOBAR\n";
1023 It's probably better to always use commas after constant names in order to
1024 force the next error.
1026 =item No comma allowed after filehandle
1028 (F) You probably mistyped a constant color name such as:
1030 print FOOBAR, "This text is color FOOBAR\n";
1032 Generating this fatal compile error is one of the main advantages of using
1033 the constants interface, since you'll immediately know if you mistype a
1036 =item No name for escape sequence %s
1038 (F) The ANSI escape sequence passed to uncolor() contains escapes which
1039 aren't recognized and can't be translated to names.
1047 =item ANSI_COLORS_ALIASES
1049 This environment variable allows the user to specify custom color aliases
1050 that will be understood by color(), colored(), and colorvalid(). None of
1051 the other functions will be affected, and no new color constants will be
1052 created. The custom colors are aliases for existing color names; no new
1053 escape sequences can be introduced. Only alphanumerics, C<.>, C<_>, and
1054 C<-> are allowed in alias names.
1058 ANSI_COLORS_ALIASES='newcolor1=oldcolor1,newcolor2=oldcolor2'
1060 Whitespace is ignored.
1062 For example the L<Solarized|http://ethanschoonover.com/solarized> colors
1065 ANSI_COLORS_ALIASES='\
1066 base00=bright_yellow, on_base00=on_bright_yellow,\
1067 base01=bright_green, on_base01=on_bright_green, \
1068 base02=black, on_base02=on_black, \
1069 base03=bright_black, on_base03=on_bright_black, \
1070 base0=bright_blue, on_base0=on_bright_blue, \
1071 base1=bright_cyan, on_base1=on_bright_cyan, \
1072 base2=white, on_base2=on_white, \
1073 base3=bright_white, on_base3=on_bright_white, \
1074 orange=bright_red, on_orange=on_bright_red, \
1075 violet=bright_magenta,on_violet=on_bright_magenta'
1077 This environment variable is read and applied when the Term::ANSIColor
1078 module is loaded and is then subsequently ignored. Changes to
1079 ANSI_COLORS_ALIASES after the module is loaded will have no effect. See
1080 coloralias() for an equivalent facility that can be used at runtime.
1082 =item ANSI_COLORS_DISABLED
1084 If this environment variable is set to a true value, all of the functions
1085 defined by this module (color(), colored(), and all of the constants not
1086 previously used in the program) will not output any escape sequences and
1087 instead will just return the empty string or pass through the original
1088 text as appropriate. This is intended to support easy use of scripts
1089 using this module on platforms that don't support ANSI escape sequences.
1093 =head1 COMPATIBILITY
1095 Term::ANSIColor was first included with Perl in Perl 5.6.0.
1097 The uncolor() function and support for ANSI_COLORS_DISABLED were added in
1098 Term::ANSIColor 1.04, included in Perl 5.8.0.
1100 Support for dark was added in Term::ANSIColor 1.08, included in Perl
1103 The color stack, including the C<:pushpop> import tag, PUSHCOLOR,
1104 POPCOLOR, LOCALCOLOR, and the $Term::ANSIColor::AUTOLOCAL variable, was
1105 added in Term::ANSIColor 2.00, included in Perl 5.10.1.
1107 colorstrip() was added in Term::ANSIColor 2.01 and colorvalid() was added
1108 in Term::ANSIColor 2.02, both included in Perl 5.11.0.
1110 Support for colors 8 through 15 (the C<bright_> variants) was added in
1111 Term::ANSIColor 3.00, included in Perl 5.13.3.
1113 Support for italic was added in Term::ANSIColor 3.02, included in Perl
1116 Support for colors 16 through 256 (the C<ansi>, C<rgb>, and C<grey>
1117 colors), the C<:constants256> import tag, the coloralias() function, and
1118 support for the ANSI_COLORS_ALIASES environment variable were added in
1119 Term::ANSIColor 4.00, included in Perl 5.17.8.
1121 $Term::ANSIColor::AUTOLOCAL was changed to take precedence over
1122 $Term::ANSIColor::AUTORESET, rather than the other way around, in
1123 Term::ANSIColor 4.00, included in Perl 5.17.8.
1127 It would be nice if one could leave off the commas around the constants
1128 entirely and just say:
1130 print BOLD BLUE ON_WHITE "Text\n" RESET;
1132 but the syntax of Perl doesn't allow this. You need a comma after the
1133 string. (Of course, you may consider it a bug that commas between all the
1134 constants aren't required, in which case you may feel free to insert
1135 commas unless you're using $Term::ANSIColor::AUTORESET or
1136 PUSHCOLOR/POPCOLOR.)
1138 For easier debugging, you may prefer to always use the commas when not
1139 setting $Term::ANSIColor::AUTORESET or PUSHCOLOR/POPCOLOR so that you'll
1140 get a fatal compile error rather than a warning.
1142 It's not possible to use this module to embed formatting and color
1143 attributes using Perl formats. They replace the escape character with a
1144 space (as documented in L<perlform(1)>), resulting in garbled output from
1145 the unrecognized attribute. Even if there were a way around that problem,
1146 the format doesn't know that the non-printing escape sequence is
1147 zero-length and would incorrectly format the output. For formatted output
1148 using color or other attributes, either use sprintf() instead or use
1149 formline() and then add the color or other attributes after formatting and
1154 The codes generated by this module are standard terminal control codes,
1155 complying with ECMA-048 and ISO 6429 (generally referred to as "ANSI
1156 color" for the color codes). The non-color control codes (bold, dark,
1157 italic, underline, and reverse) are part of the earlier ANSI X3.64
1158 standard for control sequences for video terminals and peripherals.
1160 Note that not all displays are ISO 6429-compliant, or even X3.64-compliant
1161 (or are even attempting to be so). This module will not work as expected
1162 on displays that do not honor these escape sequences, such as cmd.exe,
1163 4nt.exe, and command.com under either Windows NT or Windows 2000. They
1164 may just be ignored, or they may display as an ESC character followed by
1165 some apparent garbage.
1167 Jean Delvare provided the following table of different common terminal
1168 emulators and their support for the various attributes and others have
1169 helped me flesh it out:
1171 clear bold faint under blink reverse conceal
1172 ------------------------------------------------------------------------
1173 xterm yes yes no yes yes yes yes
1174 linux yes yes yes bold yes yes no
1175 rxvt yes yes no yes bold/black yes no
1176 dtterm yes yes yes yes reverse yes yes
1177 teraterm yes reverse no yes rev/red yes no
1178 aixterm kinda normal no yes no yes yes
1179 PuTTY yes color no yes no yes no
1180 Windows yes no no no no yes no
1181 Cygwin SSH yes yes no color color color yes
1182 Terminal.app yes yes no yes yes yes yes
1184 Windows is Windows telnet, Cygwin SSH is the OpenSSH implementation under
1185 Cygwin on Windows NT, and Mac Terminal is the Terminal application in Mac
1186 OS X. Where the entry is other than yes or no, that emulator displays the
1187 given attribute as something else instead. Note that on an aixterm, clear
1188 doesn't reset colors; you have to explicitly set the colors back to what
1189 you want. More entries in this table are welcome.
1191 Support for code 3 (italic) is rare and therefore not mentioned in that
1192 table. It is not believed to be fully supported by any of the terminals
1193 listed, although it's displayed as green in the Linux console, but it is
1194 reportedly supported by urxvt.
1196 Note that codes 6 (rapid blink) and 9 (strike-through) are specified in
1197 ANSI X3.64 and ECMA-048 but are not commonly supported by most displays
1198 and emulators and therefore aren't supported by this module at the present
1199 time. ECMA-048 also specifies a large number of other attributes,
1200 including a sequence of attributes for font changes, Fraktur characters,
1201 double-underlining, framing, circling, and overlining. As none of these
1202 attributes are widely supported or useful, they also aren't currently
1203 supported by this module.
1205 Most modern X terminal emulators support 256 colors. Known to not support
1206 those colors are aterm, rxvt, Terminal.app, and TTY/VC.
1210 Original idea (using constants) by Zenin, reimplemented using subs by Russ
1211 Allbery <rra@cpan.org>, and then combined with the original idea by
1212 Russ with input from Zenin. 256-color support is based on work by Kurt
1213 Starsinic. Russ Allbery now maintains this module.
1215 PUSHCOLOR, POPCOLOR, and LOCALCOLOR were contributed by openmethods.com
1218 =head1 COPYRIGHT AND LICENSE
1220 Copyright 1996 Zenin
1222 Copyright 1996, 1997, 1998, 2000, 2001, 2002, 2005, 2006, 2008, 2009, 2010,
1223 2011, 2012, 2013, 2014, 2015, 2016 Russ Allbery <rra@cpan.org>
1225 Copyright 2012 Kurt Starsinic <kstarsinic@gmail.com>
1227 This program is free software; you may redistribute it and/or modify it
1228 under the same terms as Perl itself.
1232 The CPAN module L<Term::ExtendedColor> provides a different and more
1233 comprehensive interface for 256-color emulators that may be more
1234 convenient. The CPAN module L<Win32::Console::ANSI> provides ANSI color
1235 (and other escape sequence) support in the Win32 Console environment.
1237 ECMA-048 is available on-line (at least at the time of this writing) at
1238 L<http://www.ecma-international.org/publications/standards/Ecma-048.htm>.
1240 ISO 6429 is available from ISO for a charge; the author of this module
1241 does not own a copy of it. Since the source material for ISO 6429 was
1242 ECMA-048 and the latter is available for free, there seems little reason
1243 to obtain the ISO standard.
1245 The 256-color control sequences are documented at
1246 L<http://invisible-island.net/xterm/ctlseqs/ctlseqs.html> (search for
1249 The current version of this module is always available from its web site
1250 at L<http://www.eyrie.org/~eagle/software/ansicolor/>. It is also part of
1251 the Perl core distribution as of 5.6.0.