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