3 package Devel::REPL::Plugin::Completion;
4 # ABSTRACT: Extensible tab completion
6 our $VERSION = '1.003029';
8 use Devel::REPL::Plugin;
9 use Scalar::Util 'weaken';
11 use namespace::autoclean;
13 has current_matches => (
17 default => sub { [] },
27 has no_term_class_warning => (
33 has do_readline_filename_completion => ( # so default is no if Completion loaded
40 before 'read' => sub {
43 if ((!$self->term->isa("Term::ReadLine::Gnu") and !$self->term->isa("Term::ReadLine::Perl"))
44 and !$self->no_term_class_warning) {
45 warn "Term::ReadLine::Gnu or Term::ReadLine::Perl is required for the Completion plugin to work";
46 $self->no_term_class_warning(1);
52 if ($self->term->isa("Term::ReadLine::Gnu")) {
53 $self->term->Attribs->{attempted_completion_function} = sub {
54 $weakself->_completion(@_);
58 if ($self->term->isa("Term::ReadLine::Perl")) {
59 $self->term->Attribs->{completion_function} = sub {
60 $weakself->_completion(@_);
67 my $is_trp = scalar(@_) == 4 ? 1 : 0;
68 my ($self, $text, $line, $start, $end) = @_;
69 $end = $start+length($text) if $is_trp;
71 # we're discarding everything after the cursor for completion purposes
72 # we can't just use $text because we want all the code before the cursor to
73 # matter, not just the current word
74 substr($line, $end) = '';
76 my $document = PPI::Document->new(\$line);
77 return unless defined($document);
79 $document->prune('PPI::Token::Whitespace');
81 my @matches = $self->complete($text, $document);
83 # iterate through the completions
85 if (scalar(@matches)) {
88 return ($self->do_readline_filename_completion) ? readline::rl_filename_list($text) : () ;
91 $self->term->Attribs->{attempted_completion_over} = 1 unless $self->do_readline_filename_completion;
92 if (scalar(@matches)) {
93 return $self->term->completion_matches($text, sub {
94 my ($text, $state) = @_;
97 $self->current_matches(\@matches);
98 $self->match_index(0);
101 $self->match_index($self->match_index + 1);
104 return $self->current_matches->[$self->match_index];
116 # recursively find the last element
117 sub last_ppi_element {
118 my ($self, $document, $type) = @_;
119 my $last = $document;
120 while ($last->can('last_element') && defined($last->last_element)) {
121 $last = $last->last_element;
122 return $last if $type && $last->isa($type);
135 By default, the Completion plugin explicitly does I<not> use the Gnu readline
136 or Term::ReadLine::Perl fallback filename completion.
138 Set the attribute C<do_readline_filename_completion> to 1 to enable this feature.
142 Shawn M Moore, C<< <sartak at gmail dot com> >>