Add LexEnv completion plugin. I still owe mst a refactor of the completion subsystem :)
[p5sagit/Devel-REPL.git] / lib / Devel / REPL / Plugin / CompletionDriver / LexEnv.pm
1 package Devel::REPL::Plugin::CompletionDriver::LexEnv;
2 use Devel::REPL::Plugin;
3 use namespace::clean -except => [ 'meta' ];
4
5 sub AFTER_PLUGIN {
6   my ($_REPL) = @_;
7
8   if (!$_REPL->can('lexical_environment')) {
9     warn "Devel::REPL::Plugin::CompletionDriver::LexEnv requires Devel::REPL::Plugin::LexEnv.";
10   }
11 }
12
13 around complete => sub {
14   my $orig = shift;
15   my ($self, $text, $document) = @_;
16
17   # recursively find the last element
18   my $last = $document;
19   while ($last->can('last_element') && defined($last->last_element)) {
20       $last = $last->last_element;
21   }
22
23   return $orig->(@_)
24     unless $last->isa('PPI::Token::Symbol');
25
26   my $sigil = substr($last, 0, 1, '');
27   my $re = qr/^\Q$last/;
28
29   return $orig->(@_),
30          # ReadLine is weirdly inconsistent
31          map  { $sigil eq '%' ? '%' . $_ : $_ }
32          grep { /$re/ }
33          map  { substr($_, 1) } # drop lexical's sigil
34          keys %{$self->lexical_environment->get_context('_')};
35 };
36
37 1;
38