1 package Devel::REPL::Plugin::Completion;
2 use Devel::REPL::Plugin;
3 use Scalar::Util 'weaken';
5 use namespace::autoclean;
7 has current_matches => (
11 default => sub { [] },
21 has no_term_class_warning => (
27 has do_readline_filename_completion => ( # so default is no if Completion loaded
34 before 'read' => sub {
37 if ((!$self->term->isa("Term::ReadLine::Gnu") and !$self->term->isa("Term::ReadLine::Perl"))
38 and !$self->no_term_class_warning) {
39 warn "Term::ReadLine::Gnu or Term::ReadLine::Perl is required for the Completion plugin to work";
40 $self->no_term_class_warning(1);
46 if ($self->term->isa("Term::ReadLine::Gnu")) {
47 $self->term->Attribs->{attempted_completion_function} = sub {
48 $weakself->_completion(@_);
52 if ($self->term->isa("Term::ReadLine::Perl")) {
53 $self->term->Attribs->{completion_function} = sub {
54 $weakself->_completion(@_);
61 my $is_trp = scalar(@_) == 4 ? 1 : 0;
62 my ($self, $text, $line, $start, $end) = @_;
63 $end = $start+length($text) if $is_trp;
65 # we're discarding everything after the cursor for completion purposes
66 # we can't just use $text because we want all the code before the cursor to
67 # matter, not just the current word
68 substr($line, $end) = '';
70 my $document = PPI::Document->new(\$line);
71 return unless defined($document);
73 $document->prune('PPI::Token::Whitespace');
75 my @matches = $self->complete($text, $document);
77 # iterate through the completions
79 if (scalar(@matches)) {
82 return ($self->do_readline_filename_completion) ? readline::rl_filename_list($text) : () ;
85 $self->term->Attribs->{attempted_completion_over} = 1 unless $self->do_readline_filename_completion;
86 if (scalar(@matches)) {
87 return $self->term->completion_matches($text, sub {
88 my ($text, $state) = @_;
91 $self->current_matches(\@matches);
92 $self->match_index(0);
95 $self->match_index($self->match_index + 1);
98 return $self->current_matches->[$self->match_index];
110 # recursively find the last element
111 sub last_ppi_element {
112 my ($self, $document, $type) = @_;
113 my $last = $document;
114 while ($last->can('last_element') && defined($last->last_element)) {
115 $last = $last->last_element;
116 return $last if $type && $last->isa($type);
127 Devel::REPL::Plugin::Completion - Extensible tab completion
131 By default, the Completion plugin explicitly does I<not> use the Gnu readline
132 or Term::ReadLine::Perl fallback filename completion.
134 Set the attribute C<do_readline_filename_completion> to 1 to enable this feature.
138 Shawn M Moore, C<< <sartak at gmail dot com> >>