簡體   English   中英

Bash / php - 為參數實現tab鍵自動完成的任何方法?

[英]Bash/php - any way to implement tab key autocomplete for arguments?

我有一個PHP命令行腳本,它將作業啟動到作業服務器,作業名稱是一個參數。 作業名稱是命名空間,例如Foo:Bar_Baz_JobName。 有沒有辦法實現自動完成,比如如何鍵入文件名的前幾個字母,然后按tab bash為你完成文件名。 我知道它可以完成,因為tab-completion在ubuntu上使用apt-get工作,我只是不知道它是否可以在PHP中完成。

自動完成是使用GNU readline庫完成的,顯然可以從PHP 訪問 具體來說,請看readline_completion_function 用法很簡單; 你用一個參數調用readline_completion_function ,一個處理完成的回調函數。 回調函數將前幾個字母(基本上是按TAB之前鍵入的任何內容)作為輸入,並應返回可能匹配的數組。

是! 你可以用PHP做到這一點!

CLIFramework提供了一個命令,可幫助您通過命令定義生成bash完成腳本。

您還可以在PHP中定義參數完成,生成的bash / zsh完成將在運行時從PHP返回執行結果:

https://github.com/c9s/CLIFramework

截屏(bash):

在此輸入圖像描述

截屏視頻(zsh):

在此輸入圖像描述

您可以嘗試使用readline ,更具體地說,使用readline_completion_function函數。

關於readline_completion_function

我會說考慮到你正在尋找的交互類型(apt-get autocomplete),這種方法並不好。

事實上,在獲得自動完成功能之前,您必須運行腳本然后才能訪問自動完成功能。

自動完成功能是部分功能。 所以,它就像bash自動完成而不是zsh。

在shell中:

➜  ~ php test.php (enter) 
Custom command: (tab)
a b c
Custom command: (tab)
a b c

代碼是:

<?php
// test.php
class AutoController
{

    private static function getCommandsArray()
    {
        $my_dir = array('a', 'b', 'c');
        return $my_dir;
    }

    /**
     * The callback which is returning an array with strings, which will be
     * auto-completed.
     *
     * @param $input
     * @param $index
     * @return array
     */
    private static function completionCallback($input, $index)
    {
        return self::getCommandsArray();
    }

    /**
     * The method which is handling the autocompletion. After it's runned, you can
     * autocomplete your commands by hitting the tab-button.
     */
    public function actionCompl()
    {
        readline_completion_function(array('self', 'completionCallback'));

        $command_input = readline("Custom command: ");

        passthru('echo ' . $command_input);
    }
}

$a = new AutoController();
$a->actionCompl();

關於運行時自動完成

正如c9s所建議的那樣 ,可以獲得這種功能,但可以extending你的bash的自動完成功能,而不是PHP。

因此,如果你看到CLIFramework的自動完成功能,你會看到:

BashGenerator.php
ZshGenerator.php

其中用於生成bash腳本以擴展bash或zsh自動完成。

因此,它取決於您使用的方式來進行自動完成。

一些參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM