From 1c90f69b275c6db881fcba20f84462d25cd9ccb9 Mon Sep 17 00:00:00 2001
From: arcan1s Here is a flag list:
+ Here is a flag list:
--h
and --help
do not require any arguments;-e
and --essid
require a string argument without completion;-t
and --tab
require a string argument, there is a completion from the specified array;--set-opts
requires a string argument, there is a completion from the specified array comma separated;
Here all variables must return an array. And there no specific formats. First we declare the flags and then we describe all other variables. As I am not going to describe the functions in more detail below I remind you that _netctl_profiles()
should be generated each time:
+
Here all variables must return an array. And there no specific formats. First we declare the flags and then we describe all other variables. As I am not going to describe the functions in more detail below I remind you that _netctl_profiles()
should be generated each time:
Then there are main functions, which will be called for completion of specific application. In my case this there is only one applications, so there is only one function:
{% highlight bash %} # work block _netctl-gui() {} {% endhighlight %} -And finally again without isolation in a separate function we create a dependence "function-application": +And finally again without isolation in a separate function we create a dependence "function-application":
{% highlight bash %} complete -F _netctl_gui netctl-gui {% endhighlight %} -As it was said above there is no specific format, so all available flags declare by array: +
As it was said above there is no specific format, so all available flags declare by array:
{% highlight bash %} _netctl_gui_arglist=( @@ -77,10 +75,8 @@ _netctl_gui_arglist=( ) {% endhighlight %} - -I just give a function that looked like this in zsh: +
I just give a function that looked like this in zsh:
{% highlight bash %} _netctl_profiles() { @@ -88,7 +84,7 @@ _netctl_profiles() { } {% endhighlight %} -Bash does not allow to do so, so this function should be a little changed: +Bash does not allow to do so, so this function should be a little changed:
{% highlight bash %} _netctl_profiles() { @@ -96,12 +92,10 @@ _netctl_profiles() { } {% endhighlight %} - -The variable COMPREPLY
responds for completion in Bash. To keep track of the current state function _get_comp_words_by_ref
must be called with parameters cur
(current flag) and prev
(previous flag, it is the state). Also some point for case are needed (variables want*
). Function compgen
is used for completion generation. A list of words is given after flag -W
. (Also there is flag -F
which requires a function as argument, but it gives warning for me.) The last argument is a current string to which you want to generate completion.
So, here is our function: +
So, here is our function:
{% highlight bash %} _netctl_gui() { @@ -138,7 +132,5 @@ _netctl_gui() { } {% endhighlight %} - -File should be places to /usr/share/bash-completion/completions/
with any name. You may found the example in my repository.
Список флагов: +
Список флагов:
-h
и --help
не требуют аргументов;-e
и --essid
требуют аргумента в виде строки, без дополнения;-t
и --tab
требуют аргумента в виде строки, дополнение из указанного массива;--set-opts
требует аргумента в виде строки, дополнение из указанного массива, разделены запятыми;Здесь все переменные должны возвращать массив. Каких-либо особых форматов тут уже нет. Сначала опишем флаги, потом уже все остальные переменные. Я напомню (так как ниже я уже не буду приводить функции более подробно), что _netctl_profiles()
, в отличие от других переменных, должна возвращать актуальный на данный момент массив:
+
Здесь все переменные должны возвращать массив. Каких-либо особых форматов тут уже нет. Сначала опишем флаги, потом уже все остальные переменные. Я напомню (так как ниже я уже не буду приводить функции более подробно), что _netctl_profiles()
, в отличие от других переменных, должна возвращать актуальный на данный момент массив:
Затем идут основные функции, которые будут вызываться для дополнения для определенной команды. В моем случае команда одна, и функция одна:
{% highlight bash %} # work block _netctl-gui() {} {% endhighlight %} -Далее, опять, без выделения в отдельную функцию делаем соответствие "функция-команда": +Далее, опять, без выделения в отдельную функцию делаем соответствие "функция-команда":
{% highlight bash %} complete -F _netctl_gui netctl-gui {% endhighlight %} - -Как было сказано выше, особого формата тут нет, доступные флаги располагаются просто массивом: +
Как было сказано выше, особого формата тут нет, доступные флаги располагаются просто массивом:
{% highlight bash %} _netctl_gui_arglist=( @@ -77,10 +74,8 @@ _netctl_gui_arglist=( ) {% endhighlight %} - -Приведу только функцию, которая в zsh выглядела таким образом: +
Приведу только функцию, которая в zsh выглядела таким образом:
{% highlight bash %} _netctl_profiles() { @@ -88,7 +83,7 @@ _netctl_profiles() { } {% endhighlight %} -В bash так не получится, пришлось чуть-чуть изменить: +В bash так не получится, пришлось чуть-чуть изменить:
{% highlight bash %} _netctl_profiles() { @@ -96,12 +91,10 @@ _netctl_profiles() { } {% endhighlight %} - -За дополнение в bash отвечает переменная COMPREPLY
. Для отслеживания текущего состояния нужно вызвать функцию _get_comp_words_by_ref
с параметрами cur
(текущая опция) и prev
(предыдущая, собственно состояние). Ну и нужно несколько точек, на которых сворачивать в определенную часть case (переменные want*
). Для генерации дополнения используется compgen
. После флага -W
ему подается список слов. (Есть еще флаг -F
, который вызывает функцию, но у меня он помимо этого еще и ворнинг выдает.) Последним аргументом идет текущая строка, к которой и нужно генерировать дополнение.
Таким образом, наша функция выглядит так: +
Таким образом, наша функция выглядит так:
{% highlight bash %} _netctl_gui() { @@ -138,7 +131,5 @@ _netctl_gui() { } {% endhighlight %} - -Файл хранится в директории /usr/share/bash-completion/completions/
с произвольным именем. Файл примера полностью может быть найден в моем репозитории.