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