user3636583
user3636583

Reputation: 177

Using completion function in Term::ReadLine::Gnu

I want to make a console and change the automatic completion function when I press tab but I want to differentiate between two cases:

  1. If I press tab and the beginning of the command matches a list I supplied in an array, the auto complete will be according to this array.
  2. If I press tab and the command isn't recognized from the list I supplied, I want the generic completion function to work, so t hat it will auto complete directories and file names in the current directory.

Is it possible? Thanks a lot.

Edit: I'm trying to do it inside a perl script. I saw this example:

rl_attempted_completion_function

A reference to an alternative function to create matches.

The function is called with TEXT, LINE_BUFFER, START, and END. LINE_BUFFER is a current input buffer string. START and END are indices in LINE_BUFFER saying what the boundaries of TEXT are.

If this function exists and returns null list or undef, or if this variable is set to undef, then an internal function rl_complete() will call the value of $rl_completion_entry_function to generate matches, otherwise the array of strings returned will be used.

The default value of this variable is undef. You can use it as follows;

use Term::ReadLine;
...
my $term = new Term::ReadLine 'sample';
my $attribs = $term->Attribs;
...
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 ();
    }
}
...
$attribs->{attempted_completion_function} = \&sample_completion;

completion_matches(TEXT, ENTRY_FUNC)

What I want to do is that in case when tab is pressed it recognizes a substring from an array I provide, the auto completion will be from that array (if there are multiple matches it will give all of them like a regular unix console). Otherwise, I want the auto completion to be file recognition.

Upvotes: 1

Views: 1124

Answers (1)

scozy
scozy

Reputation: 2582

The subroutine used internally by Term::ReadLine::Gnu to provide the default completion is filename_completion_function, which you can call directly from your custom subroutine:

use Term::ReadLine;

my $term = new Term::ReadLine 'MyTerm';
$term->Attribs->{'completion_entry_function'} = \&my_completion;
my $ans = $term->readline('How can I help you? ');

sub my_completion {
    my ($text, $state) = @_;
    if (my_test) {
        return my_custom_stuff;
    }
    else {
        return Term::ReadLine::Gnu->filename_completion_function($text, $state);
    }
}

Upvotes: 1

Related Questions