26763: fix problem on failed cd -s to relative path
[zsh.git] / Completion / compinit
blob1e4b7acef2a51a4b417a5497effd645a07d6e9a8
1 # Initialisation for new style completion. This mainly contains some helper
2 # functions and setup. Everything else is split into different files that
3 # will automatically be made autoloaded (see the end of this file).  The
4 # names of the files that will be considered for autoloading are those that
5 # begin with an underscores (like `_condition).
7 # The first line of each of these files is read and must indicate what
8 # should be done with its contents:
10 #   `#compdef <names ...>'
11 #     If the first line looks like this, the file is autoloaded as a
12 #     function and that function will be called to generate the matches
13 #     when completing for one of the commands whose <names> are given.
14 #     The names may also be interspersed with `-T <assoc>' options
15 #     specifying for which set of functions this should be added.
17 #   `#compdef -[pP] <patterns ...>'
18 #     This defines a function that should be called to generate matches
19 #     for commands whose name matches <pattern>. Note that only one pattern
20 #     may be given.
22 #   `#compdef -k <style> [ <key-sequence> ... ]'
23 #     This is used to bind special completions to all the given
24 #     <key-sequence>(s). The <style> is the name of one of the built-in
25 #     completion widgets (complete-word, delete-char-or-list,
26 #     expand-or-complete, expand-or-complete-prefix, list-choices,
27 #     menu-complete, menu-expand-or-complete, or reverse-menu-complete).
28 #     This creates a widget behaving like <style> so that the
29 #     completions are chosen as given in the the rest of the file,
30 #     rather than by the context.  The widget has the same name as
31 #     the autoload file and can be bound using bindkey in the normal way.
33 #   `#compdef -K <widget-name> <style> <key-sequence> [ ... ]'
34 #     This is similar to -k, except it takes any number of sets of
35 #     three arguments.  In each set, the widget <widget-name> will
36 #     be defined, which will behave as <style>, as with -k, and will
37 #     be bound to <key-sequence>, exactly one of which must be defined.
38 #     <widget-name> must be different for each:  this must begin with an
39 #     underscore, else one will be added, and should not clash with other
40 #     completion widgets (names based on the name of the function are the
41 #     clearest), but is otherwise arbitrary.  It can be tested in the
42 #     function by the parameter $WIDGET.
44 #   `#autoload [ <options> ]'
45 #     This is for helper functions that are not used to
46 #     generate matches, but should automatically be loaded
47 #     when they are called. The <options> will be given to the
48 #     autoload builtin when making the function autoloaded. Note
49 #     that this need not include `-U' and `-z'.
51 # Note that no white space is allowed between the `#' and the rest of
52 # the string.
54 # Functions that are used to generate matches should return zero if they
55 # were able to add matches and non-zero otherwise.
57 # See the file `compdump' for how to speed up initialisation.
59 # If we got the `-d'-flag, we will automatically dump the new state (at
60 # the end).  This takes the dumpfile as an argument.  -d (with the
61 # default dumpfile) is now the default; to turn off dumping use -D.
63 # The -C flag bypasses both the check for rebuilding the dump file and the
64 # usual call to compaudit; the -i flag causes insecure directories found by
65 # compaudit to be ignored, and the -u flag causes all directories found by
66 # compaudit to be used (without security checking).  Otherwise the user is
67 # queried for whether to use or ignore the insecure directories (which
68 # means compinit should not be called from non-interactive shells).
70 emulate -L zsh
71 setopt extendedglob
73 typeset _i_dumpfile _i_files _i_line _i_done _i_dir _i_autodump=1
74 typeset _i_tag _i_file _i_addfiles _i_fail=ask _i_check=yes _i_name
76 while [[ $# -gt 0 && $1 = -[dDiuC] ]]; do
77   case "$1" in
78   -d)
79     _i_autodump=1
80     shift
81     if [[ $# -gt 0 && "$1" != -[dfQC] ]]; then
82       _i_dumpfile="$1"
83       shift
84     fi
85     ;;
86   -D)
87     _i_autodump=0
88     shift
89     ;;
90   -i)
91     _i_fail=ign
92     shift
93     ;;
94   -u)
95     _i_fail=use
96     shift
97     ;;
98   -C)
99     _i_check=
100     shift
101     ;;
102   esac
103 done
105 # The associative arrays containing the definitions for the commands and
106 # services.
108 typeset -gA _comps _services _patcomps _postpatcomps
110 # `_compautos' contains the names and options for autoloaded functions
111 # that get options.
113 typeset -gA _compautos
115 # The associative array use to report information about the last
116 # completion to the outside.
118 typeset -gA _lastcomp
120 # Remember dumpfile.
121 if [[ -n $_i_dumpfile ]]; then
122   # Explicitly supplied dumpfile.
123   typeset -g _comp_dumpfile="$_i_dumpfile"
124 else
125   typeset -g _comp_dumpfile="${ZDOTDIR:-$HOME}/.zcompdump"
128 # The standard options set in completion functions.
130 typeset -ga _comp_options
131 _comp_options=(
132        bareglobqual
133        extendedglob
134        glob
135        multibyte
136        nullglob
137        rcexpandparam
138        unset
139     NO_allexport
140     NO_aliases
141     NO_cshnullglob
142     NO_cshjunkiequotes
143     NO_errexit
144     NO_globsubst
145     NO_histsubstpattern
146     NO_ignorebraces
147     NO_kshglob
148     NO_ksharrays
149     NO_kshtypeset
150     NO_markdirs
151     NO_octalzeroes
152     NO_shwordsplit
153     NO_shglob
154     NO_warncreateglobal
157 # And this one should be `eval'ed at the beginning of every entry point
158 # to the completion system.  It sets up what we currently consider a
159 # sane environment.  That means we set the options above, make sure we
160 # have a valid stdin descriptor (zle closes it before calling widgets)
161 # and don't get confused by user's ZERR trap handlers.
163 typeset -g _comp_setup='setopt localoptions localtraps ${_comp_options[@]};
164              local IFS=$'\'\ \\t\\r\\n\\0\''
165              exec </dev/null;
166              trap - ZERR
167              local -a reply
168              local REPLY'
170 # These can hold names of functions that are to be called before/after all
171 # matches have been generated.
173 typeset -ga compprefuncs comppostfuncs
174 compprefuncs=()
175 comppostfuncs=()
177 # Loading it now ensures that the `funcstack' parameter is always correct.
179 : $funcstack
181 # This function is used to register or delete completion functions. For
182 # registering completion functions, it is invoked with the name of the
183 # function as it's first argument (after the options). The other
184 # arguments depend on what type of completion function is defined. If
185 # none of the `-p' and `-k' options is given a function for a command is
186 # defined. The arguments after the function name are then interpreted as
187 # the names of the command for which the function generates matches.
188 # With the `-p' option a function for a name pattern is defined. This 
189 # function will be invoked when completing for a command whose name 
190 # matches the pattern given as argument after the function name (in this
191 # case only one argument is accepted).
192 # The option `-P' is like `-p', but the function will be called after
193 # trying to find a function defined for the command on the line if no
194 # such function could be found.
195 # With the `-k' option a function for a special completion keys is 
196 # defined and immediately bound to those keys. Here, the extra arguments
197 # are the name of one of the builtin completion widgets and any number
198 # of key specifications as accepted by the `bindkey' builtin.
199 # In any case the `-a' option may be given which makes the function
200 # whose name is given as the first argument be autoloaded. When defining
201 # a function for command names the `-n' option may be given and keeps
202 # the definitions from overriding any previous definitions for the
203 # commands; with `-k', the `-n' option prevents compdef from rebinding
204 # a key sequence which is already bound.
205 # For deleting definitions, the `-d' option must be given. Without the
206 # `-p' option, this deletes definitions for functions for the commands
207 # whose names are given as arguments. If combined with the `-p' option
208 # it deletes the definitions for the patterns given as argument.
209 # The `-d' option may not be combined with the `-k' option, i.e.
210 # definitions for key function can not be removed.
212 # Examples:
214 #  compdef -a foo bar baz
215 #    make the completion for the commands `bar' and `baz' use the
216 #    function `foo' and make this function be autoloaded
218 #  compdef -p foo 'c*'
219 #    make completion for all command whose name begins with a `c'
220 #    generate matches by calling the function `foo' before generating
221 #    matches defined for the command itself
223 #  compdef -k foo list-choices '^X^M' '\C-xm'
224 #    make the function `foo' be invoked when typing `Control-X Control-M'
225 #    or `Control-X m'; the function should generate matches and will
226 #    behave like the `list-choices' builtin widget
228 #  compdef -d bar baz
229 #   delete the definitions for the command names `bar' and `baz'
231 compdef() {
232   local opt autol type func delete new i ret=0 cmd svc
234   # Get the options.
236   if (( ! $# )); then
237     print -u2 "$0: I need arguments"
238     return 1
239   fi
241   while getopts "anpPkKd" opt; do
242     case "$opt" in
243     a)    autol=yes;;
244     n)    new=yes;;
245     [pPkK]) if [[ -n "$type" ]]; then
246             # Error if both `-p' and `-k' are given (or one of them
247             # twice).
248             print -u2 "$0: type already set to $type"
249             return 1
250           fi
251           if [[ "$opt" = p ]]; then
252             type=pattern
253           elif [[ "$opt" = P ]]; then
254             type=postpattern
255           elif [[ "$opt" = K ]]; then
256             type=widgetkey
257           else
258             type=key
259           fi
260           ;;
261     d) delete=yes;;
262     esac
263   done
264   shift OPTIND-1
266   if (( ! $# )); then
267     print -u2 "$0: I need arguments"
268     return 1
269   fi
271   if [[ -z "$delete" ]]; then
272     # If the first word contains an equal sign, all words must contain one
273     # and we define which services to use for the commands.
275     if [[ "$1" = *\=* ]]; then
276       while (( $# )); do
277         if [[ "$1" = *\=* ]]; then
278           cmd="${1%%\=*}"
279           svc="${1#*\=}"
280           func="$_comps[${_services[(r)$svc]:-$svc}]"
281           [[ -n ${_services[$svc]} ]] &&
282               svc=${_services[$svc]}
283           [[ -z "$func" ]] &&
284               func="${${_patcomps[(K)$svc][1]}:-${_postpatcomps[(K)$svc][1]}}"
285           if [[ -n "$func" ]]; then
286             _comps[$cmd]="$func"
287             _services[$cmd]="$svc"
288           else
289             print -u2 "$0: unknown command or service: $svc"
290             ret=1
291           fi
292         else
293           print -u2 "$0: invalid argument: $1"
294           ret=1
295         fi
296         shift
297       done
299       return ret
300     fi
302     # Adding definitions, first get the name of the function name
303     # and probably do autoloading.
305     func="$1"
306     [[ -n "$autol" ]] && autoload -Uz "$func"
307     shift
309     case "$type" in
310     widgetkey)
311       while [[ -n $1 ]]; do
312         if [[ $# -lt 3 ]]; then
313           print -u2 "$0: compdef -K requires <widget> <comp-widget> <key>"
314           return 1
315         fi
316         [[ $1 = _* ]] || 1="_$1"
317         [[ $2 = .* ]] || 2=".$2"
318         [[ $2 = .menu-select ]] && zmodload -i zsh/complist
319         zle -C "$1" "$2" "$func"
320         if [[ -n $new ]]; then
321           bindkey "$3" | read -A opt
322           [[ $opt[-1] = undefined-key ]] && bindkey "$3" "$1"
323         else
324           bindkey "$3" "$1"
325         fi
326         shift 3
327       done
328       ;;
329     key)
330       if [[ $# -lt 2 ]]; then
331         print -u2 "$0: missing keys"
332         return 1
333       fi
335       # Define the widget.
336       if [[ $1 = .* ]]; then
337         [[ $1 = .menu-select ]] && zmodload -i zsh/complist
338         zle -C "$func" "$1" "$func"
339       else
340         [[ $1 = menu-select ]] && zmodload -i zsh/complist
341         zle -C "$func" ".$1" "$func"
342       fi
343       shift
345       # And bind the keys...
346       for i; do
347         if [[ -n $new ]]; then
348            bindkey "$i" | read -A opt
349            [[ $opt[-1] = undefined-key ]] || continue
350         fi
351         bindkey "$i" "$func"
352       done
353       ;;
354     *)
355       # For commands store the function name in the
356       # associative array, command names as keys.
357       while (( $# )); do
358         if [[ "$1" = -N ]]; then
359           type=normal
360         elif [[ "$1" = -p ]]; then
361           type=pattern
362         elif [[ "$1" = -P ]]; then
363           type=postpattern
364         else
365           case "$type" in
366           pattern)
367             _patcomps[$1]="$func"
368             ;;
369           postpattern)
370             _postpatcomps[$1]="$func"
371             ;;
372           *)
373             if [[ "$1" = *\=* ]]; then
374               cmd="${1%%\=*}"
375               svc=yes
376             else
377               cmd="$1"
378               svc=
379             fi
380             if [[ -z "$new" || -z "${_comps[$1]}" ]]; then
381               _comps[$cmd]="$func"
382               [[ -n "$svc" ]] && _services[$cmd]="${1#*\=}"
383             fi
384             ;;
385           esac
386         fi
387         shift
388       done
389       ;;
390     esac
391   else
392     # Handle the `-d' option, deleting.
394     case "$type" in
395     pattern)
396       unset "_patcomps[$^@]"
397       ;;
398     postpattern)
399       unset "_postpatcomps[$^@]"
400       ;;
401     key)
402       # Oops, cannot do that yet.
404       print -u2 "$0: cannot restore key bindings"
405       return 1
406       ;;
407     *)
408       unset "_comps[$^@]"
409     esac
410   fi
413 # Now we automatically make the definition files autoloaded.
415 typeset _i_wdirs _i_wfiles
417 _i_wdirs=()
418 _i_wfiles=()
420 autoload -Uz compaudit
421 if [[ -n "$_i_check" ]]; then
422   typeset _i_q
423   if ! eval compaudit; then
424     if [[ -n "$_i_q" ]]; then
425       if [[ "$_i_fail" = ask ]]; then
426         if ! read -q \
427 "?zsh compinit: insecure $_i_q, run compaudit for list.
428 Ignore insecure $_i_q and continue [y] or abort compinit [n]? "; then
429           print -u2 "$0: initialization aborted"
430           unfunction compinit compdef
431           unset _comp_dumpfile _comp_secure compprefuncs comppostfuncs \
432                 _comps _patcomps _postpatcomps _compautos _lastcomp
434           return 1
435         fi
436         _i_wfiles=()
437         _i_wdirs=()
438       else
439         (( $#_i_wfiles )) && _i_files=( "${(@)_i_files:#(${(j:|:)_i_wfiles%.zwc})}"  )
440         (( $#_i_wdirs ))  && _i_files=( "${(@)_i_files:#(${(j:|:)_i_wdirs%.zwc})/*}" )
441       fi
442     fi
443     _comp_secure=yes
444   fi
447 # Make sure compdump is available, even if we aren't going to use it.
448 autoload -Uz compdump compinstall
450 # If we have a dump file, load it.
452 _i_done=''
454 if [[ -f "$_comp_dumpfile" ]]; then
455   if [[ -n "$_i_check" ]]; then
456     read -rA _i_line < "$_comp_dumpfile"
457     if [[ _i_autodump -eq 1 && $_i_line[2] -eq $#_i_files &&
458         $ZSH_VERSION = $_i_line[4] ]]
459     then
460       builtin . "$_comp_dumpfile"
461       _i_done=yes
462     fi
463   else
464     builtin . "$_comp_dumpfile"
465     _i_done=yes
466   fi
468 if [[ -z "$_i_done" ]]; then
469   typeset -A _i_test
471   for _i_dir in $fpath; do
472     [[ $_i_dir = . ]] && continue
473     (( $_i_wdirs[(I)$_i_dir] )) && continue
474     for _i_file in $_i_dir/^([^_]*|*~|*.zwc)(N); do
475       _i_name="${_i_file:t}"
476       (( $+_i_test[$_i_name] + $_i_wfiles[(I)$_i_file] )) && continue
477       _i_test[$_i_name]=yes
478       read -rA _i_line < $_i_file
479       _i_tag=$_i_line[1]
480       shift _i_line
481       case $_i_tag in
482       (\#compdef)
483         if [[ $_i_line[1] = -[pPkK](n|) ]]; then
484           compdef ${_i_line[1]}na "${_i_name}" "${(@)_i_line[2,-1]}"
485         else
486           compdef -na "${_i_name}" "${_i_line[@]}"
487         fi
488         ;;
489       (\#autoload)
490         autoload -Uz "$_i_line[@]" ${_i_name}
491         [[ "$_i_line" != \ # ]] && _compautos[${_i_name}]="$_i_line"
492         ;;
493       esac
494     done
495   done
497   # If autodumping was requested, do it now.
499   if [[ $_i_autodump = 1 ]]; then
500     compdump
501   fi
504 # Rebind the standard widgets
505 for _i_line in complete-word delete-char-or-list expand-or-complete \
506   expand-or-complete-prefix list-choices menu-complete \
507   menu-expand-or-complete reverse-menu-complete; do
508   zle -C $_i_line .$_i_line _main_complete
509 done
510 zle -la menu-select && zle -C menu-select .menu-select _main_complete
512 # If the default completer set includes _expand, and tab is bound
513 # to expand-or-complete, rebind it to complete-word instead.
514 bindkey '^i' | read -A _i_line
515 if [[ ${_i_line[2]} = expand-or-complete ]] &&
516   zstyle -a ':completion:' completer _i_line &&
517   (( ${_i_line[(i)_expand]} <= ${#_i_line} )); then
518   bindkey '^i' complete-word
521 unfunction compinit compaudit
522 autoload -Uz compinit compaudit
524 return 0