From cad18ff4e86e6b3789452d9e0858e915528a1504 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;
It must be specified in the header that it is a completion file and application for which it will complete (may be string if this file provides completions for several applications): +
It must be specified in the header that it is a completion file and application for which it will complete (may be string if this file provides completions for several applications):
{% highlight bash %} #compdef netctl-gui {% endhighlight %} -Next there is flags, additional functions and variables declarations. It should be noted that all functions and variables, which will be used for completions, should return arrays. In my case this scheme looks like this (I left empty these functions in this chapter): +Next there is flags, additional functions and variables declarations. It should be noted that all functions and variables, which will be used for completions, should return arrays. In my case this scheme looks like this (I left empty these functions in this chapter):
{% highlight bash %} # variables @@ -49,14 +48,14 @@ _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 without isolation in a separate function there is a small shamanism, which declares a dependence "application-function": +And finally without isolation in a separate function there is a small shamanism, which declares a dependence "application-function":
{% highlight bash %} case "$service" in @@ -66,12 +65,10 @@ case "$service" in esac {% endhighlight %} - -As it was said above, there are some different ways to create these files. In particular they differ in the flag declaration and their further processing. In my case I will use _arguments
command, which require a specific format of variables: FLAG[description]:MESSAGE:ACTION
. The last two fields are not required and, as you will see below, are not needed in some cases. If you want to add two flags for an action (short and long format), then the format is a little bit complicated: {(FLAG_2)FLAG_1,(FLAG_1)FLAG_2}[description]:MESSAGE:ACTION
. It should be noted that if you want to create completions for two flags but some flags have not a second format. you will should to add following line: {FLAG,FLAG}[description]:MESSAGE:ACTION
. MESSAGE
is a message which will be shown, ACTION
is an action which will be performed after this flag. In this tutorial ACTION
will be following: ->STATE
.
So, according to our requirements, flags declaration will be following: +
So, according to our requirements, flags declaration will be following:
{% highlight bash %} _netctl_gui_arglist=( @@ -84,10 +81,8 @@ _netctl_gui_arglist=( ) {% endhighlight %} - -In my case there are two static arrays (which will not be changed): +
In my case there are two static arrays (which will not be changed):
{% highlight bash %} _netctl_gui_settings=( @@ -101,7 +96,7 @@ _netctl_gui_tabs=( ) {% endhighlight %} -And there is a dynamic array, which should be generated each time. In my case it is a list of files in the specified directory (by the way it may be done by means of zsh): +And there is a dynamic array, which should be generated each time. In my case it is a list of files in the specified directory (by the way it may be done by means of zsh):
{% highlight bash %} _netctl_profiles() { @@ -109,10 +104,8 @@ _netctl_profiles() { } {% endhighlight %} - -Remember, there was something about a state above? It is stored in the variable $state
and in this function we will check what it is to choose the appropriate action. At the beginning of the function we should call _arguments
with our flags.
+
Remember, there was something about a state above? It is stored in the variable $state
and in this function we will check what it is to choose the appropriate action. At the beginning of the function we should call _arguments
with our flags.
File should be places to /usr/share/zsh/site-functions/
with any name (it is recommended to set prefix to _
). You may found the example in my repository.
Список флагов: +
Список флагов:
-h
и --help
не требуют аргументов;-e
и --essid
требуют аргумента в виде строки, без дополнения;-t
и --tab
требуют аргумента в виде строки, дополнение из указанного массива;--set-opts
требует аргумента в виде строки, дополнение из указанного массива, разделены запятыми;В заголовке должно быть обязательно указано, что это файл дополнений и для каких приложений он служит (можно строкой, если в файле будет содержаться дополнение для нескольких команд): +
В заголовке должно быть обязательно указано, что это файл дополнений и для каких приложений он служит (можно строкой, если в файле будет содержаться дополнение для нескольких команд):
{% highlight bash %} #compdef netctl-gui {% endhighlight %} -Дальше идет описание флагов, вспомогательные функции и переменные. Замечу, что функции и переменные, которые будут использоваться для дополнения должны возвращать массивы, а не строки. В моем случае схема выглядит примерно так (все функции и переменные в этой главе умышленно оставлены пустыми): +Дальше идет описание флагов, вспомогательные функции и переменные. Замечу, что функции и переменные, которые будут использоваться для дополнения должны возвращать массивы, а не строки. В моем случае схема выглядит примерно так (все функции и переменные в этой главе умышленно оставлены пустыми):
{% highlight bash %} # variables @@ -49,14 +48,14 @@ _netctl_gui_tabs=() _netctl_profiles() {} {% endhighlight %} -Затем идут основные функции, которые будут вызываться для дополнения для определенной команды. В моем случае команда одна, и функция одна: +Затем идут основные функции, которые будут вызываться для дополнения для определенной команды. В моем случае команда одна, и функция одна:
{% highlight bash %} # work block _netctl-gui() {} {% endhighlight %} -Далее без выделения в отдельную функцию идет небольшое шаманство, связанное с соотнесением приложения, которое было декларировано в первой строке, с функцией в теле скрипта: +Далее без выделения в отдельную функцию идет небольшое шаманство, связанное с соотнесением приложения, которое было декларировано в первой строке, с функцией в теле скрипта:
{% highlight bash %} case "$service" in @@ -66,12 +65,10 @@ case "$service" in esac {% endhighlight %} - -Как я и говорил во введении, существует несколько способов создания подобных файлов. В частности, они различаются декларацией флагов и их дальнейшей обработкой. В данном случае я буду использовать команду _arguments
, которая требует специфичный формат переменных. Выглядит он таким образом ФЛАГ[описание]:СООБЩЕНИЕ:ДЕЙСТВИЕ
. Последние два поля не обязательны и, как Вы увидите чуть ниже, вовсе и не нужны в некоторых местах. Если Вы предусматриваете два флага (короткий и длинный формат) на одно действие, то формат чуть-чуть усложняется: {(ФЛАГ_2)ФЛАГ_1,(ФЛАГ_1)ФЛАГ_2}[описание]:СООБЩЕНИЕ:ДЕЙСТВИЕ
. Замечу, что, если Вы хотите сделать дополнения для двух типов флагов, но некоторые флаги не имеют второй записи, то Вам необходимо продублировать его таким образом: {ФЛАГ,ФЛАГ}[описание]:СООБЩЕНИЕ:ДЕЙСТВИЕ
. СООБЩЕНИЕ
- сообщение, которое будет показано, ДЕЙСТВИЕ
- действие, которое будет выполнено после этого флага. В случае данного туториала, ДЕЙСТВИЕ
будет иметь вид ->СОСТОЯНИЕ
.
Итак, согласно нашим требованиям, получается такое объявление аргументов: +
Итак, согласно нашим требованиям, получается такое объявление аргументов:
{% highlight bash %} _netctl_gui_arglist=( @@ -84,10 +81,8 @@ _netctl_gui_arglist=( ) {% endhighlight %} - -В нашем случае есть два статических массива (не изменятся ни сейчас, ни через пять минут) (массивы умышленно уменьшены): +
В нашем случае есть два статических массива (не изменятся ни сейчас, ни через пять минут) (массивы умышленно уменьшены):
{% highlight bash %} _netctl_gui_settings=( @@ -101,7 +96,7 @@ _netctl_gui_tabs=( ) {% endhighlight %} -И есть динамический массив, который должен каждый раз генерироваться. Он содержит, в данном случае, файлы в указанной директории (это можно сделать и средствами zsh, кстати): +И есть динамический массив, который должен каждый раз генерироваться. Он содержит, в данном случае, файлы в указанной директории (это можно сделать и средствами zsh, кстати):
{% highlight bash %} _netctl_profiles() { @@ -109,10 +104,8 @@ _netctl_profiles() { } {% endhighlight %} - -Помните, там выше было что-то про состояние? Оно хранится в переменной $state
, и в теле функции делается проверка на то, чему оно равно, чтобы подобрать соответствующие действия. В начале также нужно не забыть вызвать _arguments
с нашими флагами.
+
Помните, там выше было что-то про состояние? Оно хранится в переменной $state
, и в теле функции делается проверка на то, чему оно равно, чтобы подобрать соответствующие действия. В начале также нужно не забыть вызвать _arguments
с нашими флагами.
Файл хранится в директории /usr/share/zsh/site-functions/
с произвольным, в общем-то, именем с префиксом _
. Файл примера полностью может быть найден в моем репозитории.