Commit | Line | Data |
80fa249c |
1 | package Devel::REPL::Plugin::History; |
2 | |
6a5409bc |
3 | use Devel::REPL::Plugin; |
aa8b7647 |
4 | use namespace::autoclean; |
80fa249c |
5 | |
6 | has 'history' => ( |
b595a818 |
7 | isa => 'ArrayRef', is => 'rw', |
8 | lazy => 1, |
78453011 |
9 | default => sub { [] } |
10 | ); |
11 | |
12 | # lazy so ReadLineHistory Plugin can set this |
13 | has 'have_readline_history' => ( |
b595a818 |
14 | is => 'rw', |
15 | lazy => 1, |
78453011 |
16 | default => sub { 0 } |
80fa249c |
17 | ); |
18 | |
19 | sub push_history { |
78453011 |
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 | } |
80fa249c |
31 | } |
32 | |
33 | around 'read' => sub { |
78453011 |
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); |
80fa249c |
49 | } |
78453011 |
50 | } |
51 | return $line; |
80fa249c |
52 | }; |
53 | |
54 | sub history_call { |
78453011 |
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; |
80fa249c |
67 | }; |
68 | |
69 | 1; |
cfd1094b |
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 | |