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