1 package Devel::REPL::Plugin::Completion;
2 use Devel::REPL::Plugin;
3 use Scalar::Util 'weaken';
5 use namespace::clean -except => [ 'meta' ];
7 has current_matches => (
11 default => sub { [] },
21 has no_term_class_warning => (
27 before 'read' => sub {
30 if ((!$self->term->isa("Term::ReadLine::Gnu") and !$self->term->isa("Term::ReadLine::Perl"))
31 and !$self->no_term_class_warning) {
32 warn "Term::ReadLine::Gnu or Term::ReadLine::Perl is required for the Completion plugin to work";
33 $self->no_term_class_warning(1);
39 if ($self->term->isa("Term::ReadLine::Gnu")) {
40 $self->term->Attribs->{attempted_completion_function} = sub {
41 $weakself->_completion(@_);
45 if ($self->term->isa("Term::ReadLine::Perl")) {
46 $self->term->Attribs->{completion_function} = sub {
47 $weakself->_completion(@_);
54 my $is_trp = scalar(@_) == 4 ? 1 : 0;
55 my ($self, $text, $line, $start, $end) = @_;
56 $end = $start+length($text) if $is_trp;
58 # we're discarding everything after the cursor for completion purposes
59 # we can't just use $text because we want all the code before the cursor to
60 # matter, not just the current word
61 substr($line, $end) = '';
63 my $document = PPI::Document->new(\$line);
64 return unless defined($document);
66 $document->prune('PPI::Token::Whitespace');
68 my @matches = $self->complete($text, $document);
70 # iterate through the completions
72 if (scalar(@matches)) {
75 return readline::rl_filename_list($text);
78 if (scalar(@matches)) {
79 return $self->term->completion_matches($text, sub {
80 my ($text, $state) = @_;
83 $self->current_matches(\@matches);
84 $self->match_index(0);
87 $self->match_index($self->match_index + 1);
90 return $self->current_matches->[$self->match_index];
93 # fall back to filename completion for Term::ReadLine::Gnu
103 # recursively find the last element
104 sub last_ppi_element {
105 my ($self, $document, $type) = @_;
106 my $last = $document;
107 while ($last->can('last_element') && defined($last->last_element)) {
108 $last = $last->last_element;
109 return $last if $type && $last->isa($type);
120 Devel::REPL::Plugin::Completion - Extensible tab completion
124 Shawn M Moore, C<< <sartak at gmail dot com> >>