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