Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I customize tab completion in Perl's Term::Shell?

I am using Term::Shell package to implement a CLI tool. This package provides a API: comp_CMD.

This function is invoked whenever the user presses the TAB. My requirement here is:

shell> stackTAB

over under

`shell>stack overTAB

flow sample junk

But the default comp_CMD provides only one set of TAB options like

shell> stack TAB

over under

`shell>stack overTAB

over under ### THE PROBLEM IS HERE

Instead of over under here, I want to get flow sample junk.

like image 954
Anandan Avatar asked Nov 21 '25 01:11

Anandan


1 Answers

With the comp_* style handlers one can only match one's completions against the last incomplete word. Fortunately, however, you can get the desired result by overriding the catch_comp function like below; it lets one match against whole command line:

my %completion_tree = (
    stack => { under => [],
               over  => [qw(flow sample junk)] }
);

sub catch_comp {
    my $o = shift;
    my ($cmd, $word, $line, $start) = @_;

    my $completed = substr $line, 0, $start;
    $completed =~ s/^\s*//;

    my $tree = \%completion_tree;
    foreach (split m'\s+', $completed) {
        last if ref($tree) ne 'HASH';
        $tree = $tree->{$_};
    }

    my @completions;
    $_ = ref($tree);
    @completions =      @$tree if /ARRAY/;
    @completions = keys %$tree if /HASH/;
    @completions =      ($tree)if /SCALAR/;

    return $o->completions($word, [@completions]);
}
like image 77
Inshallah Avatar answered Nov 24 '25 09:11

Inshallah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!