From 1c90f69b275c6db881fcba20f84462d25cd9ccb9 Mon Sep 17 00:00:00 2001 From: arcan1s Date: Mon, 25 Aug 2014 23:58:38 +0400 Subject: [PATCH] update to standards (8) --- ...014-07-17-writting-own-completions-p2.html | 24 ++++++------------ ...014-07-17-writting-own-completions-p2.html | 25 ++++++------------- 2 files changed, 16 insertions(+), 33 deletions(-) diff --git a/_posts/2014-07-17-writting-own-completions-p2.html b/_posts/2014-07-17-writting-own-completions-p2.html index 4a38cc3..bec4577 100644 --- a/_posts/2014-07-17-writting-own-completions-p2.html +++ b/_posts/2014-07-17-writting-own-completions-p2.html @@ -21,7 +21,7 @@ netctl-gui [ -h | --help ] [ -e ESSID | --essid ESSID ] [ -с FILE | --config FI [ -o PROFILE | --open PROFILE ] [ -t NUM | --tab NUM ] [ --set-opts OPTIONS ] {% endhighlight %} -

Here is a flag list: +

Here is a flag list:

-

The file pattern

-

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:

{% highlight bash %} # variables @@ -43,23 +42,22 @@ _netctl_gui_tabs=() _netctl_profiles() {} {% endhighlight %} -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: +

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 %} -

Flags

-

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 %} -

-

Arrays of variables

-

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 %} -

-

Function

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 %} -

-

Conclusion

File should be places to /usr/share/bash-completion/completions/ with any name. You may found the example in my repository.

diff --git a/ru/_posts/2014-07-17-writting-own-completions-p2.html b/ru/_posts/2014-07-17-writting-own-completions-p2.html index 122cf46..c8537ae 100644 --- a/ru/_posts/2014-07-17-writting-own-completions-p2.html +++ b/ru/_posts/2014-07-17-writting-own-completions-p2.html @@ -21,7 +21,7 @@ netctl-gui [ -h | --help ] [ -e ESSID | --essid ESSID ] [ -с FILE | --config FI [ -o PROFILE | --open PROFILE ] [ -t NUM | --tab NUM ] [ --set-opts OPTIONS ] {% endhighlight %} -

Список флагов: +

Список флагов:

-

Структура файла

-

Здесь все переменные должны возвращать массив. Каких-либо особых форматов тут уже нет. Сначала опишем флаги, потом уже все остальные переменные. Я напомню (так как ниже я уже не буду приводить функции более подробно), что _netctl_profiles(), в отличие от других переменных, должна возвращать актуальный на данный момент массив: +

Здесь все переменные должны возвращать массив. Каких-либо особых форматов тут уже нет. Сначала опишем флаги, потом уже все остальные переменные. Я напомню (так как ниже я уже не буду приводить функции более подробно), что _netctl_profiles(), в отличие от других переменных, должна возвращать актуальный на данный момент массив:

{% highlight bash %} # variables @@ -43,23 +42,21 @@ _netctl_gui_tabs=() _netctl_profiles() {} {% endhighlight %} -Затем идут основные функции, которые будут вызываться для дополнения для определенной команды. В моем случае команда одна, и функция одна: +

Затем идут основные функции, которые будут вызываться для дополнения для определенной команды. В моем случае команда одна, и функция одна:

{% 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/ с произвольным именем. Файл примера полностью может быть найден в моем репозитории.