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