1# Color screen output using ANSI escape sequences.
2#
3# This module provides utility functions (in two different forms) for coloring
4# output with ANSI escape sequences.
5#
6# This module is sometimes used in low-memory environments, so avoid use of
7# \d, \w, [:upper:], and similar constructs in the most important functions
8# (color, colored, AUTOLOAD, and the generated constant functions) since
9# loading the Unicode attribute files consumes a lot of memory.
10#
11# Ah, September, when the sysadmins turn colors and fall off the trees....
12#                               -- Dave Van Domelen
13#
14# SPDX-License-Identifier: GPL-1.0-or-later OR Artistic-1.0-Perl
15
16##############################################################################
17# Modules and declarations
18##############################################################################
19
20package Term::ANSIColor;
21
22use 5.008;
23use strict;
24use warnings;
25
26# Also uses Carp but loads it on demand to reduce memory usage.
27
28use Exporter;
29
30# use Exporter plus @ISA instead of use base to reduce memory usage.
31## no critic (ClassHierarchies::ProhibitExplicitISA)
32
33# Declare variables that should be set in BEGIN for robustness.
34## no critic (Modules::ProhibitAutomaticExportation)
35our (@EXPORT, @EXPORT_OK, %EXPORT_TAGS, @ISA, $VERSION);
36
37# We use autoloading, which sets this variable to the name of the called sub.
38our $AUTOLOAD;
39
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).
43BEGIN {
44    $VERSION = '5.01';
45
46    # All of the basic supported constants, used in %EXPORT_TAGS.
47    my @colorlist = qw(
48      CLEAR           RESET             BOLD            DARK
49      FAINT           ITALIC            UNDERLINE       UNDERSCORE
50      BLINK           REVERSE           CONCEALED
51
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
56
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
61    );
62
63    # 256-color constants, used in %EXPORT_TAGS.
64    my @colorlist256 = (
65        (map { ("ANSI$_", "ON_ANSI$_") } 0 .. 255),
66        (map { ("GREY$_", "ON_GREY$_") } 0 .. 23),
67    );
68    for my $r (0 .. 5) {
69        for my $g (0 .. 5) {
70            push(@colorlist256, map { ("RGB$r$g$_", "ON_RGB$r$g$_") } 0 .. 5);
71        }
72    }
73
74    # Exported symbol configuration.
75    @ISA         = qw(Exporter);
76    @EXPORT      = qw(color colored);
77    @EXPORT_OK   = qw(uncolor colorstrip colorvalid coloralias);
78    %EXPORT_TAGS = (
79        constants    => \@colorlist,
80        constants256 => \@colorlist256,
81        pushpop      => [@colorlist, qw(PUSHCOLOR POPCOLOR LOCALCOLOR)],
82    );
83    Exporter::export_ok_tags('pushpop', 'constants256');
84}
85
86##############################################################################
87# Package variables
88##############################################################################
89
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.
93our $AUTOLOCAL;
94
95# Caller sets this to force a reset at the end of each constant sequence.
96our $AUTORESET;
97
98# Caller sets this to force colors to be reset at the end of each line.
99our $EACHLINE;
100
101##############################################################################
102# Internal data structures
103##############################################################################
104
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.
109
110# All basic supported attributes, including aliases.
111#<<<
112our %ATTRIBUTES = (
113    'clear'          => 0,
114    'reset'          => 0,
115    'bold'           => 1,
116    'dark'           => 2,
117    'faint'          => 2,
118    'italic'         => 3,
119    'underline'      => 4,
120    'underscore'     => 4,
121    'blink'          => 5,
122    'reverse'        => 7,
123    'concealed'      => 8,
124
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,
133
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,
142);
143#>>>
144
145# Generating the 256-color codes involves a lot of codes and offsets that are
146# not helped by turning them into constants.
147
148# The first 16 256-color codes are duplicates of the 16 ANSI colors.  The rest
149# are RBG and greyscale values.
150for my $code (0 .. 15) {
151    $ATTRIBUTES{"ansi$code"}    = "38;5;$code";
152    $ATTRIBUTES{"on_ansi$code"} = "48;5;$code";
153}
154
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.
157for my $r (0 .. 5) {
158    for my $g (0 .. 5) {
159        for my $b (0 .. 5) {
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";
163        }
164    }
165}
166
167# The last 256-color codes are 24 shades of grey.
168for my $n (0 .. 23) {
169    my $code = $n + 232;
170    $ATTRIBUTES{"grey$n"}    = "38;5;$code";
171    $ATTRIBUTES{"on_grey$n"} = "48;5;$code";
172}
173
174# Reverse lookup.  Alphabetically first name for a sequence is preferred.
175our %ATTRIBUTES_R;
176for my $attr (reverse(sort(keys(%ATTRIBUTES)))) {
177    $ATTRIBUTES_R{ $ATTRIBUTES{$attr} } = $attr;
178}
179
180# Provide ansiN names for all 256 characters to provide a convenient flat
181# namespace if one doesn't want to mess with the RGB and greyscale naming.  Do
182# this after creating %ATTRIBUTES_R since we want to use the canonical names
183# when reversing a color.
184for my $code (16 .. 255) {
185    $ATTRIBUTES{"ansi$code"}    = "38;5;$code";
186    $ATTRIBUTES{"on_ansi$code"} = "48;5;$code";
187}
188
189# Import any custom colors set in the environment.
190our %ALIASES;
191if (exists($ENV{ANSI_COLORS_ALIASES})) {
192    my $spec = $ENV{ANSI_COLORS_ALIASES};
193    $spec =~ s{ \A \s+ }{}xms;
194    $spec =~ s{ \s+ \z }{}xms;
195
196    # Error reporting here is an interesting question.  Use warn rather than
197    # carp because carp would report the line of the use or require, which
198    # doesn't help anyone understand what's going on, whereas seeing this code
199    # will be more helpful.
200    ## no critic (ErrorHandling::RequireCarping)
201    for my $definition (split(m{\s*,\s*}xms, $spec)) {
202        my ($new, $old) = split(m{\s*=\s*}xms, $definition, 2);
203        if (!$new || !$old) {
204            warn qq{Bad color mapping "$definition"};
205        } else {
206            my $result = eval { coloralias($new, $old) };
207            if (!$result) {
208                my $error = $@;
209                $error =~ s{ [ ] at [ ] .* }{}xms;
210                warn qq{$error in "$definition"};
211            }
212        }
213    }
214}
215
216# Stores the current color stack maintained by PUSHCOLOR and POPCOLOR.  This
217# is global and therefore not threadsafe.
218our @COLORSTACK;
219
220##############################################################################
221# Helper functions
222##############################################################################
223
224# Stub to load the Carp module on demand.
225sub croak {
226    my (@args) = @_;
227    require Carp;
228    Carp::croak(@args);
229}
230
231##############################################################################
232# Implementation (constant form)
233##############################################################################
234
235# Time to have fun!  We now want to define the constant subs, which are named
236# the same as the attributes above but in all caps.  Each constant sub needs
237# to act differently depending on whether $AUTORESET is set.  Without
238# autoreset:
239#
240#     BLUE "text\n"  ==>  "\e[34mtext\n"
241#
242# If $AUTORESET is set, we should instead get:
243#
244#     BLUE "text\n"  ==>  "\e[34mtext\n\e[0m"
245#
246# The sub also needs to handle the case where it has no arguments correctly.
247# Maintaining all of this as separate subs would be a major nightmare, as well
248# as duplicate the %ATTRIBUTES hash, so instead we define an AUTOLOAD sub to
249# define the constant subs on demand.  To do that, we check the name of the
250# called sub against the list of attributes, and if it's an all-caps version
251# of one of them, we define the sub on the fly and then run it.
252#
253# If the environment variable ANSI_COLORS_DISABLED is set to a true value, or
254# if the variable NO_COLOR is set, just return the arguments without adding
255# any escape sequences.  This is to make it easier to write scripts that also
256# work on systems without any ANSI support, like Windows consoles.
257#
258# Avoid using character classes like [:upper:] and \w here, since they load
259# Unicode character tables and consume a ton of memory.  All of our constants
260# only use ASCII characters.
261#
262## no critic (ClassHierarchies::ProhibitAutoloading)
263## no critic (Subroutines::RequireArgUnpacking)
264## no critic (RegularExpressions::ProhibitEnumeratedClasses)
265sub AUTOLOAD {
266    my ($sub, $attr) = $AUTOLOAD =~ m{
267        \A ( [a-zA-Z0-9:]* :: ([A-Z0-9_]+) ) \z
268    }xms;
269
270    # Check if we were called with something that doesn't look like an
271    # attribute.
272    if (!($attr && defined($ATTRIBUTES{ lc $attr }))) {
273        croak("undefined subroutine &$AUTOLOAD called");
274    }
275
276    # If colors are disabled, just return the input.  Do this without
277    # installing a sub for (marginal, unbenchmarked) speed.
278    if ($ENV{ANSI_COLORS_DISABLED} || defined($ENV{NO_COLOR})) {
279        return join(q{}, @_);
280    }
281
282    # We've untainted the name of the sub.
283    $AUTOLOAD = $sub;
284
285    # Figure out the ANSI string to set the desired attribute.
286    my $escape = "\e[" . $ATTRIBUTES{ lc $attr } . 'm';
287
288    # Save the current value of $@.  We can't just use local since we want to
289    # restore it before dispatching to the newly-created sub.  (The caller may
290    # be colorizing output that includes $@.)
291    my $eval_err = $@;
292
293    # Generate the constant sub, which should still recognize some of our
294    # package variables.  Use string eval to avoid a dependency on
295    # Sub::Install, even though it makes it somewhat less readable.
296    ## no critic (BuiltinFunctions::ProhibitStringyEval)
297    ## no critic (ValuesAndExpressions::ProhibitImplicitNewlines)
298    my $eval_result = eval qq{
299        sub $AUTOLOAD {
300            if (\$ENV{ANSI_COLORS_DISABLED} || defined(\$ENV{NO_COLOR})) {
301                return join(q{}, \@_);
302            } elsif (\$AUTOLOCAL && \@_) {
303                return PUSHCOLOR('$escape') . join(q{}, \@_) . POPCOLOR;
304            } elsif (\$AUTORESET && \@_) {
305                return '$escape' . join(q{}, \@_) . "\e[0m";
306            } else {
307                return '$escape' . join(q{}, \@_);
308            }
309        }
310        1;
311    };
312
313    # Failure is an internal error, not a problem with the caller.
314    ## no critic (ErrorHandling::RequireCarping)
315    if (!$eval_result) {
316        die "failed to generate constant $attr: $@";
317    }
318
319    # Restore $@.
320    ## no critic (Variables::RequireLocalizedPunctuationVars)
321    $@ = $eval_err;
322
323    # Dispatch to the newly-created sub.
324    goto &$AUTOLOAD;
325}
326## use critic
327
328# Append a new color to the top of the color stack and return the top of
329# the stack.
330#
331# $text - Any text we're applying colors to, with color escapes prepended
332#
333# Returns: The text passed in
334sub PUSHCOLOR {
335    my (@text) = @_;
336    my $text = join(q{}, @text);
337
338    # Extract any number of color-setting escape sequences from the start of
339    # the string.
340    my ($color) = $text =~ m{ \A ( (?:\e\[ [\d;]+ m)+ ) }xms;
341
342    # If we already have a stack, append these escapes to the set from the top
343    # of the stack.  This way, each position in the stack stores the complete
344    # enabled colors for that stage, at the cost of some potential
345    # inefficiency.
346    if (@COLORSTACK) {
347        $color = $COLORSTACK[-1] . $color;
348    }
349
350    # Push the color onto the stack.
351    push(@COLORSTACK, $color);
352    return $text;
353}
354
355# Pop the color stack and return the new top of the stack (or reset, if
356# the stack is empty).
357#
358# @text - Any text we're applying colors to
359#
360# Returns: The concatenation of @text prepended with the new stack color
361sub POPCOLOR {
362    my (@text) = @_;
363    pop(@COLORSTACK);
364    if (@COLORSTACK) {
365        return $COLORSTACK[-1] . join(q{}, @text);
366    } else {
367        return RESET(@text);
368    }
369}
370
371# Surround arguments with a push and a pop.  The effect will be to reset the
372# colors to whatever was on the color stack before this sequence of colors was
373# applied.
374#
375# @text - Any text we're applying colors to
376#
377# Returns: The concatenation of the text and the proper color reset sequence.
378sub LOCALCOLOR {
379    my (@text) = @_;
380    return PUSHCOLOR(join(q{}, @text)) . POPCOLOR();
381}
382
383##############################################################################
384# Implementation (attribute string form)
385##############################################################################
386
387# Return the escape code for a given set of color attributes.
388#
389# @codes - A list of possibly space-separated color attributes
390#
391# Returns: The escape sequence setting those color attributes
392#          undef if no escape sequences were given
393#  Throws: Text exception for any invalid attribute
394sub color {
395    my (@codes) = @_;
396
397    # Return the empty string if colors are disabled.
398    if ($ENV{ANSI_COLORS_DISABLED} || defined($ENV{NO_COLOR})) {
399        return q{};
400    }
401
402    # Split on whitespace and expand aliases.
403    @codes = map { split } @codes;
404    @codes = map { defined($ALIASES{$_}) ? @{ $ALIASES{$_} } : $_ } @codes;
405
406    # Build the attribute string from semicolon-separated numbers.
407    ## no critic (RegularExpressions::ProhibitEnumeratedClasses)
408    my $attribute = q{};
409    for my $code (@codes) {
410        $code = lc($code);
411        if (defined($ATTRIBUTES{$code})) {
412            $attribute .= $ATTRIBUTES{$code} . q{;};
413        } elsif ($code =~ m{ \A (on_)? r([0-9]+) g([0-9]+) b([0-9]+) \z }xms) {
414            my ($r, $g, $b) = ($2 + 0, $3 + 0, $4 + 0);
415            if ($r > 255 || $g > 255 || $b > 255) {
416                croak("Invalid attribute name $code");
417            }
418            my $prefix = $1 ? '48' : '38';
419            $attribute .= "$prefix;2;$r;$g;$b;";
420        } else {
421            croak("Invalid attribute name $code");
422        }
423    }
424    ## use critic
425
426    # We added one too many semicolons for simplicity.  Remove the last one.
427    chop($attribute);
428
429    # Return undef if there were no attributes.
430    return ($attribute ne q{}) ? "\e[${attribute}m" : undef;
431}
432
433# Return a list of named color attributes for a given set of escape codes.
434# Escape sequences can be given with or without enclosing "\e[" and "m".  The
435# empty escape sequence '' or "\e[m" gives an empty list of attrs.
436#
437# There is one special case.  256-color codes start with 38 or 48, followed by
438# a 5 and then the 256-color code.
439#
440# @escapes - A list of escape sequences or escape sequence numbers
441#
442# Returns: An array of attribute names corresponding to those sequences
443#  Throws: Text exceptions on invalid escape sequences or unknown colors
444sub uncolor {
445    my (@escapes) = @_;
446    my (@nums, @result);
447
448    # Walk the list of escapes and build a list of attribute numbers.
449    for my $escape (@escapes) {
450        $escape =~ s{ \A \e\[ }{}xms;
451        $escape =~ s{ m \z }   {}xms;
452        my ($attrs) = $escape =~ m{ \A ((?:\d+;)* \d*) \z }xms;
453        if (!defined($attrs)) {
454            croak("Bad escape sequence $escape");
455        }
456
457        # Pull off 256-color codes (38;5;n or 48;5;n) and true color codes
458        # (38;2;n;n;n or 48;2;n;n;n) as a unit.
459        my $regex = qr{
460            (
461                0*[34]8 ; 0*2 ; \d+ ; \d+ ; \d+
462              | 0*[34]8 ; 0*5 ; \d+
463              | \d+
464            )
465            (?: ; | \z )
466        }xms;
467        push(@nums, $attrs =~ m{$regex}xmsg);
468    }
469
470    # Now, walk the list of numbers and convert them to attribute names.
471    # Strip leading zeroes from any of the numbers.  (xterm, at least, allows
472    # leading zeroes to be added to any number in an escape sequence.)
473    for my $num (@nums) {
474        if ($num =~ m{ \A 0*([34])8 ; 0*2 ; (\d+) ; (\d+) ; (\d+) \z }xms) {
475            my ($r, $g, $b) = ($2 + 0, $3 + 0, $4 + 0);
476            if ($r > 255 || $g > 255 || $b > 255) {
477                croak("No name for escape sequence $num");
478            }
479            my $prefix = ($1 == 4) ? 'on_' : q{};
480            push(@result, "${prefix}r${r}g${g}b${b}");
481        } else {
482            $num =~ s{ ( \A | ; ) 0+ (\d) }{$1$2}xmsg;
483            my $name = $ATTRIBUTES_R{$num};
484            if (!defined($name)) {
485                croak("No name for escape sequence $num");
486            }
487            push(@result, $name);
488        }
489    }
490
491    # Return the attribute names.
492    return @result;
493}
494
495# Given a string and a set of attributes, returns the string surrounded by
496# escape codes to set those attributes and then clear them at the end of the
497# string.  The attributes can be given either as an array ref as the first
498# argument or as a list as the second and subsequent arguments.
499#
500# If $EACHLINE is set, insert a reset before each occurrence of the string
501# $EACHLINE and the starting attribute code after the string $EACHLINE, so
502# that no attribute crosses line delimiters (this is often desirable if the
503# output is to be piped to a pager or some other program).
504#
505# $first - An anonymous array of attributes or the text to color
506# @rest  - The text to color or the list of attributes
507#
508# Returns: The text, concatenated if necessary, surrounded by escapes to set
509#          the desired colors and reset them afterwards
510#  Throws: Text exception on invalid attributes
511sub colored {
512    my ($first, @rest) = @_;
513    my ($string, @codes);
514    if (ref($first) && ref($first) eq 'ARRAY') {
515        @codes  = @{$first};
516        $string = join(q{}, @rest);
517    } else {
518        $string = $first;
519        @codes  = @rest;
520    }
521
522    # Return the string unmolested if colors are disabled.
523    if ($ENV{ANSI_COLORS_DISABLED} || defined($ENV{NO_COLOR})) {
524        return $string;
525    }
526
527    # Find the attribute string for our colors.
528    my $attr = color(@codes);
529
530    # If $EACHLINE is defined, split the string on line boundaries, suppress
531    # empty segments, and then colorize each of the line sections.
532    if (defined($EACHLINE)) {
533        my @text = map { ($_ ne $EACHLINE) ? $attr . $_ . "\e[0m" : $_ }
534          grep { length > 0 }
535          split(m{ (\Q$EACHLINE\E) }xms, $string);
536        return join(q{}, @text);
537    } else {
538        return $attr . $string . "\e[0m";
539    }
540}
541
542# Define a new color alias, or return the value of an existing alias.
543#
544# $alias - The color alias to define
545# @color - The color attributes the alias will correspond to (optional)
546#
547# Returns: The standard color value of the alias as a string (may be multiple
548#              attributes separated by spaces)
549#          undef if one argument was given and the alias was not recognized
550#  Throws: Text exceptions for invalid alias names, attempts to use a
551#          standard color name as an alias, or an unknown standard color name
552sub coloralias {
553    my ($alias, @color) = @_;
554    if (!@color) {
555        if (exists($ALIASES{$alias})) {
556            return join(q{ }, @{ $ALIASES{$alias} });
557        } else {
558            return;
559        }
560    }
561
562    # Avoid \w here to not load Unicode character tables, which increases the
563    # memory footprint of this module considerably.
564    #
565    ## no critic (RegularExpressions::ProhibitEnumeratedClasses)
566    if ($alias !~ m{ \A [a-zA-Z0-9._-]+ \z }xms) {
567        croak(qq{Invalid alias name "$alias"});
568    } elsif ($ATTRIBUTES{$alias}) {
569        croak(qq{Cannot alias standard color "$alias"});
570    }
571    ## use critic
572
573    # Split on whitespace and expand aliases.
574    @color = map { split } @color;
575    @color = map { defined($ALIASES{$_}) ? @{ $ALIASES{$_} } : $_ } @color;
576
577    # Check that all of the attributes are valid.
578    for my $attribute (@color) {
579        if (!exists($ATTRIBUTES{$attribute})) {
580            croak(qq{Invalid attribute name "$attribute"});
581        }
582    }
583
584    # Set the alias and return.
585    $ALIASES{$alias} = [@color];
586    return join(q{ }, @color);
587}
588
589# Given a string, strip the ANSI color codes out of that string and return the
590# result.  This removes only ANSI color codes, not movement codes and other
591# escape sequences.
592#
593# @string - The list of strings to sanitize
594#
595# Returns: (array)  The strings stripped of ANSI color escape sequences
596#          (scalar) The same, concatenated
597sub colorstrip {
598    my (@string) = @_;
599    for my $string (@string) {
600        $string =~ s{ \e\[ [\d;]* m }{}xmsg;
601    }
602    return wantarray ? @string : join(q{}, @string);
603}
604
605# Given a list of color attributes (arguments for color, for instance), return
606# true if they're all valid or false if any of them are invalid.
607#
608# @codes - A list of color attributes, possibly space-separated
609#
610# Returns: True if all the attributes are valid, false otherwise.
611sub colorvalid {
612    my (@codes) = @_;
613    @codes = map { split(q{ }, lc) } @codes;
614    for my $code (@codes) {
615        next if defined($ATTRIBUTES{$code});
616        next if defined($ALIASES{$code});
617        if ($code =~ m{ \A (?: on_ )? r (\d+) g (\d+) b (\d+) \z }xms) {
618            next if ($1 <= 255 && $2 <= 255 && $3 <= 255);
619        }
620        return;
621    }
622    return 1;
623}
624
625##############################################################################
626# Module return value and documentation
627##############################################################################
628
629# Ensure we evaluate to true.
6301;
631__END__
632
633=head1 NAME
634
635Term::ANSIColor - Color screen output using ANSI escape sequences
636
637=for stopwords
638cyan colorize namespace runtime TMTOWTDI cmd.exe cmd.exe. 4nt.exe. 4nt.exe
639command.com NT ESC Delvare SSH OpenSSH aixterm ECMA-048 Fraktur overlining
640Zenin reimplemented Allbery PUSHCOLOR POPCOLOR LOCALCOLOR openmethods.com
641openmethods.com. grey ATTR urxvt mistyped prepending Bareword filehandle
642Cygwin Starsinic aterm rxvt CPAN RGB Solarized Whitespace alphanumerics
643undef CLICOLOR NNN GGG RRR
644
645=head1 SYNOPSIS
646
647    use Term::ANSIColor;
648    print color('bold blue');
649    print "This text is bold blue.\n";
650    print color('reset');
651    print "This text is normal.\n";
652    print colored("Yellow on magenta.", 'yellow on_magenta'), "\n";
653    print "This text is normal.\n";
654    print colored(['yellow on_magenta'], 'Yellow on magenta.', "\n");
655    print colored(['red on_bright_yellow'], 'Red on bright yellow.', "\n");
656    print colored(['bright_red on_black'], 'Bright red on black.', "\n");
657    print "\n";
658
659    # Map escape sequences back to color names.
660    use Term::ANSIColor 1.04 qw(uncolor);
661    my @names = uncolor('01;31');
662    print join(q{ }, @names), "\n";
663
664    # Strip all color escape sequences.
665    use Term::ANSIColor 2.01 qw(colorstrip);
666    print colorstrip("\e[1mThis is bold\e[0m"), "\n";
667
668    # Determine whether a color is valid.
669    use Term::ANSIColor 2.02 qw(colorvalid);
670    my $valid = colorvalid('blue bold', 'on_magenta');
671    print "Color string is ", $valid ? "valid\n" : "invalid\n";
672
673    # Create new aliases for colors.
674    use Term::ANSIColor 4.00 qw(coloralias);
675    coloralias('alert', 'red');
676    print "Alert is ", coloralias('alert'), "\n";
677    print colored("This is in red.", 'alert'), "\n";
678
679    use Term::ANSIColor qw(:constants);
680    print BOLD, BLUE, "This text is in bold blue.\n", RESET;
681
682    use Term::ANSIColor qw(:constants);
683    {
684        local $Term::ANSIColor::AUTORESET = 1;
685        print BOLD BLUE "This text is in bold blue.\n";
686        print "This text is normal.\n";
687    }
688
689    use Term::ANSIColor 2.00 qw(:pushpop);
690    print PUSHCOLOR RED ON_GREEN "This text is red on green.\n";
691    print PUSHCOLOR BRIGHT_BLUE "This text is bright blue on green.\n";
692    print RESET BRIGHT_BLUE "This text is just bright blue.\n";
693    print POPCOLOR "Back to red on green.\n";
694    print LOCALCOLOR GREEN ON_BLUE "This text is green on blue.\n";
695    print "This text is red on green.\n";
696    {
697        local $Term::ANSIColor::AUTOLOCAL = 1;
698        print ON_BLUE "This text is red on blue.\n";
699        print "This text is red on green.\n";
700    }
701    print POPCOLOR "Back to whatever we started as.\n";
702
703=head1 DESCRIPTION
704
705This module has two interfaces, one through color() and colored() and the
706other through constants.  It also offers the utility functions uncolor(),
707colorstrip(), colorvalid(), and coloralias(), which have to be explicitly
708imported to be used (see L</SYNOPSIS>).
709
710If you are using Term::ANSIColor in a console command, consider supporting the
711CLICOLOR standard.  See L</"Supporting CLICOLOR"> for more information.
712
713See L</COMPATIBILITY> for the versions of Term::ANSIColor that introduced
714particular features and the versions of Perl that included them.
715
716=head2 Supported Colors
717
718Terminal emulators that support color divide into four types: ones that
719support only eight colors, ones that support sixteen, ones that support 256,
720and ones that support 24-bit color.  This module provides the ANSI escape
721codes for all of them.  These colors are referred to as ANSI colors 0 through
7227 (normal), 8 through 15 (16-color), 16 through 255 (256-color), and true
723color (called direct-color by B<xterm>).
724
725Unfortunately, interpretation of colors 0 through 7 often depends on
726whether the emulator supports eight colors or sixteen colors.  Emulators
727that only support eight colors (such as the Linux console) will display
728colors 0 through 7 with normal brightness and ignore colors 8 through 15,
729treating them the same as white.  Emulators that support 16 colors, such
730as gnome-terminal, normally display colors 0 through 7 as dim or darker
731versions and colors 8 through 15 as normal brightness.  On such emulators,
732the "normal" white (color 7) usually is shown as pale grey, requiring
733bright white (15) to be used to get a real white color.  Bright black
734usually is a dark grey color, although some terminals display it as pure
735black.  Some sixteen-color terminal emulators also treat normal yellow
736(color 3) as orange or brown, and bright yellow (color 11) as yellow.
737
738Following the normal convention of sixteen-color emulators, this module
739provides a pair of attributes for each color.  For every normal color (0
740through 7), the corresponding bright color (8 through 15) is obtained by
741prepending the string C<bright_> to the normal color name.  For example,
742C<red> is color 1 and C<bright_red> is color 9.  The same applies for
743background colors: C<on_red> is the normal color and C<on_bright_red> is
744the bright color.  Capitalize these strings for the constant interface.
745
746There is unfortunately no way to know whether the current emulator
747supports more than eight colors, which makes the choice of colors
748difficult.  The most conservative choice is to use only the regular
749colors, which are at least displayed on all emulators.  However, they will
750appear dark in sixteen-color terminal emulators, including most common
751emulators in UNIX X environments.  If you know the display is one of those
752emulators, you may wish to use the bright variants instead.  Even better,
753offer the user a way to configure the colors for a given application to
754fit their terminal emulator.
755
756For 256-color emulators, this module additionally provides C<ansi0>
757through C<ansi15>, which are the same as colors 0 through 15 in
758sixteen-color emulators but use the 256-color escape syntax, C<grey0>
759through C<grey23> ranging from nearly black to nearly white, and a set of
760RGB colors.  The RGB colors are of the form C<rgbI<RGB>> where I<R>, I<G>,
761and I<B> are numbers from 0 to 5 giving the intensity of red, green, and
762blue.  The grey and RGB colors are also available as C<ansi16> through
763C<ansi255> if you want simple names for all 256 colors.  C<on_> variants
764of all of these colors are also provided.  These colors may be ignored
765completely on non-256-color terminals or may be misinterpreted and produce
766random behavior.  Additional attributes such as blink, italic, or bold may
767not work with the 256-color palette.
768
769For true color emulators, this module supports attributes of the form C<<
770rI<NNN>gI<NNN>bI<NNN> >> and C<< on_rI<NNN>gI<NNN>bI<NNN> >> for all values of
771I<NNN> between 0 and 255.  These represent foreground and background colors,
772respectively, with the RGB values given by the I<NNN> numbers.  These colors
773may be ignored completely on non-true-color terminals or may be misinterpreted
774and produce random behavior.
775
776=head2 Function Interface
777
778The function interface uses attribute strings to describe the colors and
779text attributes to assign to text.  The recognized non-color attributes
780are clear, reset, bold, dark, faint, italic, underline, underscore, blink,
781reverse, and concealed.  Clear and reset (reset to default attributes),
782dark and faint (dim and saturated), and underline and underscore are
783equivalent, so use whichever is the most intuitive to you.
784
785Note that not all attributes are supported by all terminal types, and some
786terminals may not support any of these sequences.  Dark and faint, italic,
787blink, and concealed in particular are frequently not implemented.
788
789The recognized normal foreground color attributes (colors 0 to 7) are:
790
791  black  red  green  yellow  blue  magenta  cyan  white
792
793The corresponding bright foreground color attributes (colors 8 to 15) are:
794
795  bright_black  bright_red      bright_green  bright_yellow
796  bright_blue   bright_magenta  bright_cyan   bright_white
797
798The recognized normal background color attributes (colors 0 to 7) are:
799
800  on_black  on_red      on_green  on yellow
801  on_blue   on_magenta  on_cyan   on_white
802
803The recognized bright background color attributes (colors 8 to 15) are:
804
805  on_bright_black  on_bright_red      on_bright_green  on_bright_yellow
806  on_bright_blue   on_bright_magenta  on_bright_cyan   on_bright_white
807
808For 256-color terminals, the recognized foreground colors are:
809
810  ansi0 .. ansi255
811  grey0 .. grey23
812
813plus C<rgbI<RGB>> for I<R>, I<G>, and I<B> values from 0 to 5, such as
814C<rgb000> or C<rgb515>.  Similarly, the recognized background colors are:
815
816  on_ansi0 .. on_ansi255
817  on_grey0 .. on_grey23
818
819plus C<on_rgbI<RGB>> for I<R>, I<G>, and I<B> values from 0 to 5.
820
821For true color terminals, the recognized foreground colors are C<<
822rI<RRR>gI<GGG>bI<BBB> >> for I<RRR>, I<GGG>, and I<BBB> values between 0 and
823255.  Similarly, the recognized background colors are C<<
824on_rI<RRR>gI<GGG>bI<BBB> >> for I<RRR>, I<GGG>, and I<BBB> values between 0
825and 255.
826
827For any of the above listed attributes, case is not significant.
828
829Attributes, once set, last until they are unset (by printing the attribute
830C<clear> or C<reset>).  Be careful to do this, or otherwise your attribute
831will last after your script is done running, and people get very annoyed
832at having their prompt and typing changed to weird colors.
833
834=over 4
835
836=item color(ATTR[, ATTR ...])
837
838color() takes any number of strings as arguments and considers them to be
839space-separated lists of attributes.  It then forms and returns the escape
840sequence to set those attributes.  It doesn't print it out, just returns
841it, so you'll have to print it yourself if you want to.  This is so that
842you can save it as a string, pass it to something else, send it to a file
843handle, or do anything else with it that you might care to.  color()
844throws an exception if given an invalid attribute.
845
846=item colored(STRING, ATTR[, ATTR ...])
847
848=item colored(ATTR-REF, STRING[, STRING...])
849
850As an aid in resetting colors, colored() takes a scalar as the first
851argument and any number of attribute strings as the second argument and
852returns the scalar wrapped in escape codes so that the attributes will be
853set as requested before the string and reset to normal after the string.
854Alternately, you can pass a reference to an array as the first argument,
855and then the contents of that array will be taken as attributes and color
856codes and the remainder of the arguments as text to colorize.
857
858Normally, colored() just puts attribute codes at the beginning and end of
859the string, but if you set $Term::ANSIColor::EACHLINE to some string, that
860string will be considered the line delimiter and the attribute will be set
861at the beginning of each line of the passed string and reset at the end of
862each line.  This is often desirable if the output contains newlines and
863you're using background colors, since a background color that persists
864across a newline is often interpreted by the terminal as providing the
865default background color for the next line.  Programs like pagers can also
866be confused by attributes that span lines.  Normally you'll want to set
867$Term::ANSIColor::EACHLINE to C<"\n"> to use this feature.
868
869Particularly consider setting $Term::ANSIColor::EACHLINE if you are
870interleaving output to standard output and standard error and you aren't
871flushing standard output (via autoflush() or setting C<$|>).  If you don't,
872the code to reset the color may unexpectedly sit in the standard output buffer
873rather than going to the display, causing standard error output to appear in
874the wrong color.
875
876=item uncolor(ESCAPE)
877
878uncolor() performs the opposite translation as color(), turning escape
879sequences into a list of strings corresponding to the attributes being set
880by those sequences.  uncolor() will never return C<ansi16> through
881C<ansi255>, instead preferring the C<grey> and C<rgb> names (and likewise
882for C<on_ansi16> through C<on_ansi255>).
883
884=item colorstrip(STRING[, STRING ...])
885
886colorstrip() removes all color escape sequences from the provided strings,
887returning the modified strings separately in array context or joined
888together in scalar context.  Its arguments are not modified.
889
890=item colorvalid(ATTR[, ATTR ...])
891
892colorvalid() takes attribute strings the same as color() and returns true
893if all attributes are known and false otherwise.
894
895=item coloralias(ALIAS[, ATTR ...])
896
897If ATTR is specified, it is interpreted as a list of space-separated strings
898naming attributes or existing aliases.  In this case, coloralias() sets up an
899alias of ALIAS for the set of attributes given by ATTR.  From that point
900forward, ALIAS can be passed into color(), colored(), and colorvalid() and
901will have the same meaning as the sequence of attributes given in ATTR.  One
902possible use of this facility is to give more meaningful names to the
903256-color RGB colors.  Only ASCII alphanumerics, C<.>, C<_>, and C<-> are
904allowed in alias names.
905
906If ATTR includes aliases, those aliases will be expanded at definition time
907and their values will be used to define the new alias.  This means that if you
908define an alias A in terms of another alias B, and then later redefine alias
909B, the value of alias A will not change.
910
911If ATTR is not specified, coloralias() returns the standard attribute or
912attributes to which ALIAS is aliased, if any, or undef if ALIAS does not
913exist.  If it is aliased to multiple attributes, the return value will be a
914single string and the attributes will be separated by spaces.
915
916This is the same facility used by the ANSI_COLORS_ALIASES environment
917variable (see L</ENVIRONMENT> below) but can be used at runtime, not just
918when the module is loaded.
919
920Later invocations of coloralias() with the same ALIAS will override
921earlier aliases.  There is no way to remove an alias.
922
923Aliases have no effect on the return value of uncolor().
924
925B<WARNING>: Aliases are global and affect all callers in the same process.
926There is no way to set an alias limited to a particular block of code or a
927particular object.
928
929=back
930
931=head2 Constant Interface
932
933Alternately, if you import C<:constants>, you can use the following
934constants directly:
935
936  CLEAR           RESET             BOLD            DARK
937  FAINT           ITALIC            UNDERLINE       UNDERSCORE
938  BLINK           REVERSE           CONCEALED
939
940  BLACK           RED               GREEN           YELLOW
941  BLUE            MAGENTA           CYAN            WHITE
942  BRIGHT_BLACK    BRIGHT_RED        BRIGHT_GREEN    BRIGHT_YELLOW
943  BRIGHT_BLUE     BRIGHT_MAGENTA    BRIGHT_CYAN     BRIGHT_WHITE
944
945  ON_BLACK        ON_RED            ON_GREEN        ON_YELLOW
946  ON_BLUE         ON_MAGENTA        ON_CYAN         ON_WHITE
947  ON_BRIGHT_BLACK ON_BRIGHT_RED     ON_BRIGHT_GREEN ON_BRIGHT_YELLOW
948  ON_BRIGHT_BLUE  ON_BRIGHT_MAGENTA ON_BRIGHT_CYAN  ON_BRIGHT_WHITE
949
950These are the same as color('attribute') and can be used if you prefer
951typing:
952
953    print BOLD BLUE ON_WHITE "Text", RESET, "\n";
954
955to
956
957    print colored ("Text", 'bold blue on_white'), "\n";
958
959(Note that the newline is kept separate to avoid confusing the terminal as
960described above since a background color is being used.)
961
962If you import C<:constants256>, you can use the following constants
963directly:
964
965  ANSI0 .. ANSI255
966  GREY0 .. GREY23
967
968  RGBXYZ (for X, Y, and Z values from 0 to 5, like RGB000 or RGB515)
969
970  ON_ANSI0 .. ON_ANSI255
971  ON_GREY0 .. ON_GREY23
972
973  ON_RGBXYZ (for X, Y, and Z values from 0 to 5)
974
975Note that C<:constants256> does not include the other constants, so if you
976want to mix both, you need to include C<:constants> as well.  You may want
977to explicitly import at least C<RESET>, as in:
978
979    use Term::ANSIColor 4.00 qw(RESET :constants256);
980
981True color and aliases are not supported by the constant interface.
982
983When using the constants, if you don't want to have to remember to add the
984C<, RESET> at the end of each print line, you can set
985$Term::ANSIColor::AUTORESET to a true value.  Then, the display mode will
986automatically be reset if there is no comma after the constant.  In other
987words, with that variable set:
988
989    print BOLD BLUE "Text\n";
990
991will reset the display mode afterward, whereas:
992
993    print BOLD, BLUE, "Text\n";
994
995will not.  If you are using background colors, you will probably want to
996either use say() (in newer versions of Perl) or print the newline with a
997separate print statement to avoid confusing the terminal.
998
999If $Term::ANSIColor::AUTOLOCAL is set (see below), it takes precedence
1000over $Term::ANSIColor::AUTORESET, and the latter is ignored.
1001
1002The subroutine interface has the advantage over the constants interface in
1003that only two subroutines are exported into your namespace, versus
1004thirty-eight in the constants interface, and aliases and true color attributes
1005are supported.  On the flip side, the constants interface has the advantage of
1006better compile time error checking, since misspelled names of colors or
1007attributes in calls to color() and colored() won't be caught until runtime
1008whereas misspelled names of constants will be caught at compile time.  So,
1009pollute your namespace with almost two dozen subroutines that you may not even
1010use that often, or risk a silly bug by mistyping an attribute.  Your choice,
1011TMTOWTDI after all.
1012
1013=head2 The Color Stack
1014
1015You can import C<:pushpop> and maintain a stack of colors using PUSHCOLOR,
1016POPCOLOR, and LOCALCOLOR.  PUSHCOLOR takes the attribute string that
1017starts its argument and pushes it onto a stack of attributes.  POPCOLOR
1018removes the top of the stack and restores the previous attributes set by
1019the argument of a prior PUSHCOLOR.  LOCALCOLOR surrounds its argument in a
1020PUSHCOLOR and POPCOLOR so that the color resets afterward.
1021
1022If $Term::ANSIColor::AUTOLOCAL is set, each sequence of color constants
1023will be implicitly preceded by LOCALCOLOR.  In other words, the following:
1024
1025    {
1026        local $Term::ANSIColor::AUTOLOCAL = 1;
1027        print BLUE "Text\n";
1028    }
1029
1030is equivalent to:
1031
1032    print LOCALCOLOR BLUE "Text\n";
1033
1034If $Term::ANSIColor::AUTOLOCAL is set, it takes precedence over
1035$Term::ANSIColor::AUTORESET, and the latter is ignored.
1036
1037When using PUSHCOLOR, POPCOLOR, and LOCALCOLOR, it's particularly
1038important to not put commas between the constants.
1039
1040    print PUSHCOLOR BLUE "Text\n";
1041
1042will correctly push BLUE onto the top of the stack.
1043
1044    print PUSHCOLOR, BLUE, "Text\n";    # wrong!
1045
1046will not, and a subsequent pop won't restore the correct attributes.
1047PUSHCOLOR pushes the attributes set by its argument, which is normally a
1048string of color constants.  It can't ask the terminal what the current
1049attributes are.
1050
1051=head2 Supporting CLICOLOR
1052
1053L<https://bixense.com/clicolors/> proposes a standard for enabling and
1054disabling color output from console commands using two environment variables,
1055CLICOLOR and CLICOLOR_FORCE.  Term::ANSIColor cannot automatically support
1056this standard, since the correct action depends on where the output is going
1057and Term::ANSIColor may be used in a context where colors should always be
1058generated even if CLICOLOR is set in the environment.  But you can use the
1059supported environment variable ANSI_COLORS_DISABLED to implement CLICOLOR in
1060your own programs with code like this:
1061
1062    if (exists($ENV{CLICOLOR}) && $ENV{CLICOLOR} == 0) {
1063        if (!$ENV{CLICOLOR_FORCE}) {
1064            $ENV{ANSI_COLORS_DISABLED} = 1;
1065        }
1066    }
1067
1068If you are using the constant interface, be sure to include this code before
1069you use any color constants (such as at the very top of your script), since
1070this environment variable is only honored the first time a color constant is
1071seen.
1072
1073Be aware that this will export ANSI_COLORS_DISABLED to any child processes of
1074your program as well.
1075
1076=head1 DIAGNOSTICS
1077
1078=over 4
1079
1080=item Bad color mapping %s
1081
1082(W) The specified color mapping from ANSI_COLORS_ALIASES is not valid and
1083could not be parsed.  It was ignored.
1084
1085=item Bad escape sequence %s
1086
1087(F) You passed an invalid ANSI escape sequence to uncolor().
1088
1089=item Bareword "%s" not allowed while "strict subs" in use
1090
1091(F) You probably mistyped a constant color name such as:
1092
1093    $Foobar = FOOBAR . "This line should be blue\n";
1094
1095or:
1096
1097    @Foobar = FOOBAR, "This line should be blue\n";
1098
1099This will only show up under use strict (another good reason to run under
1100use strict).
1101
1102=item Cannot alias standard color %s
1103
1104(F) The alias name passed to coloralias() matches a standard color name.
1105Standard color names cannot be aliased.
1106
1107=item Cannot alias standard color %s in %s
1108
1109(W) The same, but in ANSI_COLORS_ALIASES.  The color mapping was ignored.
1110
1111=item Invalid alias name %s
1112
1113(F) You passed an invalid alias name to coloralias().  Alias names must
1114consist only of alphanumerics, C<.>, C<->, and C<_>.
1115
1116=item Invalid alias name %s in %s
1117
1118(W) You specified an invalid alias name on the left hand of the equal sign
1119in a color mapping in ANSI_COLORS_ALIASES.  The color mapping was ignored.
1120
1121=item Invalid attribute name %s
1122
1123(F) You passed an invalid attribute name to color(), colored(), or
1124coloralias().
1125
1126=item Invalid attribute name %s in %s
1127
1128(W) You specified an invalid attribute name on the right hand of the equal
1129sign in a color mapping in ANSI_COLORS_ALIASES.  The color mapping was
1130ignored.
1131
1132=item Name "%s" used only once: possible typo
1133
1134(W) You probably mistyped a constant color name such as:
1135
1136    print FOOBAR "This text is color FOOBAR\n";
1137
1138It's probably better to always use commas after constant names in order to
1139force the next error.
1140
1141=item No comma allowed after filehandle
1142
1143(F) You probably mistyped a constant color name such as:
1144
1145    print FOOBAR, "This text is color FOOBAR\n";
1146
1147Generating this fatal compile error is one of the main advantages of using
1148the constants interface, since you'll immediately know if you mistype a
1149color name.
1150
1151=item No name for escape sequence %s
1152
1153(F) The ANSI escape sequence passed to uncolor() contains escapes which
1154aren't recognized and can't be translated to names.
1155
1156=back
1157
1158=head1 ENVIRONMENT
1159
1160=over 4
1161
1162=item ANSI_COLORS_ALIASES
1163
1164This environment variable allows the user to specify custom color aliases
1165that will be understood by color(), colored(), and colorvalid().  None of
1166the other functions will be affected, and no new color constants will be
1167created.  The custom colors are aliases for existing color names; no new
1168escape sequences can be introduced.  Only alphanumerics, C<.>, C<_>, and
1169C<-> are allowed in alias names.
1170
1171The format is:
1172
1173    ANSI_COLORS_ALIASES='newcolor1=oldcolor1,newcolor2=oldcolor2'
1174
1175Whitespace is ignored.  The alias value can be a single attribute or a
1176space-separated list of attributes.
1177
1178For example the L<Solarized|https://ethanschoonover.com/solarized> colors
1179can be mapped with:
1180
1181    ANSI_COLORS_ALIASES='\
1182        base00=bright_yellow, on_base00=on_bright_yellow,\
1183        base01=bright_green,  on_base01=on_bright_green, \
1184        base02=black,         on_base02=on_black,        \
1185        base03=bright_black,  on_base03=on_bright_black, \
1186        base0=bright_blue,    on_base0=on_bright_blue,   \
1187        base1=bright_cyan,    on_base1=on_bright_cyan,   \
1188        base2=white,          on_base2=on_white,         \
1189        base3=bright_white,   on_base3=on_bright_white,  \
1190        orange=bright_red,    on_orange=on_bright_red,   \
1191        violet=bright_magenta,on_violet=on_bright_magenta'
1192
1193This environment variable is read and applied when the Term::ANSIColor
1194module is loaded and is then subsequently ignored.  Changes to
1195ANSI_COLORS_ALIASES after the module is loaded will have no effect.  See
1196coloralias() for an equivalent facility that can be used at runtime.
1197
1198=item ANSI_COLORS_DISABLED
1199
1200If this environment variable is set to a true value, all of the functions
1201defined by this module (color(), colored(), and all of the constants) will not
1202output any escape sequences and instead will just return the empty string or
1203pass through the original text as appropriate.  This is intended to support
1204easy use of scripts using this module on platforms that don't support ANSI
1205escape sequences.
1206
1207=item NO_COLOR
1208
1209If this environment variable is set to any value, it suppresses generation of
1210escape sequences the same as if ANSI_COLORS_DISABLED is set to a true value.
1211This implements the L<https://no-color.org/> informal standard.  Programs that
1212want to enable color despite NO_COLOR being set will need to unset that
1213environment variable before any constant or function provided by this module
1214is used.
1215
1216=back
1217
1218=head1 COMPATIBILITY
1219
1220Term::ANSIColor was first included with Perl in Perl 5.6.0.
1221
1222The uncolor() function and support for ANSI_COLORS_DISABLED were added in
1223Term::ANSIColor 1.04, included in Perl 5.8.0.
1224
1225Support for dark was added in Term::ANSIColor 1.08, included in Perl
12265.8.4.
1227
1228The color stack, including the C<:pushpop> import tag, PUSHCOLOR,
1229POPCOLOR, LOCALCOLOR, and the $Term::ANSIColor::AUTOLOCAL variable, was
1230added in Term::ANSIColor 2.00, included in Perl 5.10.1.
1231
1232colorstrip() was added in Term::ANSIColor 2.01 and colorvalid() was added
1233in Term::ANSIColor 2.02, both included in Perl 5.11.0.
1234
1235Support for colors 8 through 15 (the C<bright_> variants) was added in
1236Term::ANSIColor 3.00, included in Perl 5.13.3.
1237
1238Support for italic was added in Term::ANSIColor 3.02, included in Perl
12395.17.1.
1240
1241Support for colors 16 through 256 (the C<ansi>, C<rgb>, and C<grey>
1242colors), the C<:constants256> import tag, the coloralias() function, and
1243support for the ANSI_COLORS_ALIASES environment variable were added in
1244Term::ANSIColor 4.00, included in Perl 5.17.8.
1245
1246$Term::ANSIColor::AUTOLOCAL was changed to take precedence over
1247$Term::ANSIColor::AUTORESET, rather than the other way around, in
1248Term::ANSIColor 4.00, included in Perl 5.17.8.
1249
1250C<ansi16> through C<ansi255>, as aliases for the C<rgb> and C<grey> colors,
1251and the corresponding C<on_ansi> names and C<ANSI> and C<ON_ANSI> constants
1252were added in Term::ANSIColor 4.06, included in Perl 5.25.7.
1253
1254Support for true color (the C<rNNNgNNNbNNN> and C<on_rNNNgNNNbNNN>
1255attributes), defining aliases in terms of other aliases, and aliases mapping
1256to multiple attributes instead of only a single attribute was added in
1257Term::ANSIColor 5.00.
1258
1259Support for NO_COLOR was added in Term::ANSIColor 5.01.
1260
1261=head1 RESTRICTIONS
1262
1263Both colored() and many uses of the color constants will add the reset escape
1264sequence after a newline.  If a program mixes colored output to standard
1265output with output to standard error, this can result in the standard error
1266text having the wrong color because the reset escape sequence hasn't yet been
1267flushed to the display (since standard output to a terminal is line-buffered
1268by default).  To avoid this, either set autoflush() on STDOUT or set
1269$Term::ANSIColor::EACHLINE to C<"\n">.
1270
1271It would be nice if one could leave off the commas around the constants
1272entirely and just say:
1273
1274    print BOLD BLUE ON_WHITE "Text\n" RESET;
1275
1276but the syntax of Perl doesn't allow this.  You need a comma after the
1277string.  (Of course, you may consider it a bug that commas between all the
1278constants aren't required, in which case you may feel free to insert
1279commas unless you're using $Term::ANSIColor::AUTORESET or
1280PUSHCOLOR/POPCOLOR.)
1281
1282For easier debugging, you may prefer to always use the commas when not
1283setting $Term::ANSIColor::AUTORESET or PUSHCOLOR/POPCOLOR so that you'll
1284get a fatal compile error rather than a warning.
1285
1286It's not possible to use this module to embed formatting and color
1287attributes using Perl formats.  They replace the escape character with a
1288space (as documented in L<perlform(1)>), resulting in garbled output from
1289the unrecognized attribute.  Even if there were a way around that problem,
1290the format doesn't know that the non-printing escape sequence is
1291zero-length and would incorrectly format the output.  For formatted output
1292using color or other attributes, either use sprintf() instead or use
1293formline() and then add the color or other attributes after formatting and
1294before output.
1295
1296=head1 NOTES
1297
1298The codes generated by this module are standard terminal control codes,
1299complying with ECMA-048 and ISO 6429 (generally referred to as "ANSI
1300color" for the color codes).  The non-color control codes (bold, dark,
1301italic, underline, and reverse) are part of the earlier ANSI X3.64
1302standard for control sequences for video terminals and peripherals.
1303
1304Note that not all displays are ISO 6429-compliant, or even X3.64-compliant
1305(or are even attempting to be so).  This module will not work as expected
1306on displays that do not honor these escape sequences, such as cmd.exe,
13074nt.exe, and command.com under either Windows NT or Windows 2000.  They
1308may just be ignored, or they may display as an ESC character followed by
1309some apparent garbage.
1310
1311Jean Delvare provided the following table of different common terminal
1312emulators and their support for the various attributes and others have
1313helped me flesh it out:
1314
1315              clear    bold     faint   under    blink   reverse  conceal
1316 ------------------------------------------------------------------------
1317 xterm         yes      yes      no      yes      yes      yes      yes
1318 linux         yes      yes      yes    bold      yes      yes      no
1319 rxvt          yes      yes      no      yes  bold/black   yes      no
1320 dtterm        yes      yes      yes     yes    reverse    yes      yes
1321 teraterm      yes    reverse    no      yes    rev/red    yes      no
1322 aixterm      kinda   normal     no      yes      no       yes      yes
1323 PuTTY         yes     color     no      yes      no       yes      no
1324 Windows       yes      no       no      no       no       yes      no
1325 Cygwin SSH    yes      yes      no     color    color    color     yes
1326 Terminal.app  yes      yes      no      yes      yes      yes      yes
1327
1328Windows is Windows telnet, Cygwin SSH is the OpenSSH implementation under
1329Cygwin on Windows NT, and Mac Terminal is the Terminal application in Mac
1330OS X.  Where the entry is other than yes or no, that emulator displays the
1331given attribute as something else instead.  Note that on an aixterm, clear
1332doesn't reset colors; you have to explicitly set the colors back to what
1333you want.  More entries in this table are welcome.
1334
1335Support for code 3 (italic) is rare and therefore not mentioned in that
1336table.  It is not believed to be fully supported by any of the terminals
1337listed, although it's displayed as green in the Linux console, but it is
1338reportedly supported by urxvt.
1339
1340Note that codes 6 (rapid blink) and 9 (strike-through) are specified in ANSI
1341X3.64 and ECMA-048 but are not commonly supported by most displays and
1342emulators and therefore aren't supported by this module.  ECMA-048 also
1343specifies a large number of other attributes, including a sequence of
1344attributes for font changes, Fraktur characters, double-underlining, framing,
1345circling, and overlining.  As none of these attributes are widely supported or
1346useful, they also aren't currently supported by this module.
1347
1348Most modern X terminal emulators support 256 colors.  Known to not support
1349those colors are aterm, rxvt, Terminal.app, and TTY/VC.
1350
1351For information on true color support in various terminal emulators, see
1352L<True Colour support|https://gist.github.com/XVilka/8346728>.
1353
1354=head1 AUTHORS
1355
1356Original idea (using constants) by Zenin, reimplemented using subs by Russ
1357Allbery <rra@cpan.org>, and then combined with the original idea by
1358Russ with input from Zenin.  256-color support is based on work by Kurt
1359Starsinic.  Russ Allbery now maintains this module.
1360
1361PUSHCOLOR, POPCOLOR, and LOCALCOLOR were contributed by openmethods.com
1362voice solutions.
1363
1364=head1 COPYRIGHT AND LICENSE
1365
1366Copyright 1996-1998, 2000-2002, 2005-2006, 2008-2018, 2020 Russ Allbery
1367<rra@cpan.org>
1368
1369Copyright 1996 Zenin
1370
1371Copyright 2012 Kurt Starsinic <kstarsinic@gmail.com>
1372
1373This program is free software; you may redistribute it and/or modify it
1374under the same terms as Perl itself.
1375
1376=head1 SEE ALSO
1377
1378The CPAN module L<Term::ExtendedColor> provides a different and more
1379comprehensive interface for 256-color emulators that may be more
1380convenient.  The CPAN module L<Win32::Console::ANSI> provides ANSI color
1381(and other escape sequence) support in the Win32 Console environment.
1382The CPAN module L<Term::Chrome> provides a different interface using
1383objects and operator overloading.
1384
1385ECMA-048 is available on-line (at least at the time of this writing) at
1386L<https://www.ecma-international.org/publications/standards/Ecma-048.htm>.
1387
1388ISO 6429 is available from ISO for a charge; the author of this module
1389does not own a copy of it.  Since the source material for ISO 6429 was
1390ECMA-048 and the latter is available for free, there seems little reason
1391to obtain the ISO standard.
1392
1393The 256-color control sequences are documented at
1394L<https://invisible-island.net/xterm/ctlseqs/ctlseqs.html> (search for
1395256-color).
1396
1397Information about true color support in various terminal emulators and test
1398programs you can run to check the true color support in your terminal emulator
1399are available at L<https://gist.github.com/XVilka/8346728>.
1400
1401L<CLICOLORS|https://bixense.com/clicolors/> and
1402L<NO_COLOR|https://no-color.org/> are useful standards to be aware of, and
1403ideally follow, for any application using color.  Term::ANSIColor complies
1404with the latter.
1405
1406The current version of this module is always available from its web site
1407at L<https://www.eyrie.org/~eagle/software/ansicolor/>.  It is also part
1408of the Perl core distribution as of 5.6.0.
1409
1410=cut
1411
1412# Local Variables:
1413# copyright-at-end-flag: t
1414# End:
1415