26763: fix problem on failed cd -s to relative path
[zsh.git] / Completion / compinstall
blobc04543c57c35c32426765cf7937ed59d994136f5
1 # Configure the completion system.
3 emulate -L zsh
4 setopt extendedglob
6 local key
7 local compcontext=-default-
9 __ci_tidyup() {
10   unfunction -m __ci_\* 2>/dev/null
11   unfunction compinstall
12   autoload -Uz compinstall
15 __ci_newline() {
16   read -k \
17     key"?${1:---- Hit newline to continue or \`q' to exit without saving --- }"
18   print
19   if [[ $key = [qQ] ]]; then
20     print "compinstall aborted."
21     __ci_tidyup
22     return 1
23   else
24     return 0
25   fi
28 typeset startline='# The following lines were added by compinstall'
29 typeset endline='# End of lines added by compinstall'
30 typeset ifile line fpath_line compinit_args opt detect basic line2
31 typeset -A styles
32 typeset match mbegin mend warn_unknown warn_old warn_comment output
33 integer lines_found
35 while getopts "do" opt; do
36   case $opt in
37     (d)
38     # Detect an existing compinstall setup.
39     detect=1
40     ;;
42     (o)
43     # Output basic setup information only.
44     basic=1
45     ;;
46   esac
47 done
50 # Check the user's .zshrc, if any.
52 # This relies on the stuff we find being only minimally edited from
53 # the stuff we originally saved.  A better way of doing this would
54 # almost certainly be to use the style mechanism directly:  save the
55 # current styles in a variable, delete all styles, read in and evaluate
56 # any styles found, manipulate styles directly using zstyle, write out
57 # using zstyle -L, and if necessary restore the original styles.  One
58 # day I may even do that.
61 __ci_test_ifile() {
62   [[ -f $1 ]] && grep "$endline" $1 >/dev/null 2>&1
65 local foundold=false
66 if zstyle -s :compinstall filename ifile &&
67   __ci_test_ifile $ifile; then
68   foundold=true
69 else
70   ifile=${ZDOTDIR:-~}/.zshrc
71   if __ci_test_ifile ${ZDOTDIR:-~}/.compinstall; then
72     ifile=${ZDOTDIR:-~}/.compinstall
73     foundold=true
74   elif __ci_test_ifile $ifile; then
75     foundold=true
76   fi
80 if [[ -n $detect ]]; then
81   __ci_tidyup
82   [[ $foundold = true ]]
83   return
87 __ci_output() {
88   print -r "$startline"
89   [[ -n $output ]] && print -r "$output"
90   if [[ -n $ifile ]]; then
91     line="zstyle :compinstall filename ${(qq)ifile}"
92     print -r "$line"
93     eval "$line"
94   fi
96   [[ -n $fpath_line ]] && print -r "$fpath_line"
98   print -r "
99 autoload -Uz compinit
100 compinit${compinit_args:+ $compinit_args}"
102   print -r "$endline"
106 if [[ -n $basic ]]; then
107   __ci_output
108   __ci_tidyup
109   return
112 local newifile=$ifile
113 if [[ $foundold = true ]]; then
114   if [[ $newifile != [~/]* ]]; then
115     newifile=${ZDOTDIR:-~}/$newifile
116     print "[Existing completion definition file is not absolute path:
117 updating to $newifile]"
118   fi
119   print "I have found completion definitions in $newifile.
120 If you want me to read these, just hit return.  Otherwise, edit the file
121 name to look for definitions somewhere else, or delete the whole line
122 in order not to use existing definitions."
123   vared -ch -p 'file> ' newifile
124   if [[ -n $newifile && $newifile != [/~]* ]]; then
125     newifile=$PWD/$newifile
126     print "[Not absolute path: updating to $newifile]"
127   fi
128   [[ -z $newifile || ! -f $newifile ]] && foundold=false
129 else
130   print "I haven't found any existing completion definitions.
131 If you have some already defined by compinstall, edit the name of the
132 file where these can be found.  Note that this will only work if they
133 are exactly the form in which compinstall inserted them.  If you leave
134 the line as it is, or empty, I won't search."
135   while true;  do
136     vared -ch -p 'file> ' newifile || break
137     if [[ -n $newifile && $newifile != [/~]* ]]; then
138       newifile=$PWD/$newifile
139       print "[Not absolute path: updating to $newifile]"
140     fi
141     if [[ -n $newifile && $ifile != $newifile ]]; then
142       if __ci_test_ifile $newifile; then
143         foundold=true
144         break
145       fi
146       print "I couldn't find any definitions there.  Edit a new filename, or
147 leave the line blank to ignore it."
148     else
149       break
150     fi
151   done
153 ifile=${~newifile}
155 if [[ $foundold = true ]]; then
156   sed -n "/^[   ]*$startline/,/^[       ]*$endline/p" $ifile |
157   # We can't use the default read behaviour to handle continuation lines
158   # since it messes up internal backslashes.
159   while read -r line; do
160     # detect real continuation backslashes by checking there are an
161     # odd number together.  i think this is reliable since the only
162     # other way of quoting a backslash involves following it with
163     # a closing quote.
164     while [[ $line = *\\ ]]; do
165       line2=${(M)line%%\\##}
166       (( ${#line2} & 1 )) || break
167       read -r line2 || break
168       line="${line[1,-2]}$line2"
169     done
170     (( lines_found++ ))
171     if [[ $line = *'$fpath'* ]]; then
172       fpath_line=$line
173       if [[ $line != *\) ]]; then
174         while read -r line; do
175           fpath_line="$fpath_line
176 $line"
177           [[ $line = *\) ]] && break
178         done
179       fi
180     elif [[ $line = (#b)[[:blank:]]#zstyle[[:blank:]]##(\'[^\']#\')\
181 [[:blank:]]##([^[:blank:]]##)[[:blank:]]##(*) ]]; then
182       styles[$match[2]]="${styles[$match[2]]:+${styles[$match[2]]}
183 }${(Q)match[1]}
184 ${match[3]}"
185     elif [[ $line = [[:blank:]]#compconf* ]]; then
186       warn_old=1
187     elif [[ $line == $startline || $line == $endline ]]; then
188       # no-op
189     elif [[ $line = [[:blank:]]#\#* ]]; then
190       warn_comment=1
191     elif [[ $line = [[:blank:]]#compinit[[:blank:]]##(#b)([^[:blank:]]*) ]]
192     then
193       compinit_args=$match[1]
194     elif [[ $line != [[:blank:]]# &&
195       $line != [[:blank:]]#'autoload '*' compinit' &&
196       $line != [[:blank:]]#compinit &&
197       $line != [[:blank:]]#zstyle[[:blank:]]#:compinstall* ]]; then
198       warn_unknown="${warn_unknown:+$warn_unknown
199 }$line"
200     fi
201   done
205 # Print warnings about what we found in .zshrc.
208 if [[ -n $warn_old ]]; then
209   print "\
210 WARNING: your configuration appears to contain commands for the 3.1.6
211 configuration system.  You will have to reconfigure from scratch and the
212 existing configuration commands will be overwritten.  If you wish to preserve
213 the old commands, you should quit, copy them somewhere else, then rerun
214 compinstall.  Sorry."
215 elif [[ -n $warn_unknown ]]; then
216   print "\
217 WARNING: your configuration contains bits not understood by compinstall,
218 which will not be retained (shown below).  If you wish to retain these, you
219 should quit, copy them somewhere else, and then rerun compinstall.
221 $warn_unknown"
222 elif [[ -n $warn_comment ]]; then
223   print "All the comments in your configuration section will be lost.
224 If you want to keep them, you should copy them somewhere else first."
225 elif (( ! $lines_found )); then
226   print "Starting a new completion configuration from scratch."
227   if [[ -n $ifile && ! -d $ifile ]]; then
228     print -n "This will be "
229     if [[ ! -f $ifile ]]; then
230       print "written to the new file $ifile."
231     elif [[ ! -w $ifile ]]; then
232       print "written to the file ~/.compinstall for copying to $ifile."
233       ifile=$HOME/.compinstall
234     else
235       print "appended to the file $ifile.  It is up to you to ensure
236 that these lines are actually executed.  They will not be if your .zshrc
237 usually returns before the end."
238     fi
239   fi
241 print "Note that you will be given a chance to save the new setup
242 somewhere else at the end."
245 __ci_newline || return 1
248 typeset d compdir subdirs lines
251 # Make sure we have the completion functions in $fpath.
254 __ci_set_compdir() {
255   for d in $*; do
256     # If we find both the functions more than once, assume the later
257     # one is the standard set.
258     if [[ -f $d/compinit && -f $d/compdump ]]; then
259       compdir=$d
260     fi
261   done
264 __ci_set_compdir $fpath
266 if [[ -d $compdir/Base/Core ]]; then
267   subdirs=2
268 elif [[ -d $compdir/Base ]]; then
269   subdirs=1
270   ### compdir=${compdir:h}
273 if [[ -z $compdir ]]; then
274   # Start up a new zsh and get its default fpath.  If some swine has
275   # tinkered with this in /etc/zshenv we're out of luck.
276   lines=(${(f)"$(zsh -fc 'print -l $ZSH_VERSION $fpath')"})
277   line=$lines[1]
278   shift lines
279   # If the zsh in that path isn't right, maybe the user's shell is elsewhere.
280   if [[ $line != $ZSH_VERSION && -x $SHELL ]]; then
281     lines=(${(f)"$($SHELL -fc 'print -l $ZSH_VERSION $fpath' 2>/dev/null)"})
282     line=$lines[1]
283     shift lines
284   fi
285   if [[ $line != $ZSH_VERSION ]]; then
286     print "Hmmm, the zsh in your path is not what's running, nor is \$SHELL.
287 That's bad.
289   fi
290   __ci_set_compdir $lines
291   if [[ -n $compdir ]]; then
292     print "\
293 I've found the completion directories and will add them to your \$fpath,
294 but they should already be there at shell startup, so something (probably
295 an unconditional assignment in a startup file) is taking them out.  You
296 might want to check this, although what I'm doing should work."
297     if [[ -n $fpath_line ]]; then
298       print "\
300 What's more, there is already an \$fpath assignment in your completion
301 setup.  This gives me cause for concern.  I will override this, but don't
302 be surprised if it doesn't go according to plan.  If you have not
303 initialised completion in this shell, you should do so, then run
304 compinstall again."
305     fi
306   fi
307   if [[ $subdirs = 2 ]]; then
308     fpath_line=($compdir/[A-Z]*/[A-Z]*)
309     fpath_line="fpath=($fpath ${(F)fpath_line})"
310   elif [[ -n $subdirs ]]; then
311     fpath_line=($compdir/[A-Z]*)
312     fpath_line="fpath=($fpath ${(F)fpath_line})"
313   fi
314 else
315   if [[ $subdirs = 2 ]]; then
316     print "Completion directories $compdir/*/*
317 are already in your \$fpath, good."
318   elif [[ -n $subdirs ]]; then
319     print "Completion directories $compdir/*
320 are already in your \$fpath, good."
321   else
322     print "Completion directory $compdir
323 is already in your \$fpath, good."
324   fi
325   if [[ -n $fpath_line ]]; then
326     print "I shall keep the existing \$fpath=( ... ) assignment."
327   fi
330 if [[ -z $compdir ]]; then
331   print "\
332 The zsh in your path doesn't seem to have completion directories in the
333 function autoload path (\$fpath).  This suggests the shell wasn't installed
334 for completion.  If you want to use it, you will need to locate all the
335 completion functions yourself and install them in your \$fpath.  I will
336 continue, but don't expect this to have much effect until you do.
338 If you are planning to continue using the old compctl system for
339 completion, compinstall won't do you any good anyway."
342 __ci_newline || return 1
346 # Code for changing styles
349 typeset defcontext=":completion:*"
350 typeset curcontext=$defcontext
353 # Utility functions
357 # Get the style $1 for $curcontext into $2.
359 __ci_get_this_style() {
360   typeset -A tassoc
361   local style=$1 scalar=$2
363   tassoc=(${(f)styles[$style]})
364   eval "$scalar=\${tassoc[\$curcontext]}"
368 # Set the style $1 for $curcontext using scalar $2 for the value for this
369 # context.  If $2 is null, delete the context (this may not be correct for
370 # all styles).  Don't do any extra quotation.
371 # $2 gives the name of the scalar for symmetry with __ci_get_this_style.
373 __ci_set_this_style() {
374   local style=$1 scalar=$2 k
375   typeset -A tassoc
376   tassoc=(${(f)styles[$style]})
378   if [[ -n ${(P)scalar} ]]; then
379     tassoc[$curcontext]=${(P)scalar}
380   else
381     unset "tassoc[$curcontext]"
382   fi
384   styles[$style]=
385   for k in ${(ko)tassoc}; do
386     styles[$style]="${styles[$style]:+$styles[$style]
388 ${tassoc[$k]}"
389   done
393 # Functions displaying menus
396 __ci_change_context() {
397   clear
398   print "\
399              *** compinstall: change context ***
401 The context tells the completion system under what circumstances your
402 value will be used.  It has this form:
403   :completion:<function-name>:<completer>:<command>:<argument>:<tag>
404 See the documentation for more detail on each of these components.  The
405 default context \`$defcontext' matches everywhere in completion, unless you
406 define a more specific pattern which matches the completion context being
407 used. \`More specific' means either a string instead of a pattern, or a
408 longer pattern instead of a shorter pattern.
410 Edit a new context, or leave the line blank to reset the context to the
411 default value.  Note that you do not require quotes around the context,
412 which will automatically be added later.  Line editing and history are
413 available.
416   vared -eh -p 'context> ' curcontext
417   [[ -z $curcontext ]] && curcontext=$defcontext
421 __ci_toggle_completer() {
422   # used locally within __ci_do_completers
423   if [[ -n $completers[$1] ]]; then
424     completers[$1]=
425   else
426     completers[$1]=1
427   fi
430 __ci_do_minor_completer_options() {
431   # Set the options for the minor completers.
432   local key cond word olist omenu moriginal aspace tmparr
433   __ci_get_this_style condition cond
434   [[ -n $cond ]] && cond=${(Q)cond}
435   __ci_get_this_style word word
436   __ci_get_this_style old-list olist
437   __ci_get_this_style old-menu omenu
438   __ci_get_this_style match-original moriginal
439   __ci_get_this_style add-space aspace
441   while true; do
443     # insert-unambiguous can be handled somewhere else.
444     clear
445     print "\
446               *** compinstall: minor completer options ***
448 Current context: $curcontext
450 l.     Set options for _list: condition for delay and comparison.
451 o.     Set options for _oldlist: when to keep old list.
452 m.     Set options for _match: whether to assume a \`*' at the cursor.
453 p.     Set options for _prefix: whether to add a space before the suffix.
455 q.     Return to the previous menu without saving.
456 0.     Done setting completer options.
459     read -k key'?--- Hit selection --- '
460     print
462     [[ $key = 0 ]] && break
464     case $key in
465       [lL]) print "\
466 You can set a condition under which the _list completer will delay completion
467 until the second keypress.  It should evaluate to a number; a non-zero value
468 turns this behaviour on.  It can include parameters, in particular NUMERIC
469 to refer to a numeric argument.  For example, \`NUMERIC != 1' forces the
470 delay unless you give an argument 1 to the command.  Leave it blank to
471 assume the condition is true."
472             vared -eh -c -p 'condition> ' cond
473             print -n "
474 _list will usually compare the contents of the entire line with its previous
475 contents to decided if it has been changed since the last keypress.  You
476 can instead perform this comparison on just the current word, ignoring
477 the rest of the command line.  Do you want to do this? (y/n) [n] "
478             word=
479             read -q key && word=true
480             print
481             ;;
482       [oO]) print "\
483 _oldlist can keep a generated completion list for reshowing in the usual
484 way, e.g. with ^D, even if the list was generated by some special completion
485 command.  The default behaviour of _oldlist is to show this list if it was
486 not already visible, otherwise to generate the standard completion listing,
487 but you can force it always to be shown, or make it never shown.
488 Alternatively, you can specify a list of completers for which _oldlist will
489 be used.  Choose:
491 d.    Default behaviour.
492 a.    Always show old list.
493 n.    Never show old list.
494 s.    Specify a list of completers.
497             while true; do
498               read -k key'?--- Hit selection --- '
499               print
500               case $key in
501                 [dD]) olist=
502                    ;;
503                 [aA]) olist=always
504                       ;;
505                 [nN]) olist=never
506                       ;;
507                 [sS]) olist=
508                       tmparr=(_complete _approximate _correct _match _expand)
509                       while true; do
510                         clear
511                         print "\
512      *** compinstall:  choosing completers to have _oldlist behaviour ***
514 Type any of:
516 1.  _complete
517 2.  _approximate
518 3.  _correct
519 4.  _match
520 5.  _expand
522 or 0 to end, or - to delete the last choice."
523                         if [[ -n $olist ]]; then
524                           print "\
525 Current choices:
526   $olist"
527                         fi
528                         read -k key'?--- Hit selection --- '
529                         print
530                         case $key in
531                           0) break
532                              ;;
533                           -) olist=(${olist[1,-2]})
534                              ;;
535                           [1-5]) olist=($olist $tmparr[$key])
536                                  ;;
537                         esac
538                       done
539                       ;;
540                 *) print "Type one of d, a, n or s."
541                    continue
542                    ;;
543               esac
544               break
545             done
547             print -n "
548 _oldlist can keep the old completion list for use in menu completion, e.g. by
549 repeatedly hitting tab, even if the list was generated by some special
550 completion command.  This is the default behaviour of _oldlist, but
551 you can turn it off, so that hitting tab would use the standard completion
552 list.
554 Do you want to turn it off? (y/n) [n] "
555             omenu=
556             read -q key && omenu=false
557             ;;
558       [mM]) print "\
559 The _match completer will usually assume there is a \`*' at the cursor
560 position when trying pattern matches.  For example, \`f*n<TAB>e' would
561 be able to complete to \`filename', not just to patterns matching \`f*ne'.
562 (Note that this assumes you have the option COMPLETE_IN_WORD set, else all
563 completion takes place at the end of the word.)  You can tell _match not
564 to assume there is a \`*', or to try first without the \`*', then with it.
565 Type one of:
567 a.     Always assume \`*' at cursor position.
568 n.     Never assume \`*' at cursor position.
569 w.     Try without the \`*', then with it if that fails."
570             while true; do
571               read -k key'?--- Hit selection --- '
572               print
573               case $key in
574                 a) moriginal=
575                    ;;
576                 n) moriginal=only
577                    ;;
578                 w) moriginal=both
579                    ;;
580                 *) print "Type one of a, n or w."
581                    continue
582                    ;;
583               esac
584               break
585             done
586             ;;
587       [pP]) print -n "\
588 The _prefix completer completes only what is behind the cursor, ignoring
589 completely what is after, even if there is no space at the cursor position.
590 However, you can force it to add a space between the resulting completion
591 and the part ignored.  For example, \`f<TAB>bar' might expand to \`filebar'
592 without this, and to \`file bar' with it.  Do wish _prefix to add the
593 space? (y/n) [n] "
594             aspace=
595             read -q key && aspace=true
596             ;;
597       [qQ]) return 1
598             ;;
599     esac
601   done
603   [[ -n $cond && $cond != [[:alnum:]]## ]] && cond=${(qq)cond}
604   __ci_set_this_style condition cond
605   __ci_set_this_style word word
606   __ci_set_this_style old-list olist
607   __ci_set_this_style old-menu omenu
608   __ci_set_this_style match-original moriginal
609   __ci_set_this_style add-space aspace
611   return 0
614 __ci_do_minor_completers() {
615   # Set the minor completers not handled by __ci_do_completers.
616   # Called within __ci_do_completers, so inherits the environment.
617   # It's only divided off to keep the menus short.
619   local key
621   while true; do
623     clear
624     print "\
625               *** compinstall: minor completer menu ***
627 Current context: $curcontext
629 The following completers are available.  Those marked \`(*)' are already
630 set for the context shown above.  Note none of these are required for
631 normal completion behaviour.
633 1. ${${completers[_ignored]:+(*)}:-   } _ignored: $ckeys[_ignored]
634 2. ${${completers[_list]:+(*)}:-   } _list:    $ckeys[_list]
635 3. ${${completers[_oldlist]:+(*)}:-   } _oldlist: $ckeys[_oldlist]
636 4. ${${completers[_match]:+(*)}:-   } _match:   $ckeys[_match]
637 5. ${${completers[_prefix]:+(*)}:-   } _prefix:  $ckeys[_prefix]
639 o.     Set options for the completers above.
640 q.     Return without saving.
641 0.     Done setting minor completers.
643     read -k key'?--- Hit selection --- '
644     print
646     [[ $key = 0 ]] && break
648     case $key in
649       1) __ci_toggle_completer _ignored
650          if [[ -n $completers[_ignored] ]]; then
651            print "\
652 I am inserting the \`ignored' completer immediately after normal
653 completion.  You can move it later in the list by hand, if you prefer, so
654 that ignored completions are only used after, for example, approximations.
655 To do this, edit $ifile, look for the zstyle ... completers line, and
656 move \`_ignored' to where you want it.  This will be retained if you use
657 compinstall again provided you don't go into the completers menu.
659            # TODO: we could be more careful about keeping the user's
660            # order, particularly with multiple completers.
661            read -k key'?--- Hit any key to continue --- '
662            print
663          fi
664          ;;
665       2) __ci_toggle_completer _list
666          ;;
667       3) __ci_toggle_completer _oldlist
668          ;;
669       4) __ci_toggle_completer _match
670          ;;
671       5) __ci_toggle_completer _prefix
672          ;;
673       o) __ci_do_minor_completer_options
674          ;;
675       q) return 1
676          ;;
677     esac
679   done
681   return 0
684 __ci_do_completer_options() {
685   # Set options for the main completers; called from __ci_do_completers.
687   local maxe errors prompt glob subst compl cond
689   __ci_get_this_style max-errors errors
690   __ci_get_this_style prompt prompt
691   [[ -n $prompt ]] && prompt=${(Q)prompt}
692   __ci_get_this_style glob glob
693   [[ -n $glob ]] && glob=${(Q)glob}
694   __ci_get_this_style substitute subst
695   [[ -n $subst ]] && subst=${(Q)subst}
696   __ci_get_this_style completions compl
697   [[ -n $compl ]] && compl=${(Q)compl}
699   while true; do
701     clear
702     print "\
703               *** compinstall: completer options ***
705 Current context: $curcontext
707 The following options are available.  Note that these require the relevant
708 completers to be present, as set in the menu above this one.
710 a.     Set options for approximation or correction.
711 e.     Set options for expansion.
712 q.     Return without saving.
714 0.     Done setting options.
717     read -k key'?--- Hit selection --- '
718     print
720     # We handle approximation and correction together to avoid having
721     # to be too particular about context.
722     case $key in
723       a) clear
724          print "\
725 Approximation and correction can correct the errors in what you have typed,
726 up to a maximum number of errors which you can specify.  Each \`error'
727 is the omission of a character, the addition of a superfluous character,
728 the substitution of one character by an incorrect one, or transposition of
729 two different characters.
731 Current context: $curcontext
733 To have different values for approximation and correction, you should
734 change the context appropriately.  For approximation, use
735 \`:completion:*:approximate:*' and for correction use
736 \`:completion:*:correct:*'.
738 Enter maximum number of errors allowed:
740          maxe=
741          while true; do
742            vared -eh -c -p "number> " maxe
743            [[ $maxe = [[:digit:]]## ]] && break
744            print "Please enter a number"
745            maxe=
746          done
747          while true; do
748            print "\nSelect behaviour of numeric prefix.
750 1.     Numeric prefix is not used by approximation or completion.
751 2.     Numeric prefix, if provided, gives max number of errors allowed,
752        replacing the number you just typed for that one completion.
753 3.     Numeric prefix, if provided, prevents approximation or completion
754        from taking place at all for that one completion.
756            read -k -- key'?--- Hit selection --- '
757            print
758            [[ $key = [123] ]] || continue
759            case $key in
760              2) maxe="$maxe numeric"
761                 ;;
762              3) maxe="$maxe not-numeric"
763                 ;;
764            esac
765            print "
766 You can edit a prompt which will appear above lists of corrections.  The
767 string \`%e' inside the prompt will be replaced with the number of errors
768 found.  Leave blank for no prompt.  Quotation marks will be added
769 automatically."
770            vared -eh -c -p "prompt> " prompt
771            break
772          done
773          errors=$maxe
774          ;;
775       e) while true; do
776            clear
777            print "\
778 The _expand completer can be tuned to perform any of globbing (filename
779 generation), substitution (anything with a \`\$' or backquote), or
780 normal completion (which is useful for inserting all possible completions
781 into the command line).  For each feature, a 1 turns it on, while a 0 turns
782 it off; if the feature is unset, that expansion will *not* be performed.
784 You can also give more complicated mathematical expressions, which can use
785 the parameter NUMERIC to refer to the numeric argument.  For example, the
786 expression \`NUMERIC == 2' means that the expansion takes effect if you
787 type ESC-2 (Emacs mode) or 2 (Vi command mode) before the expansion.
788 Quotes will be added automatically as needed.
790 g.     Set condition to perform globbing: ${glob:-unset}
791 s.     Set condition to perform substitution: ${subst:-unset}
792 c.     Set condition to perform completion: ${compl:-unset}
793 0.     Done setting conditions (will not be saved until you leave options)
795            read -k key'?--- Enter selection --- '
796            print
798            case $key in
799              g) vared -eh -c -p 'globbing condition> ' glob
800                 ;;
801              s) vared -eh -c -p 'substitution condition> ' subst
802                 ;;
803              c) vared -eh -c -p 'completion condition> ' compl
804                 ;;
805            esac
807            [[ $key = 0 ]] && break
809          done
810          ;;
811       q) return 1
812          ;;
813     esac
815     [[ $key = 0 ]] && break
816   done
818   __ci_set_this_style max-errors errors
819   [[ -n $prompt ]] && prompt=${(qq)prompt}
820   __ci_set_this_style prompt prompt
821   [[ -n $glob && $glob != [[:alnum:]]## ]] && glob=${(qq)glob}
822   __ci_set_this_style glob glob
823   [[ -n $subst && $subst != [[:alnum:]]## ]] && subst=${(qq)subst}
824   __ci_set_this_style substitute subst
825   [[ -n $compl && $compl != [[:alnum:]]## ]] && compl=${(qq)compl}
826   __ci_set_this_style completions compl
828   key=
829   return 0
832 __ci_do_completers() {
833   # Set the completers for the current context.
834   # This is mostly done via a series of toggles.
836   typeset -A completers ckeys
837   local c clist newc
838   __ci_get_this_style completer newc
839   for c in ${=newc}; do
840     completers[$c]=1
841   done
842   if (( ${#completers} == 0 )); then
843     completers[_complete]=1
844     completers[_ignored]=1
845   fi
846   clist=(_list _oldlist _menu _expand _complete _ignored
847          _match _correct _approximate _prefix)
849   # TODO: these are a bit brief, so could provide some more detailed help.
850   ckeys=(_complete 'Basic completion.'
851          _approximate
852 'Approximate completion:  completion with correction of existing word.'
853          _correct
854 'Correction:  correct existing word, no completion.'
855          _expand
856 'Expansion: use globbing and parameter substitution, if possible.'
858          _ignored
859 'Use patterns that were previously ignored if no matches so far.'
860          _list
861 'Only list matches until the second time you hit TAB.'
862          _oldlist
863 'Keep matches generated by special completion functions.'
864         _match
865 'If completion fails, retry with pattern matching.'
866          _prefix
867 'If completion fails, retry ignoring the part after the cursor.'
868          )
870   # TODO: You'll need to handle the bindkey to make _expand work.
871   # TODO: _prefix completer should make sure completeinword is set.
873   while true; do
875     clear
876     print "\
877               *** compinstall: completer menu ***
879 Current context: $curcontext
881 The following completers are available.  Those marked \`(*)' are already
882 set for the context shown above.  If none are selected, the completers will
883 not be set for this context at all.
885 1. ${${completers[_complete]:+(*)}:-   } $ckeys[_complete]
886 2. ${${completers[_approximate]:+(*)}:-   } $ckeys[_approximate]
887 3. ${${completers[_correct]:+(*)}:-   } $ckeys[_correct]
888 4. ${${completers[_expand]:+(*)}:-   } $ckeys[_expand]
890 o.     Set options for the completers above.
891 m.     Set completers that modify the behaviour of the four main ones above.
892 q.     Return without saving.
893 0.     Done setting completers.
895     read -k key'?--- Hit selection --- '
896     print
898     case $key in
899       1) __ci_toggle_completer _complete
900          ;;
901       2) __ci_toggle_completer _approximate
902          ;;
903       3) __ci_toggle_completer _correct
904          ;;
905       4) __ci_toggle_completer _expand
906          ;;
907       [mM]) __ci_do_minor_completers || return
908             continue
909             ;;
910       [oO]) __ci_do_completer_options || return
911             continue
912             ;;
913       q) return 1
914          ;;
915     esac
917     [[ $key = 0 ]] && break
918   done
920   newc=
921   for c in $clist; do
922     [[ -n $completers[$c] ]] && newc="${newc:+$newc }$c"
923   done
924   [[ -z $newc ]] && newc="''"
925   __ci_set_this_style completer newc
928 __ci_toggle_matcher() {
929   # Toggle on/off the matcher in array $1 for element $2
930   if [[ ${${(P)1}[$2]} = ' ' ]]; then
931     # toggle on
932     eval "${1}[$2]=$2"
933     if [[ $1 = n* ]]; then
934       # no matcher turned on, turn off the others
935       c_list[$2]=' '
936       C_list[$2]=' '
937       p_list[$2]=' '
938       s_list[$2]=' '
939     else
940       # something else turned on, turn off no matcher
941       n_list[$2]=' '
942     fi
943     return 0
944   else
945     # toggle off
946     eval "${1}[$2]=' '"
947     if [[ $c_list[$2] == ' ' && $C_list[$2] == ' ' && \
948           $p_list[$2] == ' ' && $s_list[$2] == ' ' ]]; then
949       a_or_r[$2]=' '
950     fi
951     return 1
952   fi
955 __ci_do_matchers() {
956   # Set matchers via the matcher-list style.
957   # We just offer a pre-programmed set of possible matchers, but these
958   # cover the most common usages for matchers in a general context.
959   # More specific use of matchers is usually covered by completion functions.
961   local mlist m_ci m_pw m_sub c_list C_list p_list s_list pw_seps key key2 elt
962   local pw_dstar a_or_r i
963   integer eltcnt lastnz
965   __ci_get_this_style matcher-list mlist
966   # $mlist is the once and future list of matchers.  We don't quote it
967   # until the end; the eval effectively does de-quoting.
968   eval "mlist=($mlist)"
969   # ?_list say whether the four possible matchers are set for passes 1,
970   # 2, 3, 4, in an easy-to-read manner, i.e. the Nth part of the string
971   # is one of N (on) or space (off).
972   a_or_r="    "                 # replace by default
973   n_list="    "                 # null completion, i.e. standard
974   c_list="    "                 # case match one way
975   C_list="    "                 # case match both ways
976   p_list="    "                 # partial word completion
977   s_list="    "                 # substring completion
978   # $pw_seps gives the separators used for partial-word completion
979   # by element of the matcher list; these can be edited separately.
980   pw_seps=('._-' '._-' '._-' '._-')
981   pw_dstar=('' '' '' '')
983   # See what's in the matcher initially.  If these have been edited,
984   # we're in trouble, but that's pretty much true of everything.
985   for (( eltcnt = 1; eltcnt <= $#mlist; eltcnt++ )); do
986     [[ $mlist[eltcnt] == "+"* ]] && a_or_r[$eltcnt]='+'
987     [[ -z $mlist[$eltcnt] ]] && n_list[$eltcnt]=$eltcnt
988     # Accept the old form of lower/upper correspondence, but we'll
989     # output the new one instead.
990     [[ $mlist[$eltcnt] = *"m:{a-z}={A-Z}"* ]] && c_list[$eltcnt]=$eltcnt
991     [[ $mlist[$eltcnt] = *"m:{[:lower:]}={[:upper:]}"* ]] &&
992       c_list[$eltcnt]=$eltcnt
993     [[ $mlist[$eltcnt] = *"m:{a-zA-Z}={A-Za-z}"* ]] && C_list[$eltcnt]=$eltcnt
994     [[ $mlist[$eltcnt] = *"m:{[:lower:][:upper:]}={[:upper:][:lower:]}"* ]] &&
995       C_list[$eltcnt]=$eltcnt
996     # For partial word stuff, we use backreferences to find out what
997     # the set of separators was.
998     if [[ $mlist[$eltcnt] = (#b)*"r:|["([^\]]#)"]=*"#" r:|=*"* ]]; then
999       p_list[$eltcnt]=$eltcnt
1000       pw_seps[$eltcnt]=${match[1]}
1001       [[ $mlist[$eltcnt] = *"=**"* ]] && pw_dstar[$eltcnt]='*'
1002     fi
1003     # Just look for the left matcher for substring, since the right matcher
1004     # might have been handled as part of a partial-word spec.
1005     [[ $mlist[$eltcnt] = *"l:|=*"* ]] && s_list[$eltcnt]=$eltcnt
1006   done
1008   while true; do
1009     clear
1010     print "\
1011               *** compinstall: matcher menu ***
1013 \`Matchers' compare the completion code with the possible matches in some
1014 special way.  Numbers in parentheses show matchers to be tried and the order.
1015 The same number can be assigned to different matchers, meaning apply at the
1016 same time.  Omit a sequence number to try normal matching at that point.
1017 A \`+' in the first line indicates the element is added to preceding matchers
1018 instead of replacing them; toggle this with \`t'.  You don't need to set
1019 all four, or indeed any matchers --- then the style will not be set.
1021    ($a_or_r)\
1022    \`+' indicates add to previous matchers, else replace
1023 n. ($n_list)\
1024  No matchers; you may want to try this as the first choice.
1025 c. ($c_list)\
1026  Case-insensitive completion (lowercase matches uppercase)
1027 C. ($C_list)\
1028  Case-insensitive completion (lower/uppercase match each other)
1029 p. ($p_list)\
1030  Partial-word completion:  expand 'f.b' to 'foo.bar', etc., in one go.
1031           You can choose the separators (here \`.') used each time.
1032 s. ($s_list)\
1033  Substring completion:  complete on substrings, not just initial
1034           strings.  Warning: it is recommended this not be used for element 1.
1036 t.        Toggle replacing previous matchers (\` ' at top) or add (\`+')
1037 q.        Return without saving.
1038 0.        Done setting matchers.
1041     read -k key'?--- Hit selection --- '
1042     print
1044     if [[ $key = [nNcCpPsS] ]]; then
1045       while true; do
1046         read -k key2'?Set/unset for element number (1234)? '
1047         print
1048         [[ $key2 = [1234] ]] && break
1049         print "Only 1, 2, 3 and 4 are handled."
1050       done
1051     fi
1053     case $key in
1054       [nN]) __ci_toggle_matcher n_list $key2
1055          if [[ $n_list[$key2] != ' ' ]]; then
1056          fi
1057          ;;
1058       c) __ci_toggle_matcher c_list $key2
1059          ;;
1060       C) __ci_toggle_matcher C_list $key2
1061          ;;
1062       [pP]) if __ci_toggle_matcher p_list $key2; then
1063               print "\
1064 Edit the set of characters which terminate partial words.  Typically
1065 these are punctuation characters, such as \`.', \`_' and \`-'.
1066 The expression will automatically be quoted.
1068               vared -eh -p 'characters> ' -c 'pw_seps['$key2']'
1069               # Paranoia: we don't know if there's a ']' in that string,
1070               # which will wreck the spec unless it's at the start.  Other
1071               # quotes are OK, since they are picked up at the ${(qq)...}
1072               # step.
1073               if [[ $pw_seps[$key2] = *']'* ]]; then
1074                 pw_seps[$key2]="]${pw_seps[$key2]//\\\]}"
1075               fi
1076               print -n "
1077 You can allow the partial-word terminators to be matched in the pattern,
1078 too:  then  for example \`c.u' would expand to \`comp.source.unix', whereas
1079 usually you would need to type an extra intervening dot.  Do you wish the
1080 terminators to be matched in this way? (y/n) [n] "
1081               pw_dstar[$key2]=
1082               read -q key && pw_dstar[$key2]='*'
1083             fi
1084             ;;
1085       [tT])
1086             read -k key2'?Toggle augment/replace for elements number (1234)? '
1087             if [[ $key2 == [1234] ]]; then
1088               if [[ $a_or_r[$key2] == ' ' ]]; then
1089                 a_or_r[$key2]='+'
1090               else
1091                 a_or_r[$key2]=' '
1092               fi
1093             else
1094               print "Only 1, 2, 3 and 4 are handled."
1095             fi
1096             ;;
1097       [sS]) __ci_toggle_matcher s_list $key2
1098             ;;
1099       [qQ]) return 1
1100          ;;
1101     esac
1103     [[ $key = 0 ]] && break
1104   done
1106   # Keep track of the last element which was non-empty; all the rest
1107   # are junked.
1108   lastnz=0
1110   # Now we just reverse the first for-loop, looking for set matchers
1111   # and reconstructing the elements of the matcher array.
1112   for (( eltcnt = 1; eltcnt <= 4; eltcnt++ )); do
1113     elt=
1114     [[ $c_list[$eltcnt] != ' ' ]] &&
1115       elt="${elt:+$elt }m:{[:lower:]}={[:upper:]}"
1116     [[ $C_list[$eltcnt] != ' ' ]] &&
1117       elt="${elt:+$elt }m:{[:lower:][:upper:]}={[:upper:][:lower:]}"
1118     [[ $p_list[$eltcnt] != ' ' ]] &&
1119       elt="${elt:+$elt }r:|[${pw_seps[$eltcnt]}]=*${pw_dstar[$eltcnt]}\
1120  r:|=*${pw_dstar[$eltcnt]}"
1121     if [[ $s_list[$eltcnt] != ' ' ]]; then
1122       if [[ $elt = *"r:|=*"* ]]; then
1123         elt="${elt:+$elt }l:|=*"
1124       else
1125         elt="${elt:+$elt }l:|=* r:|=*"
1126       fi
1127     fi
1128     [[ $a_or_r[$eltcnt] != ' ' ]] && elt="+$elt"
1129     [[ -n $elt || $n_list[$eltcnt] != ' ' ]] && lastnz=$eltcnt
1130     mlist[$eltcnt]=$elt
1131   done
1133   if (( ! $lastnz )); then
1134     # No matchers set, so just make the style empty: __ci_set_this_style
1135     # will omit it completely.
1136     mlist=
1137   else
1138     # Quote the entire list: this correctly quotes element by element,
1139     # praise be to Sven.
1140     mlist=(${(qq)mlist[1,$lastnz]})
1141     # Make it a scalar just for safety's sake.
1142     mlist="$mlist"
1143   fi
1144   __ci_set_this_style matcher-list mlist
1146   return 0
1149 __ci_do_list_format() {
1150   local key format groupn verbose listp autod haslistp
1151   __ci_get_this_style format format
1152   [[ -n $format ]] && format=${(Q)format}
1153   __ci_get_this_style group-name groupn
1154   __ci_get_this_style verbose verbose
1155   __ci_get_this_style list-prompt listp
1156   [[ -n $listp ]] && haslistp=1
1157   listp=${(Q)listp}
1158   __ci_get_this_style auto-description autod
1159   [[ -n $autod ]] && autod=${(Q)autod}
1161   while true; do
1162     clear
1163     print "\
1164        *** compinstall: order and descriptions in completion lists ***
1165 Type the appropriate number for more information on how this would affect
1166 listings.
1168 1.  Print a message above completion lists describing what is being
1169     completed.
1171 2.  Make different types of completion appear in separate lists.
1173 3.  Make completion verbose, using option descriptions etc. (on by default).
1175 4.  Make single-valued options display the value's description as
1176     part of the option's description.
1178 q.  Return without saving.
1179 0.  Done setting options for formatting of completion lists.
1182     read -k key'?--- Hit selection --- '
1183     print
1185     [[ $key = 0 ]] && break
1187     case $key in
1188       1) print "\
1189 You can set a string which is displayed on a line above the list of matches
1190 for completions.  A \`%d' in this string will be replaced by a brief
1191 description of the type of completion.  For example, if you set the
1192 string to \`Completing %d', and type ^D to show a list of files, the line
1193 \`Completing files' will appear above that list.  Enter an empty line to
1194 turn this feature off.  If you enter something which doesn't include \`%d',
1195 then \`%d' will be appended.  Quotation will be added automatically.
1197          vared -eh -p 'description> ' -c format
1198          if [[ -n $format && $format != *%d* ]]; then
1199            [[ $format = *[[:blank:]] ]] || format="$format "
1200            format="$format%d"
1201          fi
1202          ;;
1203       2) print "\
1204 Normally, all possible completions are listed together in a single list, and
1205 if you have set a description with 1) above, the descriptions are listed
1206 together above that.  However, you can specify that different types of
1207 completion appear in separate lists; any description appears above its
1208 own list.  For example, external commands and shell functions would appear
1209 in separate lists when you are completing a command name.  Do you
1210 want to turn this on?
1212          while true; do
1213            read -k key'?[y]es, [n]o, [k]eep old setting? '
1214            print
1215            [[ $key = [yYnNkK] ]] && break
1216          done
1217          case $key in
1218            [yY]) groupn="''"
1219                  ;;
1220            [nN]) groupn=
1221                  ;;
1222          esac
1223          ;;
1224       3) print "By default, completion uses a \`verbose' setting.  This
1225 affects different completions in different ways.  For example,  many
1226 well-known commands have short, uninformative option names; in some cases,
1227 completion will indicate what the options do when offering to complete them.
1228 If you prefer shorter listings you can turn this off.  What setting to
1229 you want?
1231           while true; do
1232             read -k key'?[v]erbose, [n]ot verbose, [k]eep old setting? '
1233             print
1234             [[ $key = [vVnNkK] ]] && break
1235           done
1236           case $key in
1237             # might as well be explicit, particularly since it's
1238             # the only way to override an existing `false' value.
1239             [vV]) verbose=true
1240                   ;;
1241             [nN]) verbose=false
1242                   ;;
1243           esac
1244          ;;
1245       4) print "\
1246 Many commands have options which take a single argument.  In some cases,
1247 completion is not set up to describe the option even though it has a
1248 description for the argument.  You can enter a string containing \`%d',
1249 which will be replaced by the description for the option.  For
1250 example, if you enter the string \`specify: %d', and an option -ifile
1251 exists which has an argument whose description is \`input file', then the
1252 description \`specify: input file' will appear when the option itself
1253 is listed.  As this long explanation suggests, this is only occasionally
1254 useful.  Enter an empty line to turn this feature off.  If you enter
1255 something which doesn't include \`%d', then \`%d' will be appended.
1256 Quotation will be added automatically.
1258          vared -eh -p 'auto-description> ' -c autod
1259          if [[ -n $autod && $autod != *%d* ]]; then
1260            [[ $autod = *[[:blank:]] ]] || autod="$autod "
1261            autod="$autod%d"
1262          fi
1263          ;;
1264       q) return 1
1265          ;;
1266     esac
1267   done
1269   [[ -n $format ]] && format=${(qq)format}
1270   __ci_set_this_style format format
1271   __ci_set_this_style group-name groupn
1272   __ci_set_this_style verbose verbose
1273   [[ -n $autod ]] && autod=${(qq)autod}
1274   __ci_set_this_style auto-description autod
1277 __ci_do_insertion() {
1278   local key insertu original # sort
1280   __ci_get_this_style insert-unambiguous insertu
1281   __ci_get_this_style original original
1283   while true; do
1284     clear
1285     print "\
1286           *** compinstall: options for inserting completions ***
1288 1.   In completers that change what you have already typed, insert any
1289      unambiguous prefix rather than go straight to menu completion.
1291 2.   In completers which correct what you have typed, keep what you
1292      originally typed as one of the list of possible completions.
1294 q.   Return with saving.
1295 0.   Done setting options for insertion.
1297     read -k key'?-- Hit selection --- '
1298     print
1300     [[ $key = 0 ]] && break
1302     case $key in
1303       1) print "\
1304 The completers which do pattern matching and correction often alter the
1305 string which is already on the line, in the first case because it was a
1306 pattern and in the second case because what you typed was wrong.
1307 Since the possible completions can bear little or no resemblance to one
1308 another in those cases, so that typing extra characters to resolve the
1309 completion doesn't make much sense, menu completion is usually turned on
1310 straight away to allow you to pick the completion you want.  This style
1311 tells completion that if there is a common, unambiguous prefix in this
1312 case, you would prefer that to be inserted rather than going straight
1313 to menu completion.  Do you want this?
1315          while true; do
1316            read -k key'?[y]es, [n]o, [k]eep old setting? '
1317            print
1318            [[ $key = [yYnNkK] ]] && break
1319          done
1320          case $key in
1321            [yY]) insertu=true
1322                  ;;
1323            [nN]) insertu=false
1324                  ;;
1325          esac
1326          ;;
1327       2) print "\
1328 For completers which correct what you have typed, you sometimes want
1329 to keep the original string instead, so if the correction was ambiguous
1330 the original string is always listed as a possible completion.  However,
1331 if there was just one completion it is usually accepted.  You can
1332 force completion to offer the original string as a possibility even in
1333 this case.  Do you want this?
1335          while true; do
1336            read -k key'?[y]es, [n]o, [k]eep old setting? '
1337            print
1338            [[ $key = [yYnNkK] ]] && break
1339          done
1340          case $key in
1341            [yY]) original=true
1342                  ;;
1343            [nN]) original=false
1344                  ;;
1345          esac
1346          ;;
1347       [qQ]) return 1
1348               ;;
1349     esac
1351   done
1353   __ci_set_this_style insert-unambiguous insertu
1354   __ci_set_this_style original original
1355   # __ci_set_this_style sort sort
1357   return 0;
1361 __ci_do_selection() {
1362   local key listc menu select amenu elt listp selectp haslistp hasselectp
1363   integer num
1365   __ci_get_this_style list-colors listc
1366   __ci_get_this_style menu menu
1367   __ci_get_this_style list-prompt listp
1368   [[ -n $listp ]] && haslistp=1
1369   listp=${(Q)listp}
1370   __ci_get_this_style select-prompt selectp
1371   [[ -n $selectp ]] && hasselectp=1
1372   selectp=${(Q)selectp}
1374   while true; do
1375     clear
1376     print "\
1377      *** compinstall: options for colouring and selecting in lists ***
1379 1.   Use coloured lists for listing completions.
1381 2.   Use cursor keys to select completions from completion lists.
1383 3.   Allow scrolling of long selection lists and set the prompt.
1385 q.   Return without saving.
1386 0.   Done setting options for insertion.
1388     read -k key'?--- Hit selection --- '
1389     print
1391     [[ $key = 0 ]] && break
1393     case $key in
1394       1) print "\
1395 Zsh can produce coloured completion listings where different file types
1396 etc. appear in different colours.  If you want to tailor that to your
1397 own needs, you will have to edit ~/.zshrc.  Here you have the choice of:
1399 1.  Using the default colours.
1400 2.  Using the colours already set up for GNU ls via the \$LS_COLORS
1401     environment variable.  Note this must be set before the completion
1402     configuration code is executed.
1403 3.  Turn colouring off.
1404 0.  Leave the setting the way it is.  Choose this if you have a custom
1405     setting and you don't want to lose it.
1407          while true; do
1408            read -k key'?Enter 1, 2, 3, 0: '
1409            print
1410            [[ $key = [1230] ]] && break
1411          done
1412          case $key in
1413            1) listc="''"
1414               ;;
1415            2) listc='${(s.:.)LS_COLORS}'
1416               ;;
1417            3) listc=
1418               ;;
1419          esac
1420          ;;
1421       2) print "\
1422 If you use zsh's menu completion and the feature that all short completion
1423 lists appear below the line on which you are editing, you can enable
1424 \`menu selection', which lets you pick a completion with the cursor keys:
1425 the choice is highlighted, and hitting return accepts it.  Note that
1426 this only happens when you are already using menu completion.  This
1427 feature can be set so that it is only enabled when there are a certain
1428 number of completions.  Please enter:
1430 - 0 or 1, to turn this feature on unconditionally
1431 - a higher number to turn this feature on when there are that many
1432   completions
1433 - an \`l' for \`long' to turn it on for listings which don't fit on the
1434   screen.
1435 - an \`ll' for \`long list' to turn it on for completions which don't fit
1436   on the screen, even for commands which only do listing of completions.
1437   This may be combined with a number which will be used in ordinary selection.
1438 - a negative number to turn this feature off
1439 - an empty line to leave the setting the way it is.
1441          # Better to parse and display the current setting.
1442          while true; do
1443            vared -eh -p 'value> ' select
1444            [[ -z $select || $select = ((-|)<->|l|<->#ll<->#) ]] && break;
1445            print "Type a number, l, ll, ll<num>, or an empty line." >&2
1446          done
1447          amenu=(${=menu})
1448          elt=${amenu[(i)*select*]}
1449          [[ $elt -eq 0 || $elt -gt $#amenu ]] && elt=
1450          case $select in
1451            <->) if [[ -n $elt ]]; then
1452                   amenu[$elt]="select=$select"
1453                 else
1454                   amenu=($amenu "select=$select")
1455                 fi
1456                 menu="$amenu"
1457                 ;;
1458            *ll*) num=${(RS)select##ll}
1459                  select="select=long-list"
1460                  [[ -n $num ]] && select="$select select=$num"
1461                  if [[ -n $elt ]]; then
1462                    amenu[$elt]=$select
1463                  else
1464                    amenu=($amenu $select)
1465                  fi
1466                  menu="$amenu"
1467                  ;;
1468            l#) if [[ -n $elt ]]; then
1469                  amenu[$elt]="select=long"
1470                else
1471                  amenu=($amenu "select=long")
1472                fi
1473                menu="$amenu"
1474                ;;
1475            -<->) if [[ -n $elt ]]; then
1476                     # i never liked the way indexing was done anyway
1477                     if [[ $elt -eq 1 ]]; then
1478                       amenu=($amenu[$elt+1,-1])
1479                     else
1480                       amenu=($amenu[1,$elt-1] $amenu[$elt+1,-1])
1481                     fi
1482                  fi
1483                  menu="$amenu"
1484                  ;;
1485          esac
1486          if [[ $menu = *select* ]]; then
1487            print "\
1488 You can also set a prompt to use for menu selection when it would scroll
1489 off the screen.  Unless this is set, you won't see a prompt, but the feature
1490 is still enabled.
1492 Edit a prompt below.  It can contain \`%l' to show the number of matches
1493 as \`current_number/total_number', \`%p' to show the fraction of
1494 the way down the list, or font-control sequences such as %B, %U, %S and
1495 the corresponding %b, %u, %s; quotes will be added automatically.  Delete
1496 the whole line to turn it off.  Hit return to keep the current value.
1498            [[ -z $hasselectp ]] &&
1499              selectp='%SScrolling active: current selection at %p%s'
1500            vared -eh -p 'prompt> ' -c selectp
1501            [[ -z $selectp ]] && hasselectp=
1502          fi
1503          ;;
1504       3) print "\
1505 You can make completion lists scroll when they don't fit on the screen.
1506 Note this is different from scrolling in menu selection --- a more basic
1507 pager is used which should work even with fairly stupid terminals.
1509 To enable this, edit a prompt to show when scrolling is active; an empty 
1510 string turns this feature off.  It can contain \`%l' to show the number of
1511 matches as \`current_number/total_number', \`%p' to show the fraction of
1512 the way down the list, or font-control sequences such as %B, %U, %S and the
1513 corresponding %b, %u, %s; quotes will be added automatically.  Delete the
1514 whole line to turn this behaviour off, in which case the display of
1515 completions which don't fit on the screen is controlled by the LISTMAX
1516 parameter (currently ${LISTMAX:-unset}), which specifies the maximum number
1517 to show without asking.  Hit return to keep the current value.
1519          [[ -z $haslistp ]] &&
1520            listp='%SAt %p: Hit TAB for more, or the character to insert%s'
1521          vared -eh -p 'prompt> ' -c listp
1522          [[ -z $listp ]] && haslistp=
1523          ;;
1524       q) return 1
1525          ;;
1526     esac
1527   done
1529   __ci_set_this_style list-colors listc
1530   __ci_set_this_style menu menu
1531   [[ -n $haslistp ]] && listp=${(qq)listp}
1532   __ci_set_this_style list-prompt listp
1533   [[ -n $hasselectp ]] && selectp=${(qq)selectp}
1534   __ci_set_this_style select-prompt selectp
1536   return 0
1540 __ci_do_display() {
1541   local key usec
1543   __ci_get_this_style use-compctl usec
1545   while true; do
1546     clear
1547     print "\
1548          *** compinstall: display and insertion options ***
1550 1.  Change appearance of completion lists:  allows descriptions of
1551     completions to appear and sorting of different types of completions.
1553 2.  Change how completions are inserted: includes options for sorting,
1554     and keeping the original or an unambiguous prefix with correction etc.
1556 3.  Configure coloured/highlighted completion lists, selection of items
1557     and scrolling.
1559 4.  Change whether old-style \`compctl' completions will be used.
1561 q.  Return without saving.
1562 0.  Done setting display and insertion options.
1565     read -k key'?--- Hit selection --- '
1566     print
1568     [[ $key = 0 ]] && break
1570     case $key in
1571       1) __ci_do_list_format
1572          ;;
1573       2) __ci_do_insertion
1574          ;;
1575       3)  __ci_do_selection
1576          ;;
1577       4) print "\
1578 Completions defined by the new completion system (the one you are
1579 configuring) always take precedence over the old sort defined with compctl.
1580 You can choose whether or not you want to search for a compctl-defined
1581 completion if no new completion was found for a command.  The default
1582 behaviour is only to check for compctl-defined completions if the required
1583 library, zsh/compctl, is already loaded.  (If not, this implies that
1584 compctl has not been called.)  Do you want to test for compctl-defined
1585 completions?
1587          while true; do
1588            read -k key'?[y]es, [n]o, if [l]oaded, [k]eep old setting? '
1589            print
1590            [[ $key = [yYnNlLkK] ]] && break
1591          done
1592          case $key in
1593            [yY]) usec=true
1594                  ;;
1595            [nN]) usec=false
1596                  ;;
1597            [lL]) usec=
1598                  ;;
1599          esac
1600          ;;
1601       q) return 1
1602          ;;
1603     esac
1605   done
1607   __ci_set_this_style use-compctl usec
1609   return 0
1613 #       file-sort, special-dirs, ignore-parents,
1614 #       squeeze-slashes,
1615 __ci_do_file_styles() {
1616   local key files cursor expand speciald ignorep squeezes select
1617   local prefon suffon lssuffixes preserve
1619   __ci_get_this_style file-sort files
1620   __ci_get_this_style ignore-parents ignorep
1621   __ci_get_this_style special-dirs speciald
1622   __ci_get_this_style squeeze-slashes squeezes
1623   __ci_get_this_style expand expand
1624   __ci_get_this_style list-suffixes lssuffixes
1625   __ci_get_this_style preserve-prefix preserve
1626   [[ -n $preserve ]] && preserve=${(Q)preserve}
1628   while true; do
1629     clear
1630     print "\
1631       *** compinstall: options for filename completion ***
1633 1.  Choose how to sort the displayed list of filename matches.
1635 2.  In expressions with .., don't include directories already implied.
1637 3.  Allow completion of . and .. for the bone idle.
1639 4.  When expanding paths, \`foo//bar' is treated as \`foo/bar'.
1641 5.  Configure how multiple paths are expanded and displayed, 
1642     e.g. /f/b -> /foo/bar
1644 6.  Keep certain prefixes unchanged, such as \`//resource/'.
1646 q.  Return without saving.
1647 0.  Done setting options for filename completion.
1649     read -k key'?--- Hit selection --- '
1650     print
1652     [[ $key = 0 ]] && break
1654     case $key in
1655       (1) print "\
1656 Filenames listed as possible completions are usually displayed in
1657 alphabetical order.  You can alternatively choose:
1658   s  File size
1659   l  Number of (hard) links
1660   m  Modification time
1661   a  Access time
1662   i  Inode change time
1663   n  File name
1664   k  Keep the current setting
1665 You can also specify the reverse of any of the above orders (except \`k'):  to
1666 do this, type the appropriate letter in upper case.
1668          while true; do
1669            read -k key'?--- Hit selection --- '
1670            print
1671            [[ $key = [sSlLmMaAiInNkK] ]] && break
1672          done
1673          case $key in
1674            ([sS]) files=size;;
1675            ([lL]) files=links;;
1676            ([mM]) files=modification;;
1677            ([aA]) files=access;;
1678            ([iI]) files=inode;;
1679            ([nN]) files=name;;
1680          esac
1681          if [[ $key = [SLAMIN] ]]; then
1682            # slam it into reverse
1683            files="$files reverse"
1684          fi
1685          ;;
1686       (2) print "\
1687 When you type an expression containing \`..', you may usually not want to
1688 be offered certain directories for completion.
1689   p   Don't offer parents:  in \`foo/bar/../', don't make \`bar' a completion.
1690   c   Don't offer the current directory, e.g. after \`../'.
1691   o   Only perform the two tests if there is a real \`..' in the word so far.
1692   d   Only perform the two tests when completing directory names.
1693   0   None of the above; use normal completion.
1694   k   Keep the current settings.
1695 You may specify any combination of p, c, o, d including at least one of p
1696 and c, or you may specify either 0 or k.  Note that the _ignored completer
1697 functions in the normal way, i.e. you would be able to complete the
1698 directories in question if nothing else matched.
1700           while true; do
1701             vared -eh -p 'selection> ' select
1702             [[ ( $select = [pPcCoOdD]# && $select = *[pPcC]* )
1703                     || $select = [0kK] ]] && break
1704             print "Type any combination of p, c, o, d, or type 0 or k"
1705           done
1706           case $select in
1707             (0) ignorep=
1708                 ;;
1709             ([pPcCoOdD]#)
1710                 ignorep=()
1711                 [[ $select = *[pP]* ]] && ignorep=($ignorep parent)
1712                 [[ $select = *[cC]* ]] && ignorep=($ignorep pwd)
1713                 [[ $select = *[oO]* ]] && ignorep=($ignorep ..)
1714                 [[ $select = *[dD]* ]] && ignorep=($ignorep directory)
1715                 ;;
1716           esac
1717           ;;
1718       (3) print "\
1719 Filename completion does not usually offer the directory names \`.' and
1720 \`..' as choices.  However, some immensely lazy people can't even be
1721 bothered to type these.  Do you wish to be offered \`.' and \`..' as
1722 choices ([y]es, [n]o, [k]eep current setting)?
1724           while true; do
1725             read -k key'?--- Hit selection --- '
1726             [[ $key = [yYnNkK] ]] && break
1727             print "Type y, n or k."
1728           done
1729           case $key in
1730             ([yY]) speciald=true;;
1731             ([nN]) speciald=;;
1732           esac
1733           ;;
1734       (4) print "\
1735 Filename completion can complete sets of path segments at once, for example
1736 \`/u/X/l/X' to \`/usr/X11R6/lib/X11'.  Normally this means that multiple
1737 slashes in filenames are treated as matching multiple directories.  For
1738 example, \`foo//bar' could expand to \`foo/datthe/bar'.  You can, however,
1739 stick to the usual UNIX convention that multiple slashes are treated as
1740 a single slash.  Do you wish to treat multiple slashes the same as just
1741 one ([y]es, [n]o, [k]eep current setting)?
1743           while true; do
1744             read -k key'?--- Hit selection --- '
1745             [[ $key = [yYnNkK] ]] && break
1746             print "Type one of y, n or k."
1747           done
1748           case $key in
1749             ([yY]) squeezes=true;;
1750             ([nN]) squeezes=;;
1751           esac
1752           ;;
1753       (5) if [[ $expand = *prefix* ]]; then
1754              prefon=prefix
1755           else
1756              prefon=
1757           fi
1758           if [[ $expand = *suffix* ]]; then
1759              suffon=suffix
1760           else
1761              suffon=
1762           fi
1763           print "
1764 When expanding /f/b, the shell will attempt to match /f*/b* (e.g. /foo/bar), 
1765 and so on to any depth.  If the first part of the expansion fails, by default
1766 the shell will not expand the remainder.  However, you can force it always
1767 to expand the first part.  Currently this feature is ${${prefon:+on}:-off}.
1768 Do you want it on ([y]es, [n]o, [k]eep current setting)?
1770           while true; do
1771             read -k key'?--- Hit selection --- '
1772             [[ $key = [yYnNkK] ]] && break
1773             print "Type one of y, n or k."
1774           done
1775           case $key in
1776             ([yY]) prefon=prefix;;
1777             ([nN]) prefon=prefix;;
1778           esac
1779           print "
1780 Further, if /f*/b* is ambiguous, the shell will usually only expand
1781 as far as the part that is unambiguous; for example, if /foo/bar and
1782 /food/basket exist, it will wait for you to choose either /foo or /food,
1783 and not attempt to expand the rest of the match.  However, you can force
1784 it to add all possible completions for you to resolve conflicts in the
1785 normal way.  Currently this feature is ${${suffon:+on}:-off}.
1786 Do you want it on ([y]es, [n]o, [k]eep current setting)?
1788           while true; do
1789             read -k key'?--- Hit selection --- '
1790             [[ $key = [yYnNkK] ]] && break
1791             print "Type one of y, n or k."
1792           done
1793           case $key in
1794             ([yY]) suffon=suffix;;
1795             ([nN]) suffon=suffix;;
1796           esac
1797           expand=${prefon:+$prefon${suffon:+ }}${suffon}
1799           if [[ $lssuffixes = (1|[tT]|[yY]|[oO])* ]]; then
1800              lssuffixes=true
1801           else
1802              lssuffixes=
1803           fi
1804           print "
1805 When listing expansions of /f/b such as /foo/bar, /foo/bad, /failed/bag,
1806 the shell will usually only show the first part of the path if it is
1807 ambiguous, hence /foo will appear twice.  It is possible to show the
1808 full path in this case.  Currently this feature is ${${lssuffixes:+on}:-off}.
1809 Do you want this behaviour ([y]es, [n]o, [k]eep current setting)?
1811           while true; do
1812             read -k key'?--- Hit selection --- '
1813             [[ $key = [yYnNkK] ]] && break
1814             print "Type one of y, n or k."
1815           done
1816           case $key in
1817             ([yY]) lssuffixes=true;;
1818             ([nN]) lssuffixes=;;
1819           esac
1820           ;;
1821       (6) print "\
1822 On some systems, there are special forms for the start of a filename
1823 which should be left alone by the completion system.  For example, Cygwin
1824 uses a double slash to indicate a network resource, hence a prefix of
1825 the form \`//resource/' should be left alone.  This style gives a pattern
1826 to match any such prefixes; alternatives separated by \`|' are therefore
1827 possible.  Edit the pattern as you like.  If this is empty, the shell will not
1828 handle any prefixes specially."
1829           if [[ -z $preserve ]]; then
1830               preserve="//[^/]##/"
1831               print "
1832 Accept the default to handle network resources as just described."
1833           fi
1834           vared -eh -p "pattern> " preserve
1835           ;;
1836       (q) return 1
1837          ;;
1838     esac
1840   done
1842   __ci_set_this_style file-sort files
1843   __ci_set_this_style ignore-parents ignorep
1844   __ci_set_this_style special-dirs speciald
1845   __ci_set_this_style squeeze-slashes squeezes
1846   __ci_set_this_style expand expand
1847   __ci_set_this_style list-suffixes lssuffixes
1848   # pattern, always quote
1849   [[ -n $preserve ]] && preserve=${(qq)preserve}
1850   __ci_set_this_style preserve-prefix preserve
1852   return 0
1856 # TODO: history completion, jobs, prefix-needed 'n' stuff.
1857 __ci_do_misc() {
1858   local key
1860   while true; do
1861     clear
1862     print "\
1863       *** compinstall: options for particular types of completion ***
1865 1.  Options for file completion.
1867 q.  Return without saving.
1868 0.  Done setting options for particular completions.
1870     read -k key'?--- Hit selection --- '
1871     print
1873     [[ $key = 0 ]] && break
1875     case $key in
1876       1) __ci_do_file_styles
1877          ;;
1878       q) return 1
1879          ;;
1880     esac
1882   done
1884   return 0;
1888 # TODO: it should probably be possible to set completion options via
1889 #         compinstall, even though they've been around for years.
1891 while true; do
1892   clear
1893   print "\
1894                *** compinstall: main menu ***
1895 Note that hitting \`q' in menus does not abort the set of changes from
1896 lower level menus.  However, quitting at top level will ensure that nothing
1897 at all is actually written out.
1899 1.  Completers:  choose completion behaviour for tasks such as
1900     approximation, spell-checking, expansion.
1902 2.  Matching control: set behaviour for case-insensitive matching,
1903     extended (partial-word) matching and substring matching.
1905 3.  Styles for changing the way completions are displayed and inserted.
1907 4.  Styles for particular completions.
1909 c.  Change context (plus more information on contexts).
1911 q.  Return without saving.
1912 0.  Save and exit.
1915   __ci_newline \
1916     "--- Hit choice --- " || return 1
1918   # note this is a string test:  we require the `0' to have been typed.
1919   [[ $key = 0 ]] && break
1921   case $key in
1922     1) __ci_do_completers
1923        ;;
1924     2) __ci_do_matchers
1925        ;;
1926     3) __ci_do_display
1927        ;;
1928     4) __ci_do_misc
1929        ;;
1930     c) __ci_change_context
1931        ;;
1932   esac
1933 done
1936 if (( $#styles )); then
1937   typeset style stylevals context values
1938   for style in ${(ko)styles}; do
1939     stylevals=(${(f)styles[$style]})
1940     while (( $#stylevals )); do
1941       output="$output
1942 zstyle ${(qq)stylevals[1]} $style ${stylevals[2]}"
1943       shift 2 stylevals
1944     done
1945   done
1948 if [[ -z $ifile || -d $ifile ]] ||
1949   ! read -q key"?Save new settings to $ifile ([y]es, [n]o)? "; then
1950    print "Enter file to save in (~ will be expanded), or return to abort:"
1951    ifile=
1952    vared -ch -p 'file> ' ifile
1953    if [[ $ifile != [/~]* ]]; then
1954      ifile=$PWD/$ifile
1955      print "[Not absolute path; updating to $ifile]"
1956    fi
1957    ifile=${~ifile}
1960 local tmpout=${TMPPREFIX:-/tmp/zsh}compinstall$$
1962 # Assemble the complete set of lines to
1963 # insert.
1965 __ci_output >$tmpout
1967 if [[ -n $ifile ]]; then
1968   if [[ $ifile != *(zshrc|zlogin|zshenv) ]]; then 
1969     print "\
1970 If you want this file to be run automatically, you should add
1971   . $ifile
1972 to your .zshrc.  compinstall will remember the name of this file for
1973 future use."
1974     __ci_newline || return 1
1975   fi
1976   #
1977   # Now use sed to update the file.
1978   #
1979   if [[ -f $ifile ]]; then
1980     cp $ifile ${ifile}\~ &&
1981     print "Copied old file to ${ifile}~."
1982   else
1983     touch $ifile
1984   fi
1985   if { { grep "$endline" $ifile >/dev/null 2>&1 &&
1986          sed -e "/^[    ]*$endline/r $tmpout
1987 /^[     ]*$startline/,/^[       ]*$endline/d" $ifile >${tmpout}2 } || 
1988         { cp $ifile ${tmpout}2 && cat $tmpout >>${tmpout}2 } } &&
1989   cp ${tmpout}2 $ifile && rm -f ${tmpout}2; then
1990     print "\nSuccessfully added compinstall lines to $ifile."
1991     rm -f $tmpout
1992   else
1993     print "\nFailure adding lines to $ifile.  Lines left in \`$tmpout'"
1994   fi
1995   rm -f ${tmpout}2
1996 elif read -q key'?Print them to stdout instead ([y]es, [n]o)? '; then
1997   cat $tmpout
1998   rm -f $tmpout
2001 if read -q key'?Set new styles for immediate use ([y]es, [n]o)? '; then
2002   eval $output
2003   print "The new settings are now in effect.  Note this will not remove old
2004 styles you have deleted until you restart the shell."
2007 __ci_tidyup
2008 return 0