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