2017-06-05

一个 zsh 插件,为 adb 添加自动补全

UPDATE 2017.12.30

测试了更多 case
https://github.com/robbyrussell/oh-my-zsh/pull/6489

Getting started

声明一个命令补全

1
#compdef foobar

Utility functions

  1. _describe simple describe for command, check oh-my-zsh/plugin/adb.

    1
    2
    3
    4
    #compdef cmd
    local -a options
    options=('-c:description for -c opt' '-d:description for -d opt')
    _describe 'values' options

local -a:
The names refer to array parameters. An array parameter may be created this way, but it may not be assigned to in the typeset statement. When displaying, both normal and associative arrays are shown.

  1. _alternative like _describe,but you can run shell or call function for completion candidates.

    1
    _alternative 'args:custom args:(a b c)' 'files:filenames:_files'
  2. _arguments,

    Basic option specifications take the form -OPT[DESCRIPTION], e.g. like this:

    1
    2
    _arguments '-s[sort output]' '--l[long output]' '-l[long output]'

    Arguments for the option can be specified after the option description in this form -OPT[DESCRIPTION]:MESSAGE:ACTION

    1
    _arguments '-f[input file]:filename:_files' 
  3. _regex_arguments

_values, _sep_parts, & _multi_parts

  1. _values

Completion Special Parameters

  1. CURRENT
    This is the number of the current word, i.e. the word the cursor is currently on in the words array. Note that this value is only correct if the ksharrays option is not set.

OK

知道这些简单地命令, 已经能大概看懂部分插件的代码(比如现有 _adb 中只有简单的基本命令提示).

接下来就参照其他插件, 给 -s 加上补全逻辑就收工了.

1
2
3
4
5
6
7
8
9
10
11
_arguments \
'-s[devices]:specify device:->specify_device' \
'*:: :->subcmds' && return 0

case "$state" in
specify_device)
_values 'devices' $(adb devices|awk 'NR>1&& $1 ~ /^[a-zA-Z0-9].*$/ \
{printf "%s[Device_%d:%s] ",$1,++i,$2 }')
return
;;
esac

ok

–> https://github.com/tiiime/oh-my-zsh/blob/master/plugins/adb/_adb


Ref

https://github.com/zsh-users/zsh-completions
http://zsh.sourceforge.net/Doc/Release/