Search code examples
perltab-completion

How to inhibit Term::ReadLine's default filename completion?


How can I disable Term::ReadLine's default completion, or rather, make it stop suggesting filename completions at some point?

For example, what do I need to replace return() with in order to inhibit the default completion from the second word onwards?

Neither of these works:

    $attribs->{'filename_completion_function'}=undef;
    $attribs->{'rl_inhibit_completion'}=1;
use Term::ReadLine;

my $term    = new Term::ReadLine 'sample';
my $attribs = $term->Attribs;
$attribs->{attempted_completion_function} = \&sample_completion;

sub sample_completion {
    my ( $text, $line, $start, $end ) = @_;

    # If first word then username completion, else filename completion
    if ( substr( $line, 0, $start ) =~ /^\s*$/ ) {

        return $term->completion_matches( $text,
            $attribs->{'username_completion_function'} );
    }
    else {
        return ();
    }
}

while ( my $input = $term->readline( "> " ) ) {
    ...
}

Solution

  • Define completion_function instead of attempted_completion_function:

    $attribs->{completion_function} = \&completion;
    

    And then return undef if completion should stop, and return $term->completion_matches($text, $attribs->{filename_completion_function}) if filename completion is to take over.

    In the following example, nothing is suggested for the first parameter, but filenames are for the second parameter.

    use Term::ReadLine;
    
    my $term = new Term::ReadLine 'sample';
    my $attribs = $term->Attribs;
    $attribs->{completion_function} = \&completion;
    
    sub completion {
    
      my ( $text, $line, $start ) = @_;
    
      if ( substr( $line, 0, $start ) =~ /^\s*$/) {
    
        return 
    
      } else {
    
        return $term->completion_matches($text, $attribs->{filename_completion_function})
    
      }
    }
    
    while ( my $input = $term->readline ("> ") ) {
      exit 0 if $input eq "q";
    }