1 package Devel::REPL::Plugin::Completion;
2 use Devel::REPL::Plugin;
3 use Scalar::Util 'weaken';
6 use MooX::Types::MooseLike::Base qw(ArrayRef Int Bool);
8 has current_matches => (
12 default => sub { [] },
22 has no_term_class_warning => (
28 has do_readline_filename_completion => ( # so default is no if Completion loaded
35 before 'read' => sub {
38 if ((!$self->term->isa("Term::ReadLine::Gnu") and !$self->term->isa("Term::ReadLine::Perl"))
39 and !$self->no_term_class_warning) {
40 warn "Term::ReadLine::Gnu or Term::ReadLine::Perl is required for the Completion plugin to work";
41 $self->no_term_class_warning(1);
47 if ($self->term->isa("Term::ReadLine::Gnu")) {
48 $self->term->Attribs->{attempted_completion_function} = sub {
49 $weakself->_completion(@_);
53 if ($self->term->isa("Term::ReadLine::Perl")) {
54 $self->term->Attribs->{completion_function} = sub {
55 $weakself->_completion(@_);
62 my $is_trp = scalar(@_) == 4 ? 1 : 0;
63 my ($self, $text, $line, $start, $end) = @_;
64 $end = $start+length($text) if $is_trp;
66 # we're discarding everything after the cursor for completion purposes
67 # we can't just use $text because we want all the code before the cursor to
68 # matter, not just the current word
69 substr($line, $end) = '';
71 my $document = PPI::Document->new(\$line);
72 return unless defined($document);
74 $document->prune('PPI::Token::Whitespace');
76 my @matches = $self->complete($text, $document);
78 # iterate through the completions
80 if (scalar(@matches)) {
83 return ($self->do_readline_filename_completion) ? readline::rl_filename_list($text) : () ;
86 $self->term->Attribs->{attempted_completion_over} = 1 unless $self->do_readline_filename_completion;
87 if (scalar(@matches)) {
88 return $self->term->completion_matches($text, sub {
89 my ($text, $state) = @_;
92 $self->current_matches(\@matches);
93 $self->match_index(0);
96 $self->match_index($self->match_index + 1);
99 return $self->current_matches->[$self->match_index];
111 # recursively find the last element
112 sub last_ppi_element {
113 my ($self, $document, $type) = @_;
114 my $last = $document;
115 while ($last->can('last_element') && defined($last->last_element)) {
116 $last = $last->last_element;
117 return $last if $type && $last->isa($type);
128 Devel::REPL::Plugin::Completion - Extensible tab completion
132 By default, the Completion plugin explicitly does I<not> use the Gnu readline
133 or Term::ReadLine::Perl fallback filename completion.
135 Set the attribute C<do_readline_filename_completion> to 1 to enable this feature.
139 Shawn M Moore, C<< <sartak at gmail dot com> >>