如何在Perl的Term :: Shell中自定义选项卡完成?

时间:2009-07-24 12:02:10

标签: perl tab-completion

我正在使用Term::Shell包来实现CLI工具。此软件包提供API:comp_CMD

只要用户按下TAB,就会调用此函数。 我的要求是:

shell> stack TAB

over under

`shell>堆叠在 TAB

flow sample junk

但默认comp_CMD仅提供一组TAB选项,例如

shell> stack TAB

over under

`shell>堆叠在 TAB

over under ###问题就在这里

此处不是 over ,而是希望获得 flow sample junk

2 个答案:

答案 0 :(得分:3)

使用comp_*样式处理程序,只能将一个完成与最后一个不完整的单词匹配。但幸运的是,您可以通过覆盖catch_comp函数来获得所需的结果,如下所示;它让一个匹配整个命令行:

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]);
}

答案 1 :(得分:0)

我想在这里添加一件事......

在覆盖rl_complete子例程之后,我们还必须覆盖comp__(为TAB调用的默认子例程)以避免重复打印子命令。