如何在 Perl 的 Term::Shell 中自定义制表符补全?

发布于 2024-07-29 04:38:52 字数 665 浏览 4 评论 0原文

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

每当用户按下 TAB 时就会调用此函数。 我的要求是:

shell>; stackTAB

over under

`shell>stack overTAB

流示例垃圾

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

shell> stack TAB

over under

`shell>stack overTAB

over under ### 问题是这里

,我想要的是流样本垃圾,而不是在下面

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北恋 2024-08-05 04:38:52

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

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]);
}
烏雲後面有陽光 2024-08-05 04:38:52

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

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

One more thing i want to add here..

After overriding rl_complete subroutine, we also have to override comp__ (Default subroutine called for TAB) to avoid repeated printing of the subcommands.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文