zshで究極のオペレーションを

第5回zshの誇る花形機能“補完”


zshzsh150便


zsh
autoload -U compinit && compinit

2


Tab (C-i) - expand-or-complete


ESC C-d ( C-d) - list-choices (delete-char-or-list)






C-x* - expand-word


C-xg - list-expand



TabESC C-d使ONautolistTabOFFESC C-d  zshrc

1


zsh
% cd /usTab
% cd /usr/                      (/us で始まるファイル名に)

% cd /u/l/a/coTab
% cd /usr/local/apache/conf/    (/ の前に * を補ったパターンで補完)

*Emacs~/.emacs (partial-completion-mode t)

tcsh `set complete=enhance' tcshzsh
zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z} r:|[-_.]=**'

a-zA-ZA-Za-z * 
% ls -F
extra/  httpd.conf  magic  mime.types  original/
% less m.tTab
% less mime.types

便
% ls
highperformance-std.conf        magic
highperformance.conf            mime.types
httpd-std.conf                  ssl-std.conf
httpd.conf                      ssl.conf

httpd.conf
% vi httpd.Tab
% vi httpd-std.conf

`httpd.' Tab httpd-std.conf zshzstyle
zstyle ':completion:*' matcher-list '' 'm:{a-zA-Z}={A-Za-z} r:|[-_.]=**'

 '' '' 'm:{a-zA-Z}={A-Za-z} r:|[-_.]=**' 

ON
zstyle ':completion:*' matcher-list '' 'm:{a-z}={A-Z}' '+m:{A-Z}={a-z}'








`+'



2



% MATab
Completing parameter
MACHTYPE   MAILCHECK  MAILDIR    MAILPATH   MANPATH
% MANTab
% MANPATH=

$VARIABLE ${HOME}$HOME:hzsh
(ホームディレクトリの親ディレクトリにアクセスする例)
% ls ${HOTab
Completing parameter
HOME  HOST
% ls ${HOMTab
% ls ${HOME}/
($HOME値がパス名なので自動的に / が補われる)

(続けて : を入力する)
% ls ${HOME:
(}/ が自動的に消えるので h}/ を入力)

% ls ${HOME:h}/Tab
Completing files
....
($HOME/../ にあるファイル(ディレクトリ)一覧が表示される)

3


SSH
% ssh yTab
Completing remote host name
yankee  yourpc.example.com
Completing login name
yas  yukita  yuuji

ssh
ssh remotehost
ssh username@remotehost

 `ssh y'  ygetent hosts~/.ssh/known_hosts


zstyle ':completion:*' users-hosts \
    user1@{host1,host2} {user2,user3}@{host3,host4}

host1, host2, host3, host4host1host2user1host3host4user2user3


% ssh Tab
Completing remote host name
host1  host2  host3  host4
Completing login name
user1         user2
% ssh uTab
% ssh user
% ssh user1Tab
% ssh user1@
% ssh user1@Tab
% ssh user1@host
% ssh user1@hostTab
Completing remote host name
host1  host2

@usershosts
(ユーザ名のみの場合の補完単語設定)
zstyle ':completion:*' users user1 user2 user3 user4 ...

(ホスト名のみの場合の補完単語設定)
zstyle ':completion:*' hosts host1 host2 host3 host4 ...

4


killIDzsh調
% jobs
[1]    suspended  sudo -H -s
[2]  - suspended  emacs -nw
[3]  + suspended  $EDITOR .zshrc
% ps
  PID TTY   STAT    TIME COMMAND
  356 ttyp0 Is+  0:00.07 -zsh
 1844 ttyp2 O+   0:00.00 ps
25114 ttyp2 Ss   0:00.23 -zsh 
26716 ttyp2 T    0:00.01 vim .zshrc 
28066 ttyp2 T    0:00.52 emacs -nw (emcws)

(上記のようなプロセス起動状況と仮定)

% kill Tab

Completing process ID
  356 ttyp0 Is+  0:00.07 -zsh
25114 ttyp2 Ss+  0:00.23 -zsh
26411 ttyp2 S+   0:00.00 -zsh
26716 ttyp2 T    0:00.01 vim .zshrc
27519 ttyp2 O+   0:00.00 ps
28066 ttyp2 T    0:00.52 emacs -nw (emcws)

(psを裏で起動してkillできるPIDが提示される
 さらに % まで入れるとジョブが補完候補となる)

% kill %Tab
Completing job
%1  -- sudo -H -s
%2  -- emacs -nw
%3  -- $EDITOR .zshrc

ps

zshpsPIDkillPID

zstylePID
zstyle ':completion:*:processes' menu yes select=2


% kill Tab
Completing process ID
  356 ttyp0 Is+  0:00.07 -zsh
 1084 ttyp2 S+   0:00.00 -zsh                            
 9911 ttyp2 O+   0:00.00 ps
25114 ttyp2 Ss+  0:00.28 -zsh
26716 ttyp2 T    0:00.01 vim .zshrc
28066 ttyp2 T    0:00.52 emacs -nw (emcws)

(1行目が反転表示される。
 さらにもう一度Tabをタイプすると)
% kill Tab
Completing process ID
  356 ttyp0 Is+  0:00.07 -zsh
 1084 ttyp2 S+   0:00.00 -zsh                            
 9911 ttyp2 O+   0:00.00 ps
25114 ttyp2 Ss+  0:00.28 -zsh
26716 ttyp2 T    0:00.01 vim .zshrc
28066 ttyp2 T    0:00.52 emacs -nw (emcws)

(次の候補に進み2行目が反転表示される。
 C-n、C-p でも下、上に移動できる。Returnで確定。
 確定するとPIDの番号のみがコマンドラインに入る。)

使PID
zstyle ':completion:*:(processes|jobs)' menu yes select=2

 select=2 2使

5



([1]./configure や make は、その場のファイルを実際に解析して
    引数として適切な補完候補を設定)
% pwd
/home/yuuji/make/apache/apache22/httpd-2.2.13
(Apache2.2 のソースのディレクトリ)
% ./configure --Tab
zsh: do you wish to see all 272 possibilities (273 lines)? y
Completing no arguments
Completing option
--bindir           -- user executables (EPREFIX/bin)
--build            -- configure for building on BUILD # (guessed)
--cache-file       -- cache test results in FILE (disabled)
--config-cache     -- alias for `--cache-file=config.cache'
--datadir          -- read-only architecture-independent # data (DAT
--datarootdir      -- read-only arch.-independent data root # (PREFI
   :
   :
(以下省略)
([2] 処理対象ファイルに応じて補完候補を決定 - tarの場合)
% tar jxpf hTab
% tar jxpf httpd-2.2.13.tar.bz2 Tab
(補完候補取得にアーカイブ内部を調べるのに少し時間がかかる)
% tar jxpf httpd-2.2.13.tar.bz2 httpd-2.2.13/
(格納されているファイル名の共通プレフィクス(ディレクトリ)が出る
 続けて Tab)
% tar jxpf httpd-2.2.13.tar.bz2 httpd-2.2.13/tab
Completing file from archive
.deps             LICENSE           acinclude.m4      httpd.spec
.gdbinit          Makefile.in       apachenw.mcp.zip  include
ABOUT_APACHE      Makefile.win      build             libhttpd.dsp
Apache.dsw        NOTICE            buildconf         modules
BuildAll.dsp      NWGNUmakefile     config.layout     os
BuildBin.dsp      README            configure         server
CHANGES           README-win32.txt  configure.in      srclib
INSTALL           README.platforms  docs              support
InstallBin.dsp    ROADMAP           emacs-style       test
LAYOUT            VERSIONING        httpd.dsp
(格納されているファイル名一覧が出る)

% tar jxpf httpd-2.2.13.tar.bz2 httpd-2.2.13/INtab
% tar jxpf httpd-2.2.13.tar.bz2 httpd-2.2.13/INSTALL
([3] 第1引数にサブコマンドを要求するものの補完)
linux# aptitude Tab
autoclean       -- erase old downloaded package files
changelog       -- view a package's changelog
clean           -- erase downloaded package files
download        -- download the .deb file for a package
forbid-version  -- forbid aptitude from upgrading to a specific package version
forget-new      -- forget what packages are "new"
  :
  :
(以下省略)
linux# aptitude INTab
linux# aptitude install virTab
("vir"で始まるパッケージのうちインストールしていないものが候補となる)
virsh                        virtualbox
virt-goodies                 virtualbox-2.0
virt-manager                 virtualbox-2.2
virt-top                     virtualbox-ose
virt-viewer                  virtualbox-ose-dbg
virtaal                      virtualbox-ose-guest-source
virtinst                     virtualbox-ose-guest-utils
virtual-mobile-builder       virtualbox-ose-source
virtual-mysql-client         virtualbox-source
virtual-mysql-server         viruskiller

linux# aptitude remTab
linux# aptitude remove
linux# aptitude virTab
linux# aptitude remove virtualbox-3.0
(aptitude remove の場合は、
 "vir"で始まるパッケージのうちインストールしてあるものが候補となる.
 apt-get、yum や、BSD系の pkg_* なども知的補完が組み込まれている)

% svn Tab
Completing svn command
add         commit      import      mergeinfo   proplist    switch    
blame       copy        info        mkdir       propset     unlock    
cat         delete      list        move        resolve     update    
changelist  diff        lock        propdel     resolved              
checkout    export      log         propedit    revert                
cleanup     help        merge       propget     status                
(Subversionのサブコマンド一覧)

% hgTab
add         export      locate      qfinish     qrestore    showconfig
addremove   forget      log         qfold       qsave       status    
annotate    glog        manifest    qgoto       qselect     strip     
archive     grep        merge       qguard      qseries     tag       
backout     heads       outgoing    qheader     qtop        tags      
bisect      help        parents     qimport     qunapplied  tip       
branch      identify    paths       qinit       recover     transplant
branches    import      pull        qnew        remove      unbundle  
bundle      incoming    push        qnext       rename      update    
cat         init        qapplied    qpop        resolve     verify    
clone       kwdemo      qclone      qprev       revert      version   
commit      kwexpand    qcommit     qpush       rollback              
copy        kwfiles     qdelete     qrefresh    root                  
diff        kwshrink    qdiff       qrename     serve                 

(Mercurialの場合は ~/.hgrc でロードしている拡張モジュールによって
 サブコマンドが増えるがそれらを自動検出して補完候補としている)

zshzsh$PREFIXshare/zsh//functions/compinitzsh
% echo ${(F)${(uo@)_comps}}|less
($_comps の値を見やすく加工して出力)

zsh


Tabexpand-or-complete

辿

TabTabTabmenu-expand-or-complete

Tabreverse-menu-completeESC TabESC C-i
bindkey '^i' menu-expand-or-complete
bindkey '^[^i' reverse-menu-complete
bindkey '^[i' expand-or-complete

辿便expand-or-completemenu-expand-or-complete使


zsh便便使



2/

% zstyle ':completion:*' format '%BCompleting %d%b'
% zstyle ':completion:*' group-name ''

.zshrc
% zstyle -L



gizgiz
% giz
Usage: giz [ -fnqv ] [ -g grp ] [ -d {foo|bar|baz} ] file
Possible options are as follows:
 -f  Force overwrite
 -n  No exec, echo only
 -q  quiet
 -v  verbose
 -g grp  set group to grp
 -d kwd  set default keyword to kwd, which is one of:
     foo, bar, baz

Usage


1

1

-f, -n, -q, -v 

1 -g, -d 


-q  -v 



% giz  


% giz - 

(Tab)

_arguments


zsh_arguments

_arguments_arguments giz

giz
function _giz () {
  _arguments -s : \
    '-f[Force overwrite]' \
    '-n[No exec]' \
    '(-v)-q[Quiet]' \
    '(-q)-v[Verbose]' \
    '-g[Group]:group:_groups' \
    '-d[Keyword]:keyword:(foo bar baz)' \
    '1:file:_files'
}

_giz compdef
% compdef _giz giz

giz
% giz 
(通常引数位置での補完候補)
% giz ESC C-d
Completing file
tetris.html      z-1.html         z-3.html         z-5.html
tetris.png       z-2.html         z-4.html         z-anecdote.html

(ハイフンの直後での補完候補)
% giz -ESC C-d
Completing option
-d  -- Keyword
-f  -- Force overwrite
-g  -- Group
-n  -- No exec
-q  -- Quiet
-v  -- Verbose

(-fオプション入力後の補完候補からは-fが消える)
% giz -fESC C-d
Completing option
-d  -- Keyword
-g  -- Group
-n  -- No exec
-v  -- Verbose
-q  -- Quiet

(-gオプションを入れた後の補完候補)
% giz -f -gESC C-d
Completing group
_httpd    _sdpd     daemon    guest     named     operator  staff     utmp
_pflogd   _timedc   dbus      kmem      nobody    polkit    sys       wheel
_proxy    authpf    dialer    mail      nogroup   postfix   tty       wsrc
_rwhod    bin       games     maildrop  ntpd      sshd      users
(システムに存在するグループ一覧が出力される)


_arguments


giz_arguments
  _arguments -s : \
    '-f[Force overwrite]' \
    '-n[No exec]' \
    '(-v)-q[Quiet]' \
    '(-q)-v[Verbose]' \

    '-d[Keyword]:keyword:(foo bar baz)' \
    '-g[Group]:group:_groups' \
    '1:file:_files'


1


-s1giz-f-n-fn-f

: _arguments

23


-f[Force overwrite] giz-f `Force overwrite' 3 -n[No Exec] 

45


(-v)-q[Quiet]  -q[Quiet] 23-q `Quiet' (-v)-v

(-v)-q


-q-v



6


-d[Keyword]:keyword:(foo bar baz) 3 -d[Keyword] -d223 (foo bar baz) 
% giz -d ESC C-d
Completing keyword
bar  baz  foo

7


'-g[Group]:group:_groups'6_groups3_groups

8


'1:file:_files' 1
% rsync -a --delete -e 'ssh -4' remote:foo bar

'ssh -4'1remote:foo2bar

_giz'1:file:_files'1`file' _files







(一)zsh

(二) fpath 

(三) 


~/script/zsh 
% mkdir -p ~/script/zsh

~/.zshrccompinit
typeset -U fpath
fpath=($fpath ~/script/zsh)

fpathzshautoload -U compinit && compinitautoloadzsh_giz _giz~/script/zsh
_giz
#compdef giz

function _giz () {
  _arguments -s : \
    '-f[Force overwrite]' \
    '-n[No exec]' \
    '(-v)-q[Quiet]' \
    '(-q)-v[Verbose]' \
    '-g[Group]:group:_groups' \
    '-d[Keyword]:keyword:(foo bar baz)' \
    '1:file:_files'
}

zsh_gizgiz1 `#compdef giz' giz使

zsh
% exec zsh

 "giz -" 
% giz -ESC C-d
Completing option
-d                -- Keyword
-f                -- Force overwrite
-g                -- Group
-n                -- No exec
-q                -- Quiet
-v                -- Verbose


fpath~/script/zshzsh
% unfunction _giz; autoload +X _giz

unfunctionautoload +X 


_giz7:
-g[Group]:group:_groups

3 _groups zsh
関数補完される語の種別
_aliasesエイリアス
_builtin内部コマンド
_groupsグループ
_filesファイル
_functions関数名
_gnu_generic--helpオプションを受け付けるもの
_hostsホスト名
_parameters変数名
_precommandtime や eval のように引数にコマンドラインを伴うもの
_usersユーザ名
_user_at_hostUSER@HOSTの形式

 zshcompsys(1) 


zsh調

便sh使zsh
 

おすすめ記事

記事・ニュース一覧