make "perl -c script/re.pl" not start up the REPL
[p5sagit/Devel-REPL.git] / lib / Devel / REPL / Plugin / Colors.pm
1 use strict;
2 use warnings;
3 package Devel::REPL::Plugin::Colors;
4
5 use Devel::REPL::Plugin;
6 use Term::ANSIColor;
7 use namespace::autoclean;
8
9 has normal_color => (
10   is => 'rw', lazy => 1,
11   default => 'green',
12 );
13
14 has error_color => (
15   is => 'rw', lazy => 1,
16   default => 'bold red',
17 );
18
19 around format_error => sub {
20   my $orig = shift;
21   my $self = shift;
22   return color($self->error_color)
23        . $orig->($self, @_)
24        . color('reset');
25 };
26
27 # we can't just munge @_ because that screws up DDS
28 around format_result => sub {
29   my $orig = shift;
30   my $self = shift;
31   no warnings 'uninitialized';
32   return join "", (
33     color($self->normal_color),
34     $orig->($self, @_),
35     color('reset'),
36   );
37 };
38
39 # make arbitrary warns colored -- somewhat difficult because warn doesn't
40 # get $self, so we localize $SIG{__WARN__} during eval so it can get
41 # error_color
42
43 sub _wrap_warn {
44   my $orig = shift;
45   my $self = shift;
46
47   local $SIG{__WARN__} = sub {
48     my $warning = shift;
49     chomp $warning;
50     warn color($self->error_color || 'bold red')
51        . $warning
52        . color('reset')
53        . "\n";
54   };
55
56   $orig->($self, @_);
57 };
58
59 around compile => \&_wrap_warn;
60 around execute => \&_wrap_warn;
61
62 1;
63
64 __END__
65
66 =head1 NAME
67
68 Devel::REPL::Plugin::Colors - add color to return values, warnings, and errors
69
70 =head1 SYNOPSIS
71
72     use Devel::REPL;
73
74     my $repl = Devel::REPL->new;
75     $repl->load_plugin('LexEnv');
76     $repl->load_plugin('History');
77     $repl->load_plugin('Colors');
78     $repl->run;
79
80 =head1 DESCRIPTION
81
82 Colors are very pretty.
83
84 This plugin causes certain prints, warns, and errors to be colored. Generally
85 the return value(s) of each line will be colored green (you can override this
86 by setting C<< $_REPL->normal_color >> in your rcfile). Warnings and
87 compile/runtime errors will be colored with C<< $_REPL->error_color >>. This
88 plugin uses L<Term::ANSIColor>, so consult that module for valid colors. The
89 defaults are actually 'green' and 'bold red'.
90
91 =head1 SEE ALSO
92
93 C<Devel::REPL>
94
95 =head1 AUTHOR
96
97 Shawn M Moore, C<< <sartak at gmail dot com> >>
98
99 =head1 COPYRIGHT AND LICENSE
100
101 Copyright (C) 2007 by Shawn M Moore
102
103 This library is free software; you can redistribute it and/or modify
104 it under the same terms as Perl itself.
105
106 =cut