4566b51946e9bc297de325cfa858b742b46cd21d
[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 qw(
6   Devel::REPL::Plugin::Completion
7   Devel::REPL::Plugin::FindVariable
8 );
9
10 around complete => sub {
11   my $orig = shift;
12   my ($self, $text, $document) = @_;
13
14   my $last = $self->last_ppi_element($document);
15   my $incomplete = '';
16
17   # handle an incomplete method name, and back up to the ->
18   if ($last->isa('PPI::Token::Word')) {
19       my $previous = $last->sprevious_sibling
20         or return $orig->(@_);
21       $previous->isa('PPI::Token::Operator') && $previous->content eq '->'
22         or return $orig->(@_);
23       $incomplete = $last->content;
24       $last = $previous;
25   }
26
27   # require a -> here
28   return $orig->(@_)
29     unless $last->isa('PPI::Token::Operator')
30         && $last->content eq '->';
31
32   # ..which is preceded by a word (class name)
33   my $previous = $last->sprevious_sibling
34     or return $orig->(@_);
35   $previous->isa('PPI::Token::Word') || $previous->isa('PPI::Token::Symbol')
36     or return $orig->(@_);
37   my $class;
38
39   # we have a variable, need to look up its class
40   if ($previous->isa('PPI::Token::Symbol')) {
41     my $object_ref = $self->find_variable($previous->content)
42       or return $orig->(@_);
43     $class = blessed($$object_ref)
44       or return $orig->(@_);
45   }
46   else  {
47     $class = $previous->content;
48   }
49
50   # now we have $class->$incomplete
51
52   my $metaclass = Class::MOP::Class->initialize($class);
53
54   my $re = qr/^\Q$incomplete/;
55
56   return $orig->(@_),
57          grep { $_ =~ $re }
58          map  { $_->{name} }
59          $metaclass->compute_all_applicable_methods;
60 };
61
62 1;
63
64 __END__
65
66 =head1 NAME
67
68 Devel::REPL::Plugin::CompletionDriver::Methods - Complete class or object method names
69
70 =head1 AUTHOR
71
72 Shawn M Moore, C<< <sartak at gmail dot com> >>
73
74 =cut
75