1 # Term::ANSIColor -- Color screen output using ANSI escape sequences.
3 # Copyright 1996, 1997, 1998, 2000, 2001, 2002, 2005, 2006, 2008, 2009, 2010,
4 # 2011, 2012, 2013 Russ Allbery <rra@stanford.edu>
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;
29 # use Exporter plus @ISA instead of use base for 5.6 compatibility.
30 ## no critic (ClassHierarchies::ProhibitExplicitISA)
32 # Declare variables that should be set in BEGIN for robustness.
33 ## no critic (Modules::ProhibitAutomaticExportation)
34 our (@EXPORT, @EXPORT_OK, %EXPORT_TAGS, @ISA, $VERSION);
36 # We use autoloading, which sets this variable to the name of the called sub.
39 # Set $VERSION and everything export-related in a BEGIN block for robustness
40 # against circular module loading (not that we load any modules, but
41 # consistency is good).
45 # All of the basic supported constants, used in %EXPORT_TAGS.
48 FAINT ITALIC UNDERLINE UNDERSCORE
49 BLINK REVERSE CONCEALED
51 BLACK RED GREEN YELLOW
52 BLUE MAGENTA CYAN WHITE
53 ON_BLACK ON_RED ON_GREEN ON_YELLOW
54 ON_BLUE ON_MAGENTA ON_CYAN ON_WHITE
56 BRIGHT_BLACK BRIGHT_RED BRIGHT_GREEN BRIGHT_YELLOW
57 BRIGHT_BLUE BRIGHT_MAGENTA BRIGHT_CYAN BRIGHT_WHITE
58 ON_BRIGHT_BLACK ON_BRIGHT_RED ON_BRIGHT_GREEN ON_BRIGHT_YELLOW
59 ON_BRIGHT_BLUE ON_BRIGHT_MAGENTA ON_BRIGHT_CYAN ON_BRIGHT_WHITE
62 # 256-color constants, used in %EXPORT_TAGS.
63 ## no critic (ValuesAndExpressions::ProhibitMagicNumbers)
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.
147 ## no critic (ValuesAndExpressions::ProhibitMagicNumbers)
149 # The first 16 256-color codes are duplicates of the 16 ANSI colors,
150 # included for completeness.
151 for my $code (0 .. 15) {
152 $ATTRIBUTES{"ansi$code"} = "38;5;$code";
153 $ATTRIBUTES{"on_ansi$code"} = "48;5;$code";
156 # 256-color RGB colors. Red, green, and blue can each be values 0 through 5,
157 # and the resulting 216 colors start with color 16.
161 my $code = 16 + (6 * 6 * $r) + (6 * $g) + $b;
162 $ATTRIBUTES{"rgb$r$g$b"} = "38;5;$code";
163 $ATTRIBUTES{"on_rgb$r$g$b"} = "48;5;$code";
168 # The last 256-color codes are 24 shades of grey.
169 for my $n (0 .. 23) {
171 $ATTRIBUTES{"grey$n"} = "38;5;$code";
172 $ATTRIBUTES{"on_grey$n"} = "48;5;$code";
175 ## use critic (ValuesAndExpressions::ProhibitMagicNumbers)
177 # Reverse lookup. Alphabetically first name for a sequence is preferred.
179 for my $attr (reverse sort keys %ATTRIBUTES) {
180 $ATTRIBUTES_R{ $ATTRIBUTES{$attr} } = $attr;
183 # Import any custom colors set in the environment.
185 if (exists $ENV{ANSI_COLORS_ALIASES}) {
186 my $spec = $ENV{ANSI_COLORS_ALIASES};
187 $spec =~ s{\s+}{}xmsg;
189 # Error reporting here is an interesting question. Use warn rather than
190 # carp because carp would report the line of the use or require, which
191 # doesn't help anyone understand what's going on, whereas seeing this code
192 # will be more helpful.
193 ## no critic (ErrorHandling::RequireCarping)
194 for my $definition (split m{,}xms, $spec) {
195 my ($new, $old) = split m{=}xms, $definition, 2;
196 if (!$new || !$old) {
197 warn qq{Bad color mapping "$definition"};
199 my $result = eval { coloralias($new, $old) };
202 $error =~ s{ [ ] at [ ] .* }{}xms;
203 warn qq{$error in "$definition"};
209 # Stores the current color stack maintained by PUSHCOLOR and POPCOLOR. This
210 # is global and therefore not threadsafe.
213 ##############################################################################
214 # Implementation (constant form)
215 ##############################################################################
217 # Time to have fun! We now want to define the constant subs, which are named
218 # the same as the attributes above but in all caps. Each constant sub needs
219 # to act differently depending on whether $AUTORESET is set. Without
222 # BLUE "text\n" ==> "\e[34mtext\n"
224 # If $AUTORESET is set, we should instead get:
226 # BLUE "text\n" ==> "\e[34mtext\n\e[0m"
228 # The sub also needs to handle the case where it has no arguments correctly.
229 # Maintaining all of this as separate subs would be a major nightmare, as well
230 # as duplicate the %ATTRIBUTES hash, so instead we define an AUTOLOAD sub to
231 # define the constant subs on demand. To do that, we check the name of the
232 # called sub against the list of attributes, and if it's an all-caps version
233 # of one of them, we define the sub on the fly and then run it.
235 # If the environment variable ANSI_COLORS_DISABLED is set to a true value,
236 # just return the arguments without adding any escape sequences. This is to
237 # make it easier to write scripts that also work on systems without any ANSI
238 # support, like Windows consoles.
240 ## no critic (ClassHierarchies::ProhibitAutoloading)
241 ## no critic (Subroutines::RequireArgUnpacking)
243 my ($sub, $attr) = $AUTOLOAD =~ m{ \A ([\w:]*::([[:upper:]\d_]+)) \z }xms;
245 # Check if we were called with something that doesn't look like an
247 if (!$attr || !defined $ATTRIBUTES{ lc $attr }) {
248 croak("undefined subroutine &$AUTOLOAD called");
251 # If colors are disabled, just return the input. Do this without
252 # installing a sub for (marginal, unbenchmarked) speed.
253 if ($ENV{ANSI_COLORS_DISABLED}) {
257 # We've untainted the name of the sub.
260 # Figure out the ANSI string to set the desired attribute.
261 my $escape = "\e[" . $ATTRIBUTES{ lc $attr } . 'm';
263 # Save the current value of $@. We can't just use local since we want to
264 # restore it before dispatching to the newly-created sub. (The caller may
265 # be colorizing output that includes $@.)
268 # Generate the constant sub, which should still recognize some of our
269 # package variables. Use string eval to avoid a dependency on
270 # Sub::Install, even though it makes it somewhat less readable.
271 ## no critic (BuiltinFunctions::ProhibitStringyEval)
272 ## no critic (ValuesAndExpressions::ProhibitImplicitNewlines)
273 my $eval_result = eval qq{
275 if (\$ENV{ANSI_COLORS_DISABLED}) {
276 return join q{}, \@_;
277 } elsif (\$AUTOLOCAL && \@_) {
278 return PUSHCOLOR('$escape') . join(q{}, \@_) . POPCOLOR;
279 } elsif (\$AUTORESET && \@_) {
280 return '$escape' . join(q{}, \@_) . "\e[0m";
282 return '$escape' . join q{}, \@_;
288 # Failure is an internal error, not a problem with the caller.
289 ## no critic (ErrorHandling::RequireCarping)
291 die "failed to generate constant $attr: $@";
295 ## no critic (Variables::RequireLocalizedPunctuationVars)
298 # Dispatch to the newly-created sub.
299 ## no critic (References::ProhibitDoubleSigils)
302 ## use critic (Subroutines::RequireArgUnpacking)
304 # Append a new color to the top of the color stack and return the top of
307 # $text - Any text we're applying colors to, with color escapes prepended
309 # Returns: The text passed in
312 my $text = join q{}, @text;
314 # Extract any number of color-setting escape sequences from the start of
316 my ($color) = $text =~ m{ \A ( (?:\e\[ [\d;]+ m)+ ) }xms;
318 # If we already have a stack, append these escapes to the set from the top
319 # of the stack. This way, each position in the stack stores the complete
320 # enabled colors for that stage, at the cost of some potential
323 $color = $COLORSTACK[-1] . $color;
326 # Push the color onto the stack.
327 push @COLORSTACK, $color;
331 # Pop the color stack and return the new top of the stack (or reset, if
332 # the stack is empty).
334 # @text - Any text we're applying colors to
336 # Returns: The concatenation of @text prepended with the new stack color
341 return $COLORSTACK[-1] . join q{}, @text;
347 # Surround arguments with a push and a pop. The effect will be to reset the
348 # colors to whatever was on the color stack before this sequence of colors was
351 # @text - Any text we're applying colors to
353 # Returns: The concatenation of the text and the proper color reset sequence.
356 return PUSHCOLOR(join q{}, @text) . POPCOLOR();
359 ##############################################################################
360 # Implementation (attribute string form)
361 ##############################################################################
363 # Return the escape code for a given set of color attributes.
365 # @codes - A list of possibly space-separated color attributes
367 # Returns: The escape sequence setting those color attributes
368 # undef if no escape sequences were given
369 # Throws: Text exception for any invalid attribute
372 @codes = map { split } @codes;
374 # Return the empty string if colors are disabled.
375 if ($ENV{ANSI_COLORS_DISABLED}) {
379 # Build the attribute string from semicolon-separated numbers.
381 for my $code (@codes) {
383 if (defined $ATTRIBUTES{$code}) {
384 $attribute .= $ATTRIBUTES{$code} . q{;};
385 } elsif (defined $ALIASES{$code}) {
386 $attribute .= $ALIASES{$code} . q{;};
388 croak("Invalid attribute name $code");
392 # We added one too many semicolons for simplicity. Remove the last one.
395 # Return undef if there were no attributes.
396 return ($attribute ne q{}) ? "\e[${attribute}m" : undef;
399 # Return a list of named color attributes for a given set of escape codes.
400 # Escape sequences can be given with or without enclosing "\e[" and "m". The
401 # empty escape sequence '' or "\e[m" gives an empty list of attrs.
403 # There is one special case. 256-color codes start with 38 or 48, followed by
404 # a 5 and then the 256-color code.
406 # @escapes - A list of escape sequences or escape sequence numbers
408 # Returns: An array of attribute names corresponding to those sequences
409 # Throws: Text exceptions on invalid escape sequences or unknown colors
414 # Walk the list of escapes and build a list of attribute numbers.
415 for my $escape (@escapes) {
416 $escape =~ s{ \A \e\[ }{}xms;
417 $escape =~ s{ m \z } {}xms;
418 my ($attrs) = $escape =~ m{ \A ((?:\d+;)* \d*) \z }xms;
419 if (!defined $attrs) {
420 croak("Bad escape sequence $escape");
423 # Pull off 256-color codes (38;5;n or 48;5;n) as a unit.
424 push @nums, $attrs =~ m{ ( 0*[34]8;0*5;\d+ | \d+ ) (?: ; | \z ) }xmsg;
427 # Now, walk the list of numbers and convert them to attribute names.
428 # Strip leading zeroes from any of the numbers. (xterm, at least, allows
429 # leading zeroes to be added to any number in an escape sequence.)
430 for my $num (@nums) {
431 $num =~ s{ ( \A | ; ) 0+ (\d) }{$1$2}xmsg;
432 my $name = $ATTRIBUTES_R{$num};
433 if (!defined $name) {
434 croak("No name for escape sequence $num");
439 # Return the attribute names.
443 # Given a string and a set of attributes, returns the string surrounded by
444 # escape codes to set those attributes and then clear them at the end of the
445 # string. The attributes can be given either as an array ref as the first
446 # argument or as a list as the second and subsequent arguments.
448 # If $EACHLINE is set, insert a reset before each occurrence of the string
449 # $EACHLINE and the starting attribute code after the string $EACHLINE, so
450 # that no attribute crosses line delimiters (this is often desirable if the
451 # output is to be piped to a pager or some other program).
453 # $first - An anonymous array of attributes or the text to color
454 # @rest - The text to color or the list of attributes
456 # Returns: The text, concatenated if necessary, surrounded by escapes to set
457 # the desired colors and reset them afterwards
458 # Throws: Text exception on invalid attributes
460 my ($first, @rest) = @_;
461 my ($string, @codes);
462 if (ref($first) && ref($first) eq 'ARRAY') {
464 $string = join q{}, @rest;
470 # Return the string unmolested if colors are disabled.
471 if ($ENV{ANSI_COLORS_DISABLED}) {
475 # Find the attribute string for our colors.
476 my $attr = color(@codes);
478 # If $EACHLINE is defined, split the string on line boundaries, suppress
479 # empty segments, and then colorize each of the line sections.
480 if (defined $EACHLINE) {
481 my @text = map { ($_ ne $EACHLINE) ? $attr . $_ . "\e[0m" : $_ }
482 grep { length($_) > 0 }
483 split m{ (\Q$EACHLINE\E) }xms, $string;
484 return join q{}, @text;
486 return $attr . $string . "\e[0m";
490 # Define a new color alias, or return the value of an existing alias.
492 # $alias - The color alias to define
493 # $color - The standard color the alias will correspond to (optional)
495 # Returns: The standard color value of the alias
496 # undef if one argument was given and the alias was not recognized
497 # Throws: Text exceptions for invalid alias names, attempts to use a
498 # standard color name as an alias, or an unknown standard color name
500 my ($alias, $color) = @_;
501 if (!defined $color) {
502 if (!exists $ALIASES{$alias}) {
505 return $ATTRIBUTES_R{ $ALIASES{$alias} };
508 if ($alias !~ m{ \A [\w._-]+ \z }xms) {
509 croak(qq{Invalid alias name "$alias"});
510 } elsif ($ATTRIBUTES{$alias}) {
511 croak(qq{Cannot alias standard color "$alias"});
512 } elsif (!exists $ATTRIBUTES{$color}) {
513 croak(qq{Invalid attribute name "$color"});
515 $ALIASES{$alias} = $ATTRIBUTES{$color};
519 # Given a string, strip the ANSI color codes out of that string and return the
520 # result. This removes only ANSI color codes, not movement codes and other
523 # @string - The list of strings to sanitize
525 # Returns: (array) The strings stripped of ANSI color escape sequences
526 # (scalar) The same, concatenated
529 for my $string (@string) {
530 $string =~ s{ \e\[ [\d;]* m }{}xmsg;
532 return wantarray ? @string : join q{}, @string;
535 # Given a list of color attributes (arguments for color, for instance), return
536 # true if they're all valid or false if any of them are invalid.
538 # @codes - A list of color attributes, possibly space-separated
540 # Returns: True if all the attributes are valid, false otherwise.
543 @codes = map { split q{ }, lc $_ } @codes;
544 for my $code (@codes) {
545 if (!defined $ATTRIBUTES{$code} && !defined $ALIASES{$code}) {
552 ##############################################################################
553 # Module return value and documentation
554 ##############################################################################
556 # Ensure we evaluate to true.
562 Term::ANSIColor - Color screen output using ANSI escape sequences
565 cyan colorize namespace runtime TMTOWTDI cmd.exe 4nt.exe command.com NT
566 ESC Delvare SSH OpenSSH aixterm ECMA-048 Fraktur overlining Zenin
567 reimplemented Allbery PUSHCOLOR POPCOLOR LOCALCOLOR openmethods.com
568 grey ATTR urxvt mistyped prepending Bareword filehandle Cygwin Starsinic
569 aterm rxvt CPAN RGB Solarized Whitespace alphanumerics undef
574 print color 'bold blue';
575 print "This text is bold blue.\n";
577 print "This text is normal.\n";
578 print colored("Yellow on magenta.", 'yellow on_magenta'), "\n";
579 print "This text is normal.\n";
580 print colored ['yellow on_magenta'], 'Yellow on magenta.', "\n";
581 print colored ['red on_bright_yellow'], 'Red on bright yellow.', "\n";
582 print colored ['bright_red on_black'], 'Bright red on black.', "\n";
585 # Map escape sequences back to color names.
586 use Term::ANSIColor 1.04 qw(uncolor);
587 my $names = uncolor('01;31');
588 print join(q{ }, @{$names}), "\n";
590 # Strip all color escape sequences.
591 use Term::ANSIColor 2.01 qw(colorstrip);
592 print colorstrip '\e[1mThis is bold\e[0m', "\n";
594 # Determine whether a color is valid.
595 use Term::ANSIColor 2.02 qw(colorvalid);
596 my $valid = colorvalid('blue bold', 'on_magenta');
597 print "Color string is ", $valid ? "valid\n" : "invalid\n";
599 # Create new aliases for colors.
600 use Term::ANSIColor 4.00 qw(coloralias);
601 coloralias('alert', 'red');
602 print "Alert is ", coloralias('alert'), "\n";
603 print colored("This is in red.", 'alert'), "\n";
605 use Term::ANSIColor qw(:constants);
606 print BOLD, BLUE, "This text is in bold blue.\n", RESET;
608 use Term::ANSIColor qw(:constants);
610 local $Term::ANSIColor::AUTORESET = 1;
611 print BOLD BLUE "This text is in bold blue.\n";
612 print "This text is normal.\n";
615 use Term::ANSIColor 2.00 qw(:pushpop);
616 print PUSHCOLOR RED ON_GREEN "This text is red on green.\n";
617 print PUSHCOLOR BRIGHT_BLUE "This text is bright blue on green.\n";
618 print RESET BRIGHT_BLUE "This text is just bright blue.\n";
619 print POPCOLOR "Back to red on green.\n";
620 print LOCALCOLOR GREEN ON_BLUE "This text is green on blue.\n";
621 print "This text is red on green.\n";
623 local $Term::ANSIColor::AUTOLOCAL = 1;
624 print ON_BLUE "This text is red on blue.\n";
625 print "This text is red on green.\n";
627 print POPCOLOR "Back to whatever we started as.\n";
631 This module has two interfaces, one through color() and colored() and the
632 other through constants. It also offers the utility functions uncolor(),
633 colorstrip(), colorvalid(), and coloralias(), which have to be explicitly
634 imported to be used (see L</SYNOPSIS>).
636 See L</COMPATIBILITY> for the versions of Term::ANSIColor that introduced
637 particular features and the versions of Perl that included them.
639 =head2 Supported Colors
641 Terminal emulators that support color divide into two types: ones that
642 support only eight colors, ones that support sixteen, and ones that
643 support 256. This module provides the ANSI escape codes all of them.
644 These colors are referred to as ANSI colors 0 through 7 (normal), 8
645 through 15 (16-color), and 16 through 255 (256-color).
647 Unfortunately, interpretation of colors 0 through 7 often depends on
648 whether the emulator supports eight colors or sixteen colors. Emulators
649 that only support eight colors (such as the Linux console) will display
650 colors 0 through 7 with normal brightness and ignore colors 8 through 15,
651 treating them the same as white. Emulators that support 16 colors, such
652 as gnome-terminal, normally display colors 0 through 7 as dim or darker
653 versions and colors 8 through 15 as normal brightness. On such emulators,
654 the "normal" white (color 7) usually is shown as pale grey, requiring
655 bright white (15) to be used to get a real white color. Bright black
656 usually is a dark grey color, although some terminals display it as pure
657 black. Some sixteen-color terminal emulators also treat normal yellow
658 (color 3) as orange or brown, and bright yellow (color 11) as yellow.
660 Following the normal convention of sixteen-color emulators, this module
661 provides a pair of attributes for each color. For every normal color (0
662 through 7), the corresponding bright color (8 through 15) is obtained by
663 prepending the string C<bright_> to the normal color name. For example,
664 C<red> is color 1 and C<bright_red> is color 9. The same applies for
665 background colors: C<on_red> is the normal color and C<on_bright_red> is
666 the bright color. Capitalize these strings for the constant interface.
668 For 256-color emulators, this module additionally provides C<ansi0>
669 through C<ansi15>, which are the same as colors 0 through 15 in
670 sixteen-color emulators but use the 256-color escape syntax, C<grey0>
671 through C<grey23> ranging from nearly black to nearly white, and a set of
672 RGB colors. The RGB colors are of the form C<rgbI<RGB>> where I<R>, I<G>,
673 and I<B> are numbers from 0 to 5 giving the intensity of red, green, and
674 blue. C<on_> variants of all of these colors are also provided. These
675 colors may be ignored completely on non-256-color terminals or may be
676 misinterpreted and produce random behavior. Additional attributes such as
677 blink, italic, or bold may not work with the 256-color palette.
679 There is unfortunately no way to know whether the current emulator
680 supports more than eight colors, which makes the choice of colors
681 difficult. The most conservative choice is to use only the regular
682 colors, which are at least displayed on all emulators. However, they will
683 appear dark in sixteen-color terminal emulators, including most common
684 emulators in UNIX X environments. If you know the display is one of those
685 emulators, you may wish to use the bright variants instead. Even better,
686 offer the user a way to configure the colors for a given application to
687 fit their terminal emulator.
689 =head2 Function Interface
691 The function interface uses attribute strings to describe the colors and
692 text attributes to assign to text. The recognized non-color attributes
693 are clear, reset, bold, dark, faint, italic, underline, underscore, blink,
694 reverse, and concealed. Clear and reset (reset to default attributes),
695 dark and faint (dim and saturated), and underline and underscore are
696 equivalent, so use whichever is the most intuitive to you.
698 Note that not all attributes are supported by all terminal types, and some
699 terminals may not support any of these sequences. Dark and faint, italic,
700 blink, and concealed in particular are frequently not implemented.
702 The recognized normal foreground color attributes (colors 0 to 7) are:
704 black red green yellow blue magenta cyan white
706 The corresponding bright foreground color attributes (colors 8 to 15) are:
708 bright_black bright_red bright_green bright_yellow
709 bright_blue bright_magenta bright_cyan bright_white
711 The recognized normal background color attributes (colors 0 to 7) are:
713 on_black on_red on_green on yellow
714 on_blue on_magenta on_cyan on_white
716 The recognized bright background color attributes (colors 8 to 15) are:
718 on_bright_black on_bright_red on_bright_green on_bright_yellow
719 on_bright_blue on_bright_magenta on_bright_cyan on_bright_white
721 For 256-color terminals, the recognized foreground colors are:
726 plus C<rgbI<RGB>> for I<R>, I<G>, and I<B> values from 0 to 5, such as
727 C<rgb000> or C<rgb515>. Similarly, the recognized background colors are:
729 on_ansi0 .. on_ansi15
730 on_grey0 .. on_grey23
732 plus C<on_rgbI<RGB>> for for I<R>, I<G>, and I<B> values from 0 to 5.
734 For any of the above listed attributes, case is not significant.
736 Attributes, once set, last until they are unset (by printing the attribute
737 C<clear> or C<reset>). Be careful to do this, or otherwise your attribute
738 will last after your script is done running, and people get very annoyed
739 at having their prompt and typing changed to weird colors.
743 =item color(ATTR[, ATTR ...])
745 color() takes any number of strings as arguments and considers them to be
746 space-separated lists of attributes. It then forms and returns the escape
747 sequence to set those attributes. It doesn't print it out, just returns
748 it, so you'll have to print it yourself if you want to. This is so that
749 you can save it as a string, pass it to something else, send it to a file
750 handle, or do anything else with it that you might care to. color()
751 throws an exception if given an invalid attribute.
753 =item colored(STRING, ATTR[, ATTR ...])
755 =item colored(ATTR-REF, STRING[, STRING...])
757 As an aid in resetting colors, colored() takes a scalar as the first
758 argument and any number of attribute strings as the second argument and
759 returns the scalar wrapped in escape codes so that the attributes will be
760 set as requested before the string and reset to normal after the string.
761 Alternately, you can pass a reference to an array as the first argument,
762 and then the contents of that array will be taken as attributes and color
763 codes and the remainder of the arguments as text to colorize.
765 Normally, colored() just puts attribute codes at the beginning and end of
766 the string, but if you set $Term::ANSIColor::EACHLINE to some string, that
767 string will be considered the line delimiter and the attribute will be set
768 at the beginning of each line of the passed string and reset at the end of
769 each line. This is often desirable if the output contains newlines and
770 you're using background colors, since a background color that persists
771 across a newline is often interpreted by the terminal as providing the
772 default background color for the next line. Programs like pagers can also
773 be confused by attributes that span lines. Normally you'll want to set
774 $Term::ANSIColor::EACHLINE to C<"\n"> to use this feature.
776 =item uncolor(ESCAPE)
778 uncolor() performs the opposite translation as color(), turning escape
779 sequences into a list of strings corresponding to the attributes being set
782 =item colorstrip(STRING[, STRING ...])
784 colorstrip() removes all color escape sequences from the provided strings,
785 returning the modified strings separately in array context or joined
786 together in scalar context. Its arguments are not modified.
788 =item colorvalid(ATTR[, ATTR ...])
790 colorvalid() takes attribute strings the same as color() and returns true
791 if all attributes are known and false otherwise.
793 =item coloralias(ALIAS[, ATTR])
795 If ATTR is specified, coloralias() sets up an alias of ALIAS for the
796 standard color ATTR. From that point forward, ALIAS can be passed into
797 color(), colored(), and colorvalid() and will have the same meaning as
798 ATTR. One possible use of this facility is to give more meaningful names
799 to the 256-color RGB colors. Only alphanumerics, C<.>, C<_>, and C<-> are
800 allowed in alias names.
802 If ATTR is not specified, coloralias() returns the standard color name to
803 which ALIAS is aliased, if any, or undef if ALIAS does not exist.
805 This is the same facility used by the ANSI_COLORS_ALIASES environment
806 variable (see L</ENVIRONMENT> below) but can be used at runtime, not just
807 when the module is loaded.
809 Later invocations of coloralias() with the same ALIAS will override
810 earlier aliases. There is no way to remove an alias.
812 Aliases have no effect on the return value of uncolor().
814 B<WARNING>: Aliases are global and affect all callers in the same process.
815 There is no way to set an alias limited to a particular block of code or a
820 =head2 Constant Interface
822 Alternately, if you import C<:constants>, you can use the following
825 CLEAR RESET BOLD DARK
826 FAINT ITALIC UNDERLINE UNDERSCORE
827 BLINK REVERSE CONCEALED
829 BLACK RED GREEN YELLOW
830 BLUE MAGENTA CYAN WHITE
831 BRIGHT_BLACK BRIGHT_RED BRIGHT_GREEN BRIGHT_YELLOW
832 BRIGHT_BLUE BRIGHT_MAGENTA BRIGHT_CYAN BRIGHT_WHITE
834 ON_BLACK ON_RED ON_GREEN ON_YELLOW
835 ON_BLUE ON_MAGENTA ON_CYAN ON_WHITE
836 ON_BRIGHT_BLACK ON_BRIGHT_RED ON_BRIGHT_GREEN ON_BRIGHT_YELLOW
837 ON_BRIGHT_BLUE ON_BRIGHT_MAGENTA ON_BRIGHT_CYAN ON_BRIGHT_WHITE
839 These are the same as color('attribute') and can be used if you prefer
842 print BOLD BLUE ON_WHITE "Text", RESET, "\n";
846 print colored ("Text", 'bold blue on_white'), "\n";
848 (Note that the newline is kept separate to avoid confusing the terminal as
849 described above since a background color is being used.)
851 If you import C<:constants256>, you can use the following constants
857 RGBXYZ (for X, Y, and Z values from 0 to 5, like RGB000 or RGB515)
859 ON_ANSI0 .. ON_ANSI15
860 ON_GREY0 .. ON_GREY23
862 ON_RGBXYZ (for X, Y, and Z values from 0 to 5)
864 Note that C<:constants256> does not include the other constants, so if you
865 want to mix both, you need to include C<:constants> as well. You may want
866 to explicitly import at least C<RESET>, as in:
868 use Term::ANSIColor 4.00 qw(RESET :constants256);
870 When using the constants, if you don't want to have to remember to add the
871 C<, RESET> at the end of each print line, you can set
872 $Term::ANSIColor::AUTORESET to a true value. Then, the display mode will
873 automatically be reset if there is no comma after the constant. In other
874 words, with that variable set:
876 print BOLD BLUE "Text\n";
878 will reset the display mode afterward, whereas:
880 print BOLD, BLUE, "Text\n";
882 will not. If you are using background colors, you will probably want to
883 either use say() (in newer versions of Perl) or print the newline with a
884 separate print statement to avoid confusing the terminal.
886 If $Term::ANSIColor::AUTOLOCAL is set (see below), it takes precedence
887 over $Term::ANSIColor::AUTORESET, and the latter is ignored.
889 The subroutine interface has the advantage over the constants interface in
890 that only two subroutines are exported into your namespace, versus
891 thirty-eight in the constants interface. On the flip side, the constants
892 interface has the advantage of better compile time error checking, since
893 misspelled names of colors or attributes in calls to color() and colored()
894 won't be caught until runtime whereas misspelled names of constants will
895 be caught at compile time. So, pollute your namespace with almost two
896 dozen subroutines that you may not even use that often, or risk a silly
897 bug by mistyping an attribute. Your choice, TMTOWTDI after all.
899 =head2 The Color Stack
901 You can import C<:pushpop> and maintain a stack of colors using PUSHCOLOR,
902 POPCOLOR, and LOCALCOLOR. PUSHCOLOR takes the attribute string that
903 starts its argument and pushes it onto a stack of attributes. POPCOLOR
904 removes the top of the stack and restores the previous attributes set by
905 the argument of a prior PUSHCOLOR. LOCALCOLOR surrounds its argument in a
906 PUSHCOLOR and POPCOLOR so that the color resets afterward.
908 If $Term::ANSIColor::AUTOLOCAL is set, each sequence of color constants
909 will be implicitly preceded by LOCALCOLOR. In other words, the following:
912 local $Term::ANSIColor::AUTOLOCAL = 1;
918 print LOCALCOLOR BLUE "Text\n";
920 If $Term::ANSIColor::AUTOLOCAL is set, it takes precedence over
921 $Term::ANSIColor::AUTORESET, and the latter is ignored.
923 When using PUSHCOLOR, POPCOLOR, and LOCALCOLOR, it's particularly
924 important to not put commas between the constants.
926 print PUSHCOLOR BLUE "Text\n";
928 will correctly push BLUE onto the top of the stack.
930 print PUSHCOLOR, BLUE, "Text\n"; # wrong!
932 will not, and a subsequent pop won't restore the correct attributes.
933 PUSHCOLOR pushes the attributes set by its argument, which is normally a
934 string of color constants. It can't ask the terminal what the current
941 =item Bad color mapping %s
943 (W) The specified color mapping from ANSI_COLORS_ALIASES is not valid and
944 could not be parsed. It was ignored.
946 =item Bad escape sequence %s
948 (F) You passed an invalid ANSI escape sequence to uncolor().
950 =item Bareword "%s" not allowed while "strict subs" in use
952 (F) You probably mistyped a constant color name such as:
954 $Foobar = FOOBAR . "This line should be blue\n";
958 @Foobar = FOOBAR, "This line should be blue\n";
960 This will only show up under use strict (another good reason to run under
963 =item Cannot alias standard color %s
965 (F) The alias name passed to coloralias() matches a standard color name.
966 Standard color names cannot be aliased.
968 =item Cannot alias standard color %s in %s
970 (W) The same, but in ANSI_COLORS_ALIASES. The color mapping was ignored.
972 =item Invalid alias name %s
974 (F) You passed an invalid alias name to coloralias(). Alias names must
975 consist only of alphanumerics, C<.>, C<->, and C<_>.
977 =item Invalid alias name %s in %s
979 (W) You specified an invalid alias name on the left hand of the equal sign
980 in a color mapping in ANSI_COLORS_ALIASES. The color mapping was ignored.
982 =item Invalid attribute name %s
984 (F) You passed an invalid attribute name to color(), colored(), or
987 =item Invalid attribute name %s in %s
989 (W) You specified an invalid attribute name on the right hand of the equal
990 sign in a color mapping in ANSI_COLORS_ALIASES. The color mapping was
993 =item Name "%s" used only once: possible typo
995 (W) You probably mistyped a constant color name such as:
997 print FOOBAR "This text is color FOOBAR\n";
999 It's probably better to always use commas after constant names in order to
1000 force the next error.
1002 =item No comma allowed after filehandle
1004 (F) You probably mistyped a constant color name such as:
1006 print FOOBAR, "This text is color FOOBAR\n";
1008 Generating this fatal compile error is one of the main advantages of using
1009 the constants interface, since you'll immediately know if you mistype a
1012 =item No name for escape sequence %s
1014 (F) The ANSI escape sequence passed to uncolor() contains escapes which
1015 aren't recognized and can't be translated to names.
1023 =item ANSI_COLORS_ALIASES
1025 This environment variable allows the user to specify custom color aliases
1026 that will be understood by color(), colored(), and colorvalid(). None of
1027 the other functions will be affected, and no new color constants will be
1028 created. The custom colors are aliases for existing color names; no new
1029 escape sequences can be introduced. Only alphanumerics, C<.>, C<_>, and
1030 C<-> are allowed in alias names.
1034 ANSI_COLORS_ALIASES='newcolor1=oldcolor1,newcolor2=oldcolor2'
1036 Whitespace is ignored.
1038 For example the L<Solarized|http://ethanschoonover.com/solarized> colors
1041 ANSI_COLORS_ALIASES='\
1042 base00=bright_yellow, on_base00=on_bright_yellow,\
1043 base01=bright_green, on_base01=on_bright_green, \
1044 base02=black, on_base02=on_black, \
1045 base03=bright_black, on_base03=on_bright_black, \
1046 base0=bright_blue, on_base0=on_bright_blue, \
1047 base1=bright_cyan, on_base1=on_bright_cyan, \
1048 base2=white, on_base2=on_white, \
1049 base3=bright_white, on_base3=on_bright_white, \
1050 orange=bright_red, on_orange=on_bright_red, \
1051 violet=bright_magenta,on_violet=on_bright_magenta'
1053 This environment variable is read and applied when the Term::ANSIColor
1054 module is loaded and is then subsequently ignored. Changes to
1055 ANSI_COLORS_ALIASES after the module is loaded will have no effect. See
1056 coloralias() for an equivalent facility that can be used at runtime.
1058 =item ANSI_COLORS_DISABLED
1060 If this environment variable is set to a true value, all of the functions
1061 defined by this module (color(), colored(), and all of the constants not
1062 previously used in the program) will not output any escape sequences and
1063 instead will just return the empty string or pass through the original
1064 text as appropriate. This is intended to support easy use of scripts
1065 using this module on platforms that don't support ANSI escape sequences.
1069 =head1 COMPATIBILITY
1071 Term::ANSIColor was first included with Perl in Perl 5.6.0.
1073 The uncolor() function and support for ANSI_COLORS_DISABLED were added in
1074 Term::ANSIColor 1.04, included in Perl 5.8.0.
1076 Support for dark was added in Term::ANSIColor 1.08, included in Perl
1079 The color stack, including the C<:pushpop> import tag, PUSHCOLOR,
1080 POPCOLOR, LOCALCOLOR, and the $Term::ANSIColor::AUTOLOCAL variable, was
1081 added in Term::ANSIColor 2.00, included in Perl 5.10.1.
1083 colorstrip() was added in Term::ANSIColor 2.01 and colorvalid() was added
1084 in Term::ANSIColor 2.02, both included in Perl 5.11.0.
1086 Support for colors 8 through 15 (the C<bright_> variants) was added in
1087 Term::ANSIColor 3.00, included in Perl 5.13.3.
1089 Support for italic was added in Term::ANSIColor 3.02, included in Perl
1092 Support for colors 16 through 256 (the C<ansi>, C<rgb>, and C<grey>
1093 colors), the C<:constants256> import tag, the coloralias() function, and
1094 support for the ANSI_COLORS_ALIASES environment variable were added in
1095 Term::ANSIColor 4.00.
1097 $Term::ANSIColor::AUTOLOCAL was changed to take precedence over
1098 $Term::ANSIColor::AUTORESET, rather than the other way around, in
1099 Term::ANSIColor 4.00.
1103 It would be nice if one could leave off the commas around the constants
1104 entirely and just say:
1106 print BOLD BLUE ON_WHITE "Text\n" RESET;
1108 but the syntax of Perl doesn't allow this. You need a comma after the
1109 string. (Of course, you may consider it a bug that commas between all the
1110 constants aren't required, in which case you may feel free to insert
1111 commas unless you're using $Term::ANSIColor::AUTORESET or
1112 PUSHCOLOR/POPCOLOR.)
1114 For easier debugging, you may prefer to always use the commas when not
1115 setting $Term::ANSIColor::AUTORESET or PUSHCOLOR/POPCOLOR so that you'll
1116 get a fatal compile error rather than a warning.
1118 It's not possible to use this module to embed formatting and color
1119 attributes using Perl formats. They replace the escape character with a
1120 space (as documented in L<perlform(1)>), resulting in garbled output from
1121 the unrecognized attribute. Even if there were a way around that problem,
1122 the format doesn't know that the non-printing escape sequence is
1123 zero-length and would incorrectly format the output. For formatted output
1124 using color or other attributes, either use sprintf() instead or use
1125 formline() and then add the color or other attributes after formatting and
1130 The codes generated by this module are standard terminal control codes,
1131 complying with ECMA-048 and ISO 6429 (generally referred to as "ANSI
1132 color" for the color codes). The non-color control codes (bold, dark,
1133 italic, underline, and reverse) are part of the earlier ANSI X3.64
1134 standard for control sequences for video terminals and peripherals.
1136 Note that not all displays are ISO 6429-compliant, or even X3.64-compliant
1137 (or are even attempting to be so). This module will not work as expected
1138 on displays that do not honor these escape sequences, such as cmd.exe,
1139 4nt.exe, and command.com under either Windows NT or Windows 2000. They
1140 may just be ignored, or they may display as an ESC character followed by
1141 some apparent garbage.
1143 Jean Delvare provided the following table of different common terminal
1144 emulators and their support for the various attributes and others have
1145 helped me flesh it out:
1147 clear bold faint under blink reverse conceal
1148 ------------------------------------------------------------------------
1149 xterm yes yes no yes yes yes yes
1150 linux yes yes yes bold yes yes no
1151 rxvt yes yes no yes bold/black yes no
1152 dtterm yes yes yes yes reverse yes yes
1153 teraterm yes reverse no yes rev/red yes no
1154 aixterm kinda normal no yes no yes yes
1155 PuTTY yes color no yes no yes no
1156 Windows yes no no no no yes no
1157 Cygwin SSH yes yes no color color color yes
1158 Terminal.app yes yes no yes yes yes yes
1160 Windows is Windows telnet, Cygwin SSH is the OpenSSH implementation under
1161 Cygwin on Windows NT, and Mac Terminal is the Terminal application in Mac
1162 OS X. Where the entry is other than yes or no, that emulator displays the
1163 given attribute as something else instead. Note that on an aixterm, clear
1164 doesn't reset colors; you have to explicitly set the colors back to what
1165 you want. More entries in this table are welcome.
1167 Support for code 3 (italic) is rare and therefore not mentioned in that
1168 table. It is not believed to be fully supported by any of the terminals
1169 listed, although it's displayed as green in the Linux console, but it is
1170 reportedly supported by urxvt.
1172 Note that codes 6 (rapid blink) and 9 (strike-through) are specified in
1173 ANSI X3.64 and ECMA-048 but are not commonly supported by most displays
1174 and emulators and therefore aren't supported by this module at the present
1175 time. ECMA-048 also specifies a large number of other attributes,
1176 including a sequence of attributes for font changes, Fraktur characters,
1177 double-underlining, framing, circling, and overlining. As none of these
1178 attributes are widely supported or useful, they also aren't currently
1179 supported by this module.
1181 Most modern X terminal emulators support 256 colors. Known to not support
1182 those colors are aterm, rxvt, Terminal.app, and TTY/VC.
1186 ECMA-048 is available on-line (at least at the time of this writing) at
1187 L<http://www.ecma-international.org/publications/standards/Ecma-048.htm>.
1189 ISO 6429 is available from ISO for a charge; the author of this module
1190 does not own a copy of it. Since the source material for ISO 6429 was
1191 ECMA-048 and the latter is available for free, there seems little reason
1192 to obtain the ISO standard.
1194 The 256-color control sequences are documented at
1195 L<http://www.xfree86.org/current/ctlseqs.html> (search for 256-color).
1197 The CPAN module Term::ExtendedColor provides a different and more
1198 comprehensive interface for 256-color emulators that may be more
1201 The current version of this module is always available from its web site
1202 at L<http://www.eyrie.org/~eagle/software/ansicolor/>. It is also part of
1203 the Perl core distribution as of 5.6.0.
1207 Original idea (using constants) by Zenin, reimplemented using subs by Russ
1208 Allbery <rra@stanford.edu>, and then combined with the original idea by
1209 Russ with input from Zenin. 256-color support is based on work by Kurt
1210 Starsinic. Russ Allbery now maintains this module.
1212 PUSHCOLOR, POPCOLOR, and LOCALCOLOR were contributed by openmethods.com
1215 =head1 COPYRIGHT AND LICENSE
1217 Copyright 1996 Zenin. Copyright 1996, 1997, 1998, 2000, 2001, 2002, 2005,
1218 2006, 2008, 2009, 2010, 2011, 2012 Russ Allbery <rra@stanford.edu>.
1219 Copyright 2012 Kurt Starsinic <kstarsinic@gmail.com>. This program is
1220 free software; you may redistribute it and/or modify it under the same
1221 terms as Perl itself.