9ce0674dbccf300e8e2dcf3578c8d2811a106812
[p5sagit/Devel-REPL.git] / lib / Devel / REPL / Plugin / CompletionDriver / Globals.pm
1 package Devel::REPL::Plugin::CompletionDriver::Globals;
2 use Devel::REPL::Plugin;
3 use namespace::clean -except => [ 'meta' ];
4
5 sub BEFORE_PLUGIN {
6     my $self = shift;
7     $self->load_plugin('Completion');
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
16   return $orig->(@_)
17     unless $last->isa('PPI::Token::Symbol')
18         || $last->isa('PPI::Token::Word');
19
20   my $sigil = $last =~ s/^[\$\@\%\&\*]// ? $1 : undef;
21   my $re = qr/^\Q$last/;
22
23   my @package_fragments = split qr/::|'/, $last;
24
25   # split drops the last fragment if it's empty
26   push @package_fragments, '' if $last =~ /(?:'|::)$/;
27
28   # the beginning of the variable, or an incomplete package name
29   my $incomplete = pop @package_fragments;
30
31   # recurse for the complete package fragments
32   my $stash = \%::;
33   for (@package_fragments) {
34     $stash = $stash->{"$_\::"};
35   }
36
37   # collect any variables from this stash
38   my @found = grep { /$re/ }
39               map  { join '::', @package_fragments, $_ }
40               keys %$stash;
41
42   # check to see if it's an incomplete package name, and add its variables
43   # so Devel<TAB> is completed correctly
44   for my $key (keys %$stash) {
45       next unless $key =~ /::$/;            # only look at deeper packages
46       next unless $key =~ /^\Q$incomplete/; # only look at matching packages
47       push @found,
48         map { join '::', @package_fragments, $_ }
49         map { "$key$_" } # $key already has trailing ::
50         keys %{ $stash->{$key} };
51   }
52
53   return $orig->(@_), @found;
54 };
55
56 1;
57
58 __END__
59
60 =head1 NAME
61
62 Devel::REPL::Plugin::CompletionDriver::Globals - Complete global variables, packages, namespaced functions
63
64 =head1 AUTHOR
65
66 Shawn M Moore, C<< <sartak at gmail dot com> >>
67
68 =cut
69