ae4a8ecc1b231cf11fc2fc5449209396ef1da9d2
[p5sagit/Devel-REPL.git] / lib / Devel / REPL / Plugin / Completion.pm
1 package Devel::REPL::Plugin::Completion;
2 use Devel::REPL::Plugin;
3 use Scalar::Util 'weaken';
4 use PPI;
5 use namespace::clean -except => [ 'meta' ];
6
7 has current_matches => (
8     is => 'rw',
9     isa => 'ArrayRef',
10     lazy => 1,
11     default => sub { [] },
12 );
13
14 has match_index => (
15     is => 'rw',
16     isa => 'Int',
17     lazy => 1,
18     default => sub { 0 },
19 );
20
21 sub BEFORE_PLUGIN {
22   my ($self) = @_;
23
24   my $weakself = $self;
25   weaken($weakself);
26
27   $self->term->Attribs->{attempted_completion_function} = sub {
28     $weakself->_completion(@_);
29   };
30 }
31
32 sub _completion {
33   my ($self, $text, $line, $start, $end) = @_;
34
35   # we're discarding everything after the cursor for completion purposes
36   substr($line, $end) = '';
37
38   my $document = PPI::Document->new(\$line);
39   return unless defined($document);
40
41   my @matches = $self->complete($text, $document);
42
43   # iterate through the completions
44   return $self->term->completion_matches($text, sub {
45     my ($text, $state) = @_;
46
47     if (!$state) {
48       $self->current_matches(\@matches);
49       $self->match_index(0);
50     }
51     else {
52       $self->match_index($self->match_index + 1);
53     }
54
55     return $self->current_matches->[$self->match_index];
56   });
57 }
58
59 sub complete {
60   return ();
61 }
62
63 1;
64