add use strict; use warnings to modules, just to be sure
[p5sagit/Devel-REPL.git] / lib / Devel / REPL / Plugin / History.pm
CommitLineData
1716b200 1use strict;
2use warnings;
80fa249c 3package Devel::REPL::Plugin::History;
4
6a5409bc 5use Devel::REPL::Plugin;
aa8b7647 6use namespace::autoclean;
80fa249c 7
8has 'history' => (
b595a818 9 isa => 'ArrayRef', is => 'rw',
10 lazy => 1,
78453011 11 default => sub { [] }
12);
13
14# lazy so ReadLineHistory Plugin can set this
15has 'have_readline_history' => (
b595a818 16 is => 'rw',
17 lazy => 1,
78453011 18 default => sub { 0 }
80fa249c 19);
20
21sub push_history {
78453011 22 my ($self, $line) = @_;
23 # Push history is not needed if we have Term::ReadLine
24 # support. We put the test inside push_history() in case
25 # someone has modified it in their code.
26 if ($self->have_readline_history) {
27 # update history to keep consistent with Term::ReadLine
28 $self->history( [ $self->term->GetHistory ] );
29 } else {
30 # not used with Term::ReadLine history support
31 push(@{$self->history}, $line);
32 }
80fa249c 33}
34
35around 'read' => sub {
78453011 36 my $orig = shift;
37 my ($self, @args) = @_;
38 my $line = $self->$orig(@args);
39 if (defined $line) {
40 if ($line =~ m/^!(.*)$/) {
41 my $call = $1;
42 $line = $self->history_call($call);
43 if (defined $line) {
44 $self->print($line."\n");
45 } else {
46 return "'Unable to find ${call} in history'";
47 }
48 }
49 if ($line =~ m/\S/) {
50 $self->push_history($line);
80fa249c 51 }
78453011 52 }
53 return $line;
80fa249c 54};
55
56sub history_call {
78453011 57 my ($self, $call) = @_;
58 if ($call =~ m/^(-?\d+)$/) { # handle !1 or !-1
59 my $idx = $1;
60 $idx-- if ($idx > 0); # !1 gets history element 0
61 my $line = $self->history->[$idx];
62 return $line;
63 }
64 my $re = qr/^\Q${call}\E/;
65 foreach my $line (reverse @{$self->history}) {
66 return $line if ($line =~ $re);
67 }
68 return;
80fa249c 69};
70
711;
cfd1094b 72
73__END__
74
75=head1 NAME
76
77Devel::REPL::Plugin::History - Keep track of all input, provide shortcuts !1, !-1
78
79=cut
80