17592b84f56d973135e9ad29ac572ed8f825c63b
[p5sagit/Devel-REPL.git] / lib / Devel / REPL / Plugin / Colors.pm
1 package Devel::REPL::Plugin::Colors;
2
3 use Moose::Role;
4 use Term::ANSIColor;
5 use namespace::clean -except => [ 'meta' ];
6
7 has normal_color => (
8   is => 'rw', lazy => 1,
9   default => 'green',
10 );
11
12 has error_color => (
13   is => 'rw', lazy => 1,
14   default => '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   return join "", (
30     color($self->normal_color),
31     $orig->($self, @_),
32     color('reset'),
33   );
34 };
35
36 # make arbitrary warns colored -- somewhat difficult because warn doesn't
37 # get $self, so we localize $SIG{__WARN__} during eval so it can get
38 # error_color
39
40 sub _wrap_warn {
41   my $orig = shift;
42   my $self = shift;
43
44   local $SIG{__WARN__} = sub {
45     my $warning = shift;
46     chomp $warning;
47     warn color($self->error_color || 'bold red')
48        . $warning
49        . color('reset')
50        . "\n";
51   };
52
53   $orig->($self, @_);
54 };
55
56 around compile => \&_wrap_warn;
57 around execute => \&_wrap_warn;
58
59 1;
60
61 __END__
62
63 =head1 NAME
64
65 Devel::REPL::Plugin::Colors - add color to return values, warnings, and errors
66
67 =head1 SYNOPSIS
68
69     #!/usr/bin/perl 
70
71     use lib './lib';
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