05fca4f0360b4e5e3da3e175d04644d38a2c02c6
[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 has no_term_class_warning => (
22   isa => "Bool",
23   is  => "rw",
24   default => 0,
25 );
26
27 before 'read' => sub {
28   my ($self) = @_;
29
30   unless ($self->term->isa("Term::ReadLine::Gnu") and !$self->no_term_class_warning) {
31     warn "Term::ReadLine::Gnu is required for the Completion plugin to work";
32     $self->no_term_class_warning(1);
33   }
34
35   my $weakself = $self;
36   weaken($weakself);
37
38   $self->term->Attribs->{attempted_completion_function} = sub {
39     $weakself->_completion(@_);
40   };
41 };
42
43 sub _completion {
44   my ($self, $text, $line, $start, $end) = @_;
45
46   # we're discarding everything after the cursor for completion purposes
47   # we can't just use $text because we want all the code before the cursor to
48   # matter, not just the current word
49   substr($line, $end) = '';
50
51   my $document = PPI::Document->new(\$line);
52   return unless defined($document);
53
54   $document->prune('PPI::Token::Whitespace');
55
56   my @matches = $self->complete($text, $document);
57
58   # iterate through the completions
59   return $self->term->completion_matches($text, sub {
60     my ($text, $state) = @_;
61
62     if (!$state) {
63       $self->current_matches(\@matches);
64       $self->match_index(0);
65     }
66     else {
67       $self->match_index($self->match_index + 1);
68     }
69
70     return $self->current_matches->[$self->match_index];
71   });
72 }
73
74 sub complete {
75   return ();
76 }
77
78 # recursively find the last element
79 sub last_ppi_element {
80   my ($self, $document, $type) = @_;
81   my $last = $document;
82   while ($last->can('last_element') && defined($last->last_element)) {
83     $last = $last->last_element;
84     return $last if $type && $last->isa($type);
85   }
86   return $last;
87 }
88
89 1;
90
91 __END__
92
93 =head1 NAME
94
95 Devel::REPL::Plugin::Completion - Extensible tab completion
96
97 =head1 AUTHOR
98
99 Shawn M Moore, C<< <sartak at gmail dot com> >>
100
101 =cut
102