3 package Devel::REPL::Plugin::Completion;
5 use Devel::REPL::Plugin;
6 use Scalar::Util 'weaken';
8 use namespace::autoclean;
10 has current_matches => (
14 default => sub { [] },
24 has no_term_class_warning => (
30 has do_readline_filename_completion => ( # so default is no if Completion loaded
37 before 'read' => sub {
40 if ((!$self->term->isa("Term::ReadLine::Gnu") and !$self->term->isa("Term::ReadLine::Perl"))
41 and !$self->no_term_class_warning) {
42 warn "Term::ReadLine::Gnu or Term::ReadLine::Perl is required for the Completion plugin to work";
43 $self->no_term_class_warning(1);
49 if ($self->term->isa("Term::ReadLine::Gnu")) {
50 $self->term->Attribs->{attempted_completion_function} = sub {
51 $weakself->_completion(@_);
55 if ($self->term->isa("Term::ReadLine::Perl")) {
56 $self->term->Attribs->{completion_function} = sub {
57 $weakself->_completion(@_);
64 my $is_trp = scalar(@_) == 4 ? 1 : 0;
65 my ($self, $text, $line, $start, $end) = @_;
66 $end = $start+length($text) if $is_trp;
68 # we're discarding everything after the cursor for completion purposes
69 # we can't just use $text because we want all the code before the cursor to
70 # matter, not just the current word
71 substr($line, $end) = '';
73 my $document = PPI::Document->new(\$line);
74 return unless defined($document);
76 $document->prune('PPI::Token::Whitespace');
78 my @matches = $self->complete($text, $document);
80 # iterate through the completions
82 if (scalar(@matches)) {
85 return ($self->do_readline_filename_completion) ? readline::rl_filename_list($text) : () ;
88 $self->term->Attribs->{attempted_completion_over} = 1 unless $self->do_readline_filename_completion;
89 if (scalar(@matches)) {
90 return $self->term->completion_matches($text, sub {
91 my ($text, $state) = @_;
94 $self->current_matches(\@matches);
95 $self->match_index(0);
98 $self->match_index($self->match_index + 1);
101 return $self->current_matches->[$self->match_index];
113 # recursively find the last element
114 sub last_ppi_element {
115 my ($self, $document, $type) = @_;
116 my $last = $document;
117 while ($last->can('last_element') && defined($last->last_element)) {
118 $last = $last->last_element;
119 return $last if $type && $last->isa($type);
130 Devel::REPL::Plugin::Completion - Extensible tab completion
134 By default, the Completion plugin explicitly does I<not> use the Gnu readline
135 or Term::ReadLine::Perl fallback filename completion.
137 Set the attribute C<do_readline_filename_completion> to 1 to enable this feature.
141 Shawn M Moore, C<< <sartak at gmail dot com> >>