aa09f0e9083e043f435696bdcdca744465ffcb55
[p5sagit/Devel-REPL.git] / lib / Devel / REPL / Plugin / CompletionDriver / Methods.pm
1 package Devel::REPL::Plugin::CompletionDriver::Methods;
2 use Devel::REPL::Plugin;
3 use namespace::clean -except => [ 'meta' ];
4
5 with 'Devel::REPL::Plugin::FindVariable';
6
7 around complete => sub {
8   my $orig = shift;
9   my ($self, $text, $document) = @_;
10
11   my $last = $self->last_ppi_element($document);
12   my $incomplete = '';
13
14   # handle an incomplete method name, and back up to the ->
15   if ($last->isa('PPI::Token::Word')) {
16       my $previous = $last->sprevious_sibling
17         or return $orig->(@_);
18       $previous->isa('PPI::Token::Operator') && $previous->content eq '->'
19         or return $orig->(@_);
20       $incomplete = $last->content;
21       $last = $previous;
22   }
23
24   # require a -> here
25   return $orig->(@_)
26     unless $last->isa('PPI::Token::Operator')
27         && $last->content eq '->';
28
29   # ..which is preceded by a word (class name)
30   my $previous = $last->sprevious_sibling
31     or return $orig->(@_);
32   $previous->isa('PPI::Token::Word') || $previous->isa('PPI::Token::Symbol')
33     or return $orig->(@_);
34   my $class;
35
36   # we have a variable, need to look up its class
37   if ($previous->isa('PPI::Token::Symbol')) {
38     my $object_ref = $self->find_variable($previous->content)
39       or return $orig->(@_);
40     $class = blessed($$object_ref)
41       or return $orig->(@_);
42   }
43   else  {
44     $class = $previous->content;
45   }
46
47   # now we have $class->$incomplete
48
49   my $metaclass = Class::MOP::Class->initialize($class);
50
51   my $re = qr/^\Q$incomplete/;
52
53   return $orig->(@_),
54          grep { $_ =~ $re }
55          map  { $_->{name} }
56          $metaclass->compute_all_applicable_methods;
57 };
58
59 1;
60
61 __END__
62
63 =head1 NAME
64
65 Devel::REPL::Plugin::CompletionDriver::Methods - Complete class or object method names
66
67 =cut
68