Merge branch 'ls/typofix'
[git] / contrib / completion / git-completion.bash
1 # bash/zsh completion support for core Git.
2 #
3 # Copyright (C) 2006,2007 Shawn O. Pearce <spearce@spearce.org>
4 # Conceptually based on gitcompletion (http://gitweb.hawaga.org.uk/).
5 # Distributed under the GNU General Public License, version 2.0.
6 #
7 # The contained completion routines provide support for completing:
8 #
9 #    *) local and remote branch names
10 #    *) local and remote tag names
11 #    *) .git/remotes file names
12 #    *) git 'subcommands'
13 #    *) git email aliases for git-send-email
14 #    *) tree paths within 'ref:path/to/file' expressions
15 #    *) file paths within current working directory and index
16 #    *) common --long-options
17 #
18 # To use these routines:
19 #
20 #    1) Copy this file to somewhere (e.g. ~/.git-completion.bash).
21 #    2) Add the following line to your .bashrc/.zshrc:
22 #        source ~/.git-completion.bash
23 #    3) Consider changing your PS1 to also show the current branch,
24 #       see git-prompt.sh for details.
25 #
26 # If you use complex aliases of form '!f() { ... }; f', you can use the null
27 # command ':' as the first command in the function body to declare the desired
28 # completion style.  For example '!f() { : git commit ; ... }; f' will
29 # tell the completion to use commit completion.  This also works with aliases
30 # of form "!sh -c '...'".  For example, "!sh -c ': git commit ; ... '".
31 #
32 # If you have a command that is not part of git, but you would still
33 # like completion, you can use __git_complete:
34 #
35 #   __git_complete gl git_log
36 #
37 # Or if it's a main command (i.e. git or gitk):
38 #
39 #   __git_complete gk gitk
40 #
41 # Compatible with bash 3.2.57.
42 #
43 # You can set the following environment variables to influence the behavior of
44 # the completion routines:
45 #
46 #   GIT_COMPLETION_CHECKOUT_NO_GUESS
47 #
48 #     When set to "1", do not include "DWIM" suggestions in git-checkout
49 #     and git-switch completion (e.g., completing "foo" when "origin/foo"
50 #     exists).
51 #
52 #   GIT_COMPLETION_SHOW_ALL
53 #
54 #     When set to "1" suggest all options, including options which are
55 #     typically hidden (e.g. '--allow-empty' for 'git commit').
56
57 case "$COMP_WORDBREAKS" in
58 *:*) : great ;;
59 *)   COMP_WORDBREAKS="$COMP_WORDBREAKS:"
60 esac
61
62 # Discovers the path to the git repository taking any '--git-dir=<path>' and
63 # '-C <path>' options into account and stores it in the $__git_repo_path
64 # variable.
65 __git_find_repo_path ()
66 {
67         if [ -n "${__git_repo_path-}" ]; then
68                 # we already know where it is
69                 return
70         fi
71
72         if [ -n "${__git_C_args-}" ]; then
73                 __git_repo_path="$(git "${__git_C_args[@]}" \
74                         ${__git_dir:+--git-dir="$__git_dir"} \
75                         rev-parse --absolute-git-dir 2>/dev/null)"
76         elif [ -n "${__git_dir-}" ]; then
77                 test -d "$__git_dir" &&
78                 __git_repo_path="$__git_dir"
79         elif [ -n "${GIT_DIR-}" ]; then
80                 test -d "$GIT_DIR" &&
81                 __git_repo_path="$GIT_DIR"
82         elif [ -d .git ]; then
83                 __git_repo_path=.git
84         else
85                 __git_repo_path="$(git rev-parse --git-dir 2>/dev/null)"
86         fi
87 }
88
89 # Deprecated: use __git_find_repo_path() and $__git_repo_path instead
90 # __gitdir accepts 0 or 1 arguments (i.e., location)
91 # returns location of .git repo
92 __gitdir ()
93 {
94         if [ -z "${1-}" ]; then
95                 __git_find_repo_path || return 1
96                 echo "$__git_repo_path"
97         elif [ -d "$1/.git" ]; then
98                 echo "$1/.git"
99         else
100                 echo "$1"
101         fi
102 }
103
104 # Runs git with all the options given as argument, respecting any
105 # '--git-dir=<path>' and '-C <path>' options present on the command line
106 __git ()
107 {
108         git ${__git_C_args:+"${__git_C_args[@]}"} \
109                 ${__git_dir:+--git-dir="$__git_dir"} "$@" 2>/dev/null
110 }
111
112 # Removes backslash escaping, single quotes and double quotes from a word,
113 # stores the result in the variable $dequoted_word.
114 # 1: The word to dequote.
115 __git_dequote ()
116 {
117         local rest="$1" len ch
118
119         dequoted_word=""
120
121         while test -n "$rest"; do
122                 len=${#dequoted_word}
123                 dequoted_word="$dequoted_word${rest%%[\\\'\"]*}"
124                 rest="${rest:$((${#dequoted_word}-$len))}"
125
126                 case "${rest:0:1}" in
127                 \\)
128                         ch="${rest:1:1}"
129                         case "$ch" in
130                         $'\n')
131                                 ;;
132                         *)
133                                 dequoted_word="$dequoted_word$ch"
134                                 ;;
135                         esac
136                         rest="${rest:2}"
137                         ;;
138                 \')
139                         rest="${rest:1}"
140                         len=${#dequoted_word}
141                         dequoted_word="$dequoted_word${rest%%\'*}"
142                         rest="${rest:$((${#dequoted_word}-$len+1))}"
143                         ;;
144                 \")
145                         rest="${rest:1}"
146                         while test -n "$rest" ; do
147                                 len=${#dequoted_word}
148                                 dequoted_word="$dequoted_word${rest%%[\\\"]*}"
149                                 rest="${rest:$((${#dequoted_word}-$len))}"
150                                 case "${rest:0:1}" in
151                                 \\)
152                                         ch="${rest:1:1}"
153                                         case "$ch" in
154                                         \"|\\|\$|\`)
155                                                 dequoted_word="$dequoted_word$ch"
156                                                 ;;
157                                         $'\n')
158                                                 ;;
159                                         *)
160                                                 dequoted_word="$dequoted_word\\$ch"
161                                                 ;;
162                                         esac
163                                         rest="${rest:2}"
164                                         ;;
165                                 \")
166                                         rest="${rest:1}"
167                                         break
168                                         ;;
169                                 esac
170                         done
171                         ;;
172                 esac
173         done
174 }
175
176 # The following function is based on code from:
177 #
178 #   bash_completion - programmable completion functions for bash 3.2+
179 #
180 #   Copyright © 2006-2008, Ian Macdonald <ian@caliban.org>
181 #             © 2009-2010, Bash Completion Maintainers
182 #                     <bash-completion-devel@lists.alioth.debian.org>
183 #
184 #   This program is free software; you can redistribute it and/or modify
185 #   it under the terms of the GNU General Public License as published by
186 #   the Free Software Foundation; either version 2, or (at your option)
187 #   any later version.
188 #
189 #   This program is distributed in the hope that it will be useful,
190 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
191 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
192 #   GNU General Public License for more details.
193 #
194 #   You should have received a copy of the GNU General Public License
195 #   along with this program; if not, see <http://www.gnu.org/licenses/>.
196 #
197 #   The latest version of this software can be obtained here:
198 #
199 #   http://bash-completion.alioth.debian.org/
200 #
201 #   RELEASE: 2.x
202
203 # This function can be used to access a tokenized list of words
204 # on the command line:
205 #
206 #       __git_reassemble_comp_words_by_ref '=:'
207 #       if test "${words_[cword_-1]}" = -w
208 #       then
209 #               ...
210 #       fi
211 #
212 # The argument should be a collection of characters from the list of
213 # word completion separators (COMP_WORDBREAKS) to treat as ordinary
214 # characters.
215 #
216 # This is roughly equivalent to going back in time and setting
217 # COMP_WORDBREAKS to exclude those characters.  The intent is to
218 # make option types like --date=<type> and <rev>:<path> easy to
219 # recognize by treating each shell word as a single token.
220 #
221 # It is best not to set COMP_WORDBREAKS directly because the value is
222 # shared with other completion scripts.  By the time the completion
223 # function gets called, COMP_WORDS has already been populated so local
224 # changes to COMP_WORDBREAKS have no effect.
225 #
226 # Output: words_, cword_, cur_.
227
228 __git_reassemble_comp_words_by_ref()
229 {
230         local exclude i j first
231         # Which word separators to exclude?
232         exclude="${1//[^$COMP_WORDBREAKS]}"
233         cword_=$COMP_CWORD
234         if [ -z "$exclude" ]; then
235                 words_=("${COMP_WORDS[@]}")
236                 return
237         fi
238         # List of word completion separators has shrunk;
239         # re-assemble words to complete.
240         for ((i=0, j=0; i < ${#COMP_WORDS[@]}; i++, j++)); do
241                 # Append each nonempty word consisting of just
242                 # word separator characters to the current word.
243                 first=t
244                 while
245                         [ $i -gt 0 ] &&
246                         [ -n "${COMP_WORDS[$i]}" ] &&
247                         # word consists of excluded word separators
248                         [ "${COMP_WORDS[$i]//[^$exclude]}" = "${COMP_WORDS[$i]}" ]
249                 do
250                         # Attach to the previous token,
251                         # unless the previous token is the command name.
252                         if [ $j -ge 2 ] && [ -n "$first" ]; then
253                                 ((j--))
254                         fi
255                         first=
256                         words_[$j]=${words_[j]}${COMP_WORDS[i]}
257                         if [ $i = $COMP_CWORD ]; then
258                                 cword_=$j
259                         fi
260                         if (($i < ${#COMP_WORDS[@]} - 1)); then
261                                 ((i++))
262                         else
263                                 # Done.
264                                 return
265                         fi
266                 done
267                 words_[$j]=${words_[j]}${COMP_WORDS[i]}
268                 if [ $i = $COMP_CWORD ]; then
269                         cword_=$j
270                 fi
271         done
272 }
273
274 if ! type _get_comp_words_by_ref >/dev/null 2>&1; then
275 _get_comp_words_by_ref ()
276 {
277         local exclude cur_ words_ cword_
278         if [ "$1" = "-n" ]; then
279                 exclude=$2
280                 shift 2
281         fi
282         __git_reassemble_comp_words_by_ref "$exclude"
283         cur_=${words_[cword_]}
284         while [ $# -gt 0 ]; do
285                 case "$1" in
286                 cur)
287                         cur=$cur_
288                         ;;
289                 prev)
290                         prev=${words_[$cword_-1]}
291                         ;;
292                 words)
293                         words=("${words_[@]}")
294                         ;;
295                 cword)
296                         cword=$cword_
297                         ;;
298                 esac
299                 shift
300         done
301 }
302 fi
303
304 # Fills the COMPREPLY array with prefiltered words without any additional
305 # processing.
306 # Callers must take care of providing only words that match the current word
307 # to be completed and adding any prefix and/or suffix (trailing space!), if
308 # necessary.
309 # 1: List of newline-separated matching completion words, complete with
310 #    prefix and suffix.
311 __gitcomp_direct ()
312 {
313         local IFS=$'\n'
314
315         COMPREPLY=($1)
316 }
317
318 # Similar to __gitcomp_direct, but appends to COMPREPLY instead.
319 # Callers must take care of providing only words that match the current word
320 # to be completed and adding any prefix and/or suffix (trailing space!), if
321 # necessary.
322 # 1: List of newline-separated matching completion words, complete with
323 #    prefix and suffix.
324 __gitcomp_direct_append ()
325 {
326         local IFS=$'\n'
327
328         COMPREPLY+=($1)
329 }
330
331 __gitcompappend ()
332 {
333         local x i=${#COMPREPLY[@]}
334         for x in $1; do
335                 if [[ "$x" == "$3"* ]]; then
336                         COMPREPLY[i++]="$2$x$4"
337                 fi
338         done
339 }
340
341 __gitcompadd ()
342 {
343         COMPREPLY=()
344         __gitcompappend "$@"
345 }
346
347 # Generates completion reply, appending a space to possible completion words,
348 # if necessary.
349 # It accepts 1 to 4 arguments:
350 # 1: List of possible completion words.
351 # 2: A prefix to be added to each possible completion word (optional).
352 # 3: Generate possible completion matches for this word (optional).
353 # 4: A suffix to be appended to each possible completion word (optional).
354 __gitcomp ()
355 {
356         local cur_="${3-$cur}"
357
358         case "$cur_" in
359         --*=)
360                 ;;
361         --no-*)
362                 local c i=0 IFS=$' \t\n'
363                 for c in $1; do
364                         if [[ $c == "--" ]]; then
365                                 continue
366                         fi
367                         c="$c${4-}"
368                         if [[ $c == "$cur_"* ]]; then
369                                 case $c in
370                                 --*=|*.) ;;
371                                 *) c="$c " ;;
372                                 esac
373                                 COMPREPLY[i++]="${2-}$c"
374                         fi
375                 done
376                 ;;
377         *)
378                 local c i=0 IFS=$' \t\n'
379                 for c in $1; do
380                         if [[ $c == "--" ]]; then
381                                 c="--no-...${4-}"
382                                 if [[ $c == "$cur_"* ]]; then
383                                         COMPREPLY[i++]="${2-}$c "
384                                 fi
385                                 break
386                         fi
387                         c="$c${4-}"
388                         if [[ $c == "$cur_"* ]]; then
389                                 case $c in
390                                 *=|*.) ;;
391                                 *) c="$c " ;;
392                                 esac
393                                 COMPREPLY[i++]="${2-}$c"
394                         fi
395                 done
396                 ;;
397         esac
398 }
399
400 # Clear the variables caching builtins' options when (re-)sourcing
401 # the completion script.
402 if [[ -n ${ZSH_VERSION-} ]]; then
403         unset ${(M)${(k)parameters[@]}:#__gitcomp_builtin_*} 2>/dev/null
404 else
405         unset $(compgen -v __gitcomp_builtin_)
406 fi
407
408 # This function is equivalent to
409 #
410 #    __gitcomp "$(git xxx --git-completion-helper) ..."
411 #
412 # except that the output is cached. Accept 1-3 arguments:
413 # 1: the git command to execute, this is also the cache key
414 # 2: extra options to be added on top (e.g. negative forms)
415 # 3: options to be excluded
416 __gitcomp_builtin ()
417 {
418         # spaces must be replaced with underscore for multi-word
419         # commands, e.g. "git remote add" becomes remote_add.
420         local cmd="$1"
421         local incl="${2-}"
422         local excl="${3-}"
423
424         local var=__gitcomp_builtin_"${cmd/-/_}"
425         local options
426         eval "options=\${$var-}"
427
428         if [ -z "$options" ]; then
429                 local completion_helper
430                 if [ "${GIT_COMPLETION_SHOW_ALL-}" = "1" ]; then
431                         completion_helper="--git-completion-helper-all"
432                 else
433                         completion_helper="--git-completion-helper"
434                 fi
435                 # leading and trailing spaces are significant to make
436                 # option removal work correctly.
437                 options=" $incl $(__git ${cmd/_/ } $completion_helper) " || return
438
439                 for i in $excl; do
440                         options="${options/ $i / }"
441                 done
442                 eval "$var=\"$options\""
443         fi
444
445         __gitcomp "$options"
446 }
447
448 # Variation of __gitcomp_nl () that appends to the existing list of
449 # completion candidates, COMPREPLY.
450 __gitcomp_nl_append ()
451 {
452         local IFS=$'\n'
453         __gitcompappend "$1" "${2-}" "${3-$cur}" "${4- }"
454 }
455
456 # Generates completion reply from newline-separated possible completion words
457 # by appending a space to all of them.
458 # It accepts 1 to 4 arguments:
459 # 1: List of possible completion words, separated by a single newline.
460 # 2: A prefix to be added to each possible completion word (optional).
461 # 3: Generate possible completion matches for this word (optional).
462 # 4: A suffix to be appended to each possible completion word instead of
463 #    the default space (optional).  If specified but empty, nothing is
464 #    appended.
465 __gitcomp_nl ()
466 {
467         COMPREPLY=()
468         __gitcomp_nl_append "$@"
469 }
470
471 # Fills the COMPREPLY array with prefiltered paths without any additional
472 # processing.
473 # Callers must take care of providing only paths that match the current path
474 # to be completed and adding any prefix path components, if necessary.
475 # 1: List of newline-separated matching paths, complete with all prefix
476 #    path components.
477 __gitcomp_file_direct ()
478 {
479         local IFS=$'\n'
480
481         COMPREPLY=($1)
482
483         # use a hack to enable file mode in bash < 4
484         compopt -o filenames +o nospace 2>/dev/null ||
485         compgen -f /non-existing-dir/ >/dev/null ||
486         true
487 }
488
489 # Generates completion reply with compgen from newline-separated possible
490 # completion filenames.
491 # It accepts 1 to 3 arguments:
492 # 1: List of possible completion filenames, separated by a single newline.
493 # 2: A directory prefix to be added to each possible completion filename
494 #    (optional).
495 # 3: Generate possible completion matches for this word (optional).
496 __gitcomp_file ()
497 {
498         local IFS=$'\n'
499
500         # XXX does not work when the directory prefix contains a tilde,
501         # since tilde expansion is not applied.
502         # This means that COMPREPLY will be empty and Bash default
503         # completion will be used.
504         __gitcompadd "$1" "${2-}" "${3-$cur}" ""
505
506         # use a hack to enable file mode in bash < 4
507         compopt -o filenames +o nospace 2>/dev/null ||
508         compgen -f /non-existing-dir/ >/dev/null ||
509         true
510 }
511
512 # Execute 'git ls-files', unless the --committable option is specified, in
513 # which case it runs 'git diff-index' to find out the files that can be
514 # committed.  It return paths relative to the directory specified in the first
515 # argument, and using the options specified in the second argument.
516 __git_ls_files_helper ()
517 {
518         if [ "$2" == "--committable" ]; then
519                 __git -C "$1" -c core.quotePath=false diff-index \
520                         --name-only --relative HEAD -- "${3//\\/\\\\}*"
521         else
522                 # NOTE: $2 is not quoted in order to support multiple options
523                 __git -C "$1" -c core.quotePath=false ls-files \
524                         --exclude-standard $2 -- "${3//\\/\\\\}*"
525         fi
526 }
527
528
529 # __git_index_files accepts 1 or 2 arguments:
530 # 1: Options to pass to ls-files (required).
531 # 2: A directory path (optional).
532 #    If provided, only files within the specified directory are listed.
533 #    Sub directories are never recursed.  Path must have a trailing
534 #    slash.
535 # 3: List only paths matching this path component (optional).
536 __git_index_files ()
537 {
538         local root="$2" match="$3"
539
540         __git_ls_files_helper "$root" "$1" "${match:-?}" |
541         awk -F / -v pfx="${2//\\/\\\\}" '{
542                 paths[$1] = 1
543         }
544         END {
545                 for (p in paths) {
546                         if (substr(p, 1, 1) != "\"") {
547                                 # No special characters, easy!
548                                 print pfx p
549                                 continue
550                         }
551
552                         # The path is quoted.
553                         p = dequote(p)
554                         if (p == "")
555                                 continue
556
557                         # Even when a directory name itself does not contain
558                         # any special characters, it will still be quoted if
559                         # any of its (stripped) trailing path components do.
560                         # Because of this we may have seen the same directory
561                         # both quoted and unquoted.
562                         if (p in paths)
563                                 # We have seen the same directory unquoted,
564                                 # skip it.
565                                 continue
566                         else
567                                 print pfx p
568                 }
569         }
570         function dequote(p,    bs_idx, out, esc, esc_idx, dec) {
571                 # Skip opening double quote.
572                 p = substr(p, 2)
573
574                 # Interpret backslash escape sequences.
575                 while ((bs_idx = index(p, "\\")) != 0) {
576                         out = out substr(p, 1, bs_idx - 1)
577                         esc = substr(p, bs_idx + 1, 1)
578                         p = substr(p, bs_idx + 2)
579
580                         if ((esc_idx = index("abtvfr\"\\", esc)) != 0) {
581                                 # C-style one-character escape sequence.
582                                 out = out substr("\a\b\t\v\f\r\"\\",
583                                                  esc_idx, 1)
584                         } else if (esc == "n") {
585                                 # Uh-oh, a newline character.
586                                 # We cannot reliably put a pathname
587                                 # containing a newline into COMPREPLY,
588                                 # and the newline would create a mess.
589                                 # Skip this path.
590                                 return ""
591                         } else {
592                                 # Must be a \nnn octal value, then.
593                                 dec = esc             * 64 + \
594                                       substr(p, 1, 1) * 8  + \
595                                       substr(p, 2, 1)
596                                 out = out sprintf("%c", dec)
597                                 p = substr(p, 3)
598                         }
599                 }
600                 # Drop closing double quote, if there is one.
601                 # (There is not any if this is a directory, as it was
602                 # already stripped with the trailing path components.)
603                 if (substr(p, length(p), 1) == "\"")
604                         out = out substr(p, 1, length(p) - 1)
605                 else
606                         out = out p
607
608                 return out
609         }'
610 }
611
612 # __git_complete_index_file requires 1 argument:
613 # 1: the options to pass to ls-file
614 #
615 # The exception is --committable, which finds the files appropriate commit.
616 __git_complete_index_file ()
617 {
618         local dequoted_word pfx="" cur_
619
620         __git_dequote "$cur"
621
622         case "$dequoted_word" in
623         ?*/*)
624                 pfx="${dequoted_word%/*}/"
625                 cur_="${dequoted_word##*/}"
626                 ;;
627         *)
628                 cur_="$dequoted_word"
629         esac
630
631         __gitcomp_file_direct "$(__git_index_files "$1" "$pfx" "$cur_")"
632 }
633
634 # Lists branches from the local repository.
635 # 1: A prefix to be added to each listed branch (optional).
636 # 2: List only branches matching this word (optional; list all branches if
637 #    unset or empty).
638 # 3: A suffix to be appended to each listed branch (optional).
639 __git_heads ()
640 {
641         local pfx="${1-}" cur_="${2-}" sfx="${3-}"
642
643         __git for-each-ref --format="${pfx//\%/%%}%(refname:strip=2)$sfx" \
644                         "refs/heads/$cur_*" "refs/heads/$cur_*/**"
645 }
646
647 # Lists branches from remote repositories.
648 # 1: A prefix to be added to each listed branch (optional).
649 # 2: List only branches matching this word (optional; list all branches if
650 #    unset or empty).
651 # 3: A suffix to be appended to each listed branch (optional).
652 __git_remote_heads ()
653 {
654         local pfx="${1-}" cur_="${2-}" sfx="${3-}"
655
656         __git for-each-ref --format="${pfx//\%/%%}%(refname:strip=2)$sfx" \
657                         "refs/remotes/$cur_*" "refs/remotes/$cur_*/**"
658 }
659
660 # Lists tags from the local repository.
661 # Accepts the same positional parameters as __git_heads() above.
662 __git_tags ()
663 {
664         local pfx="${1-}" cur_="${2-}" sfx="${3-}"
665
666         __git for-each-ref --format="${pfx//\%/%%}%(refname:strip=2)$sfx" \
667                         "refs/tags/$cur_*" "refs/tags/$cur_*/**"
668 }
669
670 # List unique branches from refs/remotes used for 'git checkout' and 'git
671 # switch' tracking DWIMery.
672 # 1: A prefix to be added to each listed branch (optional)
673 # 2: List only branches matching this word (optional; list all branches if
674 #    unset or empty).
675 # 3: A suffix to be appended to each listed branch (optional).
676 __git_dwim_remote_heads ()
677 {
678         local pfx="${1-}" cur_="${2-}" sfx="${3-}"
679         local fer_pfx="${pfx//\%/%%}" # "escape" for-each-ref format specifiers
680
681         # employ the heuristic used by git checkout and git switch
682         # Try to find a remote branch that cur_es the completion word
683         # but only output if the branch name is unique
684         __git for-each-ref --format="$fer_pfx%(refname:strip=3)$sfx" \
685                 --sort="refname:strip=3" \
686                 "refs/remotes/*/$cur_*" "refs/remotes/*/$cur_*/**" | \
687         uniq -u
688 }
689
690 # Lists refs from the local (by default) or from a remote repository.
691 # It accepts 0, 1 or 2 arguments:
692 # 1: The remote to list refs from (optional; ignored, if set but empty).
693 #    Can be the name of a configured remote, a path, or a URL.
694 # 2: In addition to local refs, list unique branches from refs/remotes/ for
695 #    'git checkout's tracking DWIMery (optional; ignored, if set but empty).
696 # 3: A prefix to be added to each listed ref (optional).
697 # 4: List only refs matching this word (optional; list all refs if unset or
698 #    empty).
699 # 5: A suffix to be appended to each listed ref (optional; ignored, if set
700 #    but empty).
701 #
702 # Use __git_complete_refs() instead.
703 __git_refs ()
704 {
705         local i hash dir track="${2-}"
706         local list_refs_from=path remote="${1-}"
707         local format refs
708         local pfx="${3-}" cur_="${4-$cur}" sfx="${5-}"
709         local match="${4-}"
710         local fer_pfx="${pfx//\%/%%}" # "escape" for-each-ref format specifiers
711
712         __git_find_repo_path
713         dir="$__git_repo_path"
714
715         if [ -z "$remote" ]; then
716                 if [ -z "$dir" ]; then
717                         return
718                 fi
719         else
720                 if __git_is_configured_remote "$remote"; then
721                         # configured remote takes precedence over a
722                         # local directory with the same name
723                         list_refs_from=remote
724                 elif [ -d "$remote/.git" ]; then
725                         dir="$remote/.git"
726                 elif [ -d "$remote" ]; then
727                         dir="$remote"
728                 else
729                         list_refs_from=url
730                 fi
731         fi
732
733         if [ "$list_refs_from" = path ]; then
734                 if [[ "$cur_" == ^* ]]; then
735                         pfx="$pfx^"
736                         fer_pfx="$fer_pfx^"
737                         cur_=${cur_#^}
738                         match=${match#^}
739                 fi
740                 case "$cur_" in
741                 refs|refs/*)
742                         format="refname"
743                         refs=("$match*" "$match*/**")
744                         track=""
745                         ;;
746                 *)
747                         for i in HEAD FETCH_HEAD ORIG_HEAD MERGE_HEAD REBASE_HEAD CHERRY_PICK_HEAD; do
748                                 case "$i" in
749                                 $match*)
750                                         if [ -e "$dir/$i" ]; then
751                                                 echo "$pfx$i$sfx"
752                                         fi
753                                         ;;
754                                 esac
755                         done
756                         format="refname:strip=2"
757                         refs=("refs/tags/$match*" "refs/tags/$match*/**"
758                                 "refs/heads/$match*" "refs/heads/$match*/**"
759                                 "refs/remotes/$match*" "refs/remotes/$match*/**")
760                         ;;
761                 esac
762                 __git_dir="$dir" __git for-each-ref --format="$fer_pfx%($format)$sfx" \
763                         "${refs[@]}"
764                 if [ -n "$track" ]; then
765                         __git_dwim_remote_heads "$pfx" "$match" "$sfx"
766                 fi
767                 return
768         fi
769         case "$cur_" in
770         refs|refs/*)
771                 __git ls-remote "$remote" "$match*" | \
772                 while read -r hash i; do
773                         case "$i" in
774                         *^{}) ;;
775                         *) echo "$pfx$i$sfx" ;;
776                         esac
777                 done
778                 ;;
779         *)
780                 if [ "$list_refs_from" = remote ]; then
781                         case "HEAD" in
782                         $match*)        echo "${pfx}HEAD$sfx" ;;
783                         esac
784                         __git for-each-ref --format="$fer_pfx%(refname:strip=3)$sfx" \
785                                 "refs/remotes/$remote/$match*" \
786                                 "refs/remotes/$remote/$match*/**"
787                 else
788                         local query_symref
789                         case "HEAD" in
790                         $match*)        query_symref="HEAD" ;;
791                         esac
792                         __git ls-remote "$remote" $query_symref \
793                                 "refs/tags/$match*" "refs/heads/$match*" \
794                                 "refs/remotes/$match*" |
795                         while read -r hash i; do
796                                 case "$i" in
797                                 *^{})   ;;
798                                 refs/*) echo "$pfx${i#refs/*/}$sfx" ;;
799                                 *)      echo "$pfx$i$sfx" ;;  # symbolic refs
800                                 esac
801                         done
802                 fi
803                 ;;
804         esac
805 }
806
807 # Completes refs, short and long, local and remote, symbolic and pseudo.
808 #
809 # Usage: __git_complete_refs [<option>]...
810 # --remote=<remote>: The remote to list refs from, can be the name of a
811 #                    configured remote, a path, or a URL.
812 # --dwim: List unique remote branches for 'git switch's tracking DWIMery.
813 # --pfx=<prefix>: A prefix to be added to each ref.
814 # --cur=<word>: The current ref to be completed.  Defaults to the current
815 #               word to be completed.
816 # --sfx=<suffix>: A suffix to be appended to each ref instead of the default
817 #                 space.
818 # --mode=<mode>: What set of refs to complete, one of 'refs' (the default) to
819 #                complete all refs, 'heads' to complete only branches, or
820 #                'remote-heads' to complete only remote branches. Note that
821 #                --remote is only compatible with --mode=refs.
822 __git_complete_refs ()
823 {
824         local remote= dwim= pfx= cur_="$cur" sfx=" " mode="refs"
825
826         while test $# != 0; do
827                 case "$1" in
828                 --remote=*)     remote="${1##--remote=}" ;;
829                 --dwim)         dwim="yes" ;;
830                 # --track is an old spelling of --dwim
831                 --track)        dwim="yes" ;;
832                 --pfx=*)        pfx="${1##--pfx=}" ;;
833                 --cur=*)        cur_="${1##--cur=}" ;;
834                 --sfx=*)        sfx="${1##--sfx=}" ;;
835                 --mode=*)       mode="${1##--mode=}" ;;
836                 *)              return 1 ;;
837                 esac
838                 shift
839         done
840
841         # complete references based on the specified mode
842         case "$mode" in
843                 refs)
844                         __gitcomp_direct "$(__git_refs "$remote" "" "$pfx" "$cur_" "$sfx")" ;;
845                 heads)
846                         __gitcomp_direct "$(__git_heads "$pfx" "$cur_" "$sfx")" ;;
847                 remote-heads)
848                         __gitcomp_direct "$(__git_remote_heads "$pfx" "$cur_" "$sfx")" ;;
849                 *)
850                         return 1 ;;
851         esac
852
853         # Append DWIM remote branch names if requested
854         if [ "$dwim" = "yes" ]; then
855                 __gitcomp_direct_append "$(__git_dwim_remote_heads "$pfx" "$cur_" "$sfx")"
856         fi
857 }
858
859 # __git_refs2 requires 1 argument (to pass to __git_refs)
860 # Deprecated: use __git_complete_fetch_refspecs() instead.
861 __git_refs2 ()
862 {
863         local i
864         for i in $(__git_refs "$1"); do
865                 echo "$i:$i"
866         done
867 }
868
869 # Completes refspecs for fetching from a remote repository.
870 # 1: The remote repository.
871 # 2: A prefix to be added to each listed refspec (optional).
872 # 3: The ref to be completed as a refspec instead of the current word to be
873 #    completed (optional)
874 # 4: A suffix to be appended to each listed refspec instead of the default
875 #    space (optional).
876 __git_complete_fetch_refspecs ()
877 {
878         local i remote="$1" pfx="${2-}" cur_="${3-$cur}" sfx="${4- }"
879
880         __gitcomp_direct "$(
881                 for i in $(__git_refs "$remote" "" "" "$cur_") ; do
882                         echo "$pfx$i:$i$sfx"
883                 done
884                 )"
885 }
886
887 # __git_refs_remotes requires 1 argument (to pass to ls-remote)
888 __git_refs_remotes ()
889 {
890         local i hash
891         __git ls-remote "$1" 'refs/heads/*' | \
892         while read -r hash i; do
893                 echo "$i:refs/remotes/$1/${i#refs/heads/}"
894         done
895 }
896
897 __git_remotes ()
898 {
899         __git_find_repo_path
900         test -d "$__git_repo_path/remotes" && ls -1 "$__git_repo_path/remotes"
901         __git remote
902 }
903
904 # Returns true if $1 matches the name of a configured remote, false otherwise.
905 __git_is_configured_remote ()
906 {
907         local remote
908         for remote in $(__git_remotes); do
909                 if [ "$remote" = "$1" ]; then
910                         return 0
911                 fi
912         done
913         return 1
914 }
915
916 __git_list_merge_strategies ()
917 {
918         LANG=C LC_ALL=C git merge -s help 2>&1 |
919         sed -n -e '/[Aa]vailable strategies are: /,/^$/{
920                 s/\.$//
921                 s/.*://
922                 s/^[    ]*//
923                 s/[     ]*$//
924                 p
925         }'
926 }
927
928 __git_merge_strategies=
929 # 'git merge -s help' (and thus detection of the merge strategy
930 # list) fails, unfortunately, if run outside of any git working
931 # tree.  __git_merge_strategies is set to the empty string in
932 # that case, and the detection will be repeated the next time it
933 # is needed.
934 __git_compute_merge_strategies ()
935 {
936         test -n "$__git_merge_strategies" ||
937         __git_merge_strategies=$(__git_list_merge_strategies)
938 }
939
940 __git_merge_strategy_options="ours theirs subtree subtree= patience
941         histogram diff-algorithm= ignore-space-change ignore-all-space
942         ignore-space-at-eol renormalize no-renormalize no-renames
943         find-renames find-renames= rename-threshold="
944
945 __git_complete_revlist_file ()
946 {
947         local dequoted_word pfx ls ref cur_="$cur"
948         case "$cur_" in
949         *..?*:*)
950                 return
951                 ;;
952         ?*:*)
953                 ref="${cur_%%:*}"
954                 cur_="${cur_#*:}"
955
956                 __git_dequote "$cur_"
957
958                 case "$dequoted_word" in
959                 ?*/*)
960                         pfx="${dequoted_word%/*}"
961                         cur_="${dequoted_word##*/}"
962                         ls="$ref:$pfx"
963                         pfx="$pfx/"
964                         ;;
965                 *)
966                         cur_="$dequoted_word"
967                         ls="$ref"
968                         ;;
969                 esac
970
971                 case "$COMP_WORDBREAKS" in
972                 *:*) : great ;;
973                 *)   pfx="$ref:$pfx" ;;
974                 esac
975
976                 __gitcomp_file "$(__git ls-tree "$ls" \
977                                 | sed 's/^.*    //
978                                        s/$//')" \
979                         "$pfx" "$cur_"
980                 ;;
981         *...*)
982                 pfx="${cur_%...*}..."
983                 cur_="${cur_#*...}"
984                 __git_complete_refs --pfx="$pfx" --cur="$cur_"
985                 ;;
986         *..*)
987                 pfx="${cur_%..*}.."
988                 cur_="${cur_#*..}"
989                 __git_complete_refs --pfx="$pfx" --cur="$cur_"
990                 ;;
991         *)
992                 __git_complete_refs
993                 ;;
994         esac
995 }
996
997 __git_complete_file ()
998 {
999         __git_complete_revlist_file
1000 }
1001
1002 __git_complete_revlist ()
1003 {
1004         __git_complete_revlist_file
1005 }
1006
1007 __git_complete_remote_or_refspec ()
1008 {
1009         local cur_="$cur" cmd="${words[__git_cmd_idx]}"
1010         local i c=$((__git_cmd_idx+1)) remote="" pfx="" lhs=1 no_complete_refspec=0
1011         if [ "$cmd" = "remote" ]; then
1012                 ((c++))
1013         fi
1014         while [ $c -lt $cword ]; do
1015                 i="${words[c]}"
1016                 case "$i" in
1017                 --mirror) [ "$cmd" = "push" ] && no_complete_refspec=1 ;;
1018                 -d|--delete) [ "$cmd" = "push" ] && lhs=0 ;;
1019                 --all)
1020                         case "$cmd" in
1021                         push) no_complete_refspec=1 ;;
1022                         fetch)
1023                                 return
1024                                 ;;
1025                         *) ;;
1026                         esac
1027                         ;;
1028                 --multiple) no_complete_refspec=1; break ;;
1029                 -*) ;;
1030                 *) remote="$i"; break ;;
1031                 esac
1032                 ((c++))
1033         done
1034         if [ -z "$remote" ]; then
1035                 __gitcomp_nl "$(__git_remotes)"
1036                 return
1037         fi
1038         if [ $no_complete_refspec = 1 ]; then
1039                 return
1040         fi
1041         [ "$remote" = "." ] && remote=
1042         case "$cur_" in
1043         *:*)
1044                 case "$COMP_WORDBREAKS" in
1045                 *:*) : great ;;
1046                 *)   pfx="${cur_%%:*}:" ;;
1047                 esac
1048                 cur_="${cur_#*:}"
1049                 lhs=0
1050                 ;;
1051         +*)
1052                 pfx="+"
1053                 cur_="${cur_#+}"
1054                 ;;
1055         esac
1056         case "$cmd" in
1057         fetch)
1058                 if [ $lhs = 1 ]; then
1059                         __git_complete_fetch_refspecs "$remote" "$pfx" "$cur_"
1060                 else
1061                         __git_complete_refs --pfx="$pfx" --cur="$cur_"
1062                 fi
1063                 ;;
1064         pull|remote)
1065                 if [ $lhs = 1 ]; then
1066                         __git_complete_refs --remote="$remote" --pfx="$pfx" --cur="$cur_"
1067                 else
1068                         __git_complete_refs --pfx="$pfx" --cur="$cur_"
1069                 fi
1070                 ;;
1071         push)
1072                 if [ $lhs = 1 ]; then
1073                         __git_complete_refs --pfx="$pfx" --cur="$cur_"
1074                 else
1075                         __git_complete_refs --remote="$remote" --pfx="$pfx" --cur="$cur_"
1076                 fi
1077                 ;;
1078         esac
1079 }
1080
1081 __git_complete_strategy ()
1082 {
1083         __git_compute_merge_strategies
1084         case "$prev" in
1085         -s|--strategy)
1086                 __gitcomp "$__git_merge_strategies"
1087                 return 0
1088                 ;;
1089         -X)
1090                 __gitcomp "$__git_merge_strategy_options"
1091                 return 0
1092                 ;;
1093         esac
1094         case "$cur" in
1095         --strategy=*)
1096                 __gitcomp "$__git_merge_strategies" "" "${cur##--strategy=}"
1097                 return 0
1098                 ;;
1099         --strategy-option=*)
1100                 __gitcomp "$__git_merge_strategy_options" "" "${cur##--strategy-option=}"
1101                 return 0
1102                 ;;
1103         esac
1104         return 1
1105 }
1106
1107 __git_all_commands=
1108 __git_compute_all_commands ()
1109 {
1110         test -n "$__git_all_commands" ||
1111         __git_all_commands=$(__git --list-cmds=main,others,alias,nohelpers)
1112 }
1113
1114 # Lists all set config variables starting with the given section prefix,
1115 # with the prefix removed.
1116 __git_get_config_variables ()
1117 {
1118         local section="$1" i IFS=$'\n'
1119         for i in $(__git config --name-only --get-regexp "^$section\..*"); do
1120                 echo "${i#$section.}"
1121         done
1122 }
1123
1124 __git_pretty_aliases ()
1125 {
1126         __git_get_config_variables "pretty"
1127 }
1128
1129 # __git_aliased_command requires 1 argument
1130 __git_aliased_command ()
1131 {
1132         local cur=$1 last list= word cmdline
1133
1134         while [[ -n "$cur" ]]; do
1135                 if [[ "$list" == *" $cur "* ]]; then
1136                         # loop detected
1137                         return
1138                 fi
1139
1140                 cmdline=$(__git config --get "alias.$cur")
1141                 list=" $cur $list"
1142                 last=$cur
1143                 cur=
1144
1145                 for word in $cmdline; do
1146                         case "$word" in
1147                         \!gitk|gitk)
1148                                 cur="gitk"
1149                                 break
1150                                 ;;
1151                         \!*)    : shell command alias ;;
1152                         -*)     : option ;;
1153                         *=*)    : setting env ;;
1154                         git)    : git itself ;;
1155                         \(\))   : skip parens of shell function definition ;;
1156                         {)      : skip start of shell helper function ;;
1157                         :)      : skip null command ;;
1158                         \'*)    : skip opening quote after sh -c ;;
1159                         *)
1160                                 cur="$word"
1161                                 break
1162                         esac
1163                 done
1164         done
1165
1166         cur=$last
1167         if [[ "$cur" != "$1" ]]; then
1168                 echo "$cur"
1169         fi
1170 }
1171
1172 # Check whether one of the given words is present on the command line,
1173 # and print the first word found.
1174 #
1175 # Usage: __git_find_on_cmdline [<option>]... "<wordlist>"
1176 # --show-idx: Optionally show the index of the found word in the $words array.
1177 __git_find_on_cmdline ()
1178 {
1179         local word c="$__git_cmd_idx" show_idx
1180
1181         while test $# -gt 1; do
1182                 case "$1" in
1183                 --show-idx)     show_idx=y ;;
1184                 *)              return 1 ;;
1185                 esac
1186                 shift
1187         done
1188         local wordlist="$1"
1189
1190         while [ $c -lt $cword ]; do
1191                 for word in $wordlist; do
1192                         if [ "$word" = "${words[c]}" ]; then
1193                                 if [ -n "${show_idx-}" ]; then
1194                                         echo "$c $word"
1195                                 else
1196                                         echo "$word"
1197                                 fi
1198                                 return
1199                         fi
1200                 done
1201                 ((c++))
1202         done
1203 }
1204
1205 # Similar to __git_find_on_cmdline, except that it loops backwards and thus
1206 # prints the *last* word found. Useful for finding which of two options that
1207 # supersede each other came last, such as "--guess" and "--no-guess".
1208 #
1209 # Usage: __git_find_last_on_cmdline [<option>]... "<wordlist>"
1210 # --show-idx: Optionally show the index of the found word in the $words array.
1211 __git_find_last_on_cmdline ()
1212 {
1213         local word c=$cword show_idx
1214
1215         while test $# -gt 1; do
1216                 case "$1" in
1217                 --show-idx)     show_idx=y ;;
1218                 *)              return 1 ;;
1219                 esac
1220                 shift
1221         done
1222         local wordlist="$1"
1223
1224         while [ $c -gt "$__git_cmd_idx" ]; do
1225                 ((c--))
1226                 for word in $wordlist; do
1227                         if [ "$word" = "${words[c]}" ]; then
1228                                 if [ -n "$show_idx" ]; then
1229                                         echo "$c $word"
1230                                 else
1231                                         echo "$word"
1232                                 fi
1233                                 return
1234                         fi
1235                 done
1236         done
1237 }
1238
1239 # Echo the value of an option set on the command line or config
1240 #
1241 # $1: short option name
1242 # $2: long option name including =
1243 # $3: list of possible values
1244 # $4: config string (optional)
1245 #
1246 # example:
1247 # result="$(__git_get_option_value "-d" "--do-something=" \
1248 #     "yes no" "core.doSomething")"
1249 #
1250 # result is then either empty (no option set) or "yes" or "no"
1251 #
1252 # __git_get_option_value requires 3 arguments
1253 __git_get_option_value ()
1254 {
1255         local c short_opt long_opt val
1256         local result= values config_key word
1257
1258         short_opt="$1"
1259         long_opt="$2"
1260         values="$3"
1261         config_key="$4"
1262
1263         ((c = $cword - 1))
1264         while [ $c -ge 0 ]; do
1265                 word="${words[c]}"
1266                 for val in $values; do
1267                         if [ "$short_opt$val" = "$word" ] ||
1268                            [ "$long_opt$val"  = "$word" ]; then
1269                                 result="$val"
1270                                 break 2
1271                         fi
1272                 done
1273                 ((c--))
1274         done
1275
1276         if [ -n "$config_key" ] && [ -z "$result" ]; then
1277                 result="$(__git config "$config_key")"
1278         fi
1279
1280         echo "$result"
1281 }
1282
1283 __git_has_doubledash ()
1284 {
1285         local c=1
1286         while [ $c -lt $cword ]; do
1287                 if [ "--" = "${words[c]}" ]; then
1288                         return 0
1289                 fi
1290                 ((c++))
1291         done
1292         return 1
1293 }
1294
1295 # Try to count non option arguments passed on the command line for the
1296 # specified git command.
1297 # When options are used, it is necessary to use the special -- option to
1298 # tell the implementation were non option arguments begin.
1299 # XXX this can not be improved, since options can appear everywhere, as
1300 # an example:
1301 #       git mv x -n y
1302 #
1303 # __git_count_arguments requires 1 argument: the git command executed.
1304 __git_count_arguments ()
1305 {
1306         local word i c=0
1307
1308         # Skip "git" (first argument)
1309         for ((i="$__git_cmd_idx"; i < ${#words[@]}; i++)); do
1310                 word="${words[i]}"
1311
1312                 case "$word" in
1313                         --)
1314                                 # Good; we can assume that the following are only non
1315                                 # option arguments.
1316                                 ((c = 0))
1317                                 ;;
1318                         "$1")
1319                                 # Skip the specified git command and discard git
1320                                 # main options
1321                                 ((c = 0))
1322                                 ;;
1323                         ?*)
1324                                 ((c++))
1325                                 ;;
1326                 esac
1327         done
1328
1329         printf "%d" $c
1330 }
1331
1332 __git_whitespacelist="nowarn warn error error-all fix"
1333 __git_patchformat="mbox stgit stgit-series hg mboxrd"
1334 __git_showcurrentpatch="diff raw"
1335 __git_am_inprogress_options="--skip --continue --resolved --abort --quit --show-current-patch"
1336 __git_quoted_cr="nowarn warn strip"
1337
1338 _git_am ()
1339 {
1340         __git_find_repo_path
1341         if [ -d "$__git_repo_path"/rebase-apply ]; then
1342                 __gitcomp "$__git_am_inprogress_options"
1343                 return
1344         fi
1345         case "$cur" in
1346         --whitespace=*)
1347                 __gitcomp "$__git_whitespacelist" "" "${cur##--whitespace=}"
1348                 return
1349                 ;;
1350         --patch-format=*)
1351                 __gitcomp "$__git_patchformat" "" "${cur##--patch-format=}"
1352                 return
1353                 ;;
1354         --show-current-patch=*)
1355                 __gitcomp "$__git_showcurrentpatch" "" "${cur##--show-current-patch=}"
1356                 return
1357                 ;;
1358         --quoted-cr=*)
1359                 __gitcomp "$__git_quoted_cr" "" "${cur##--quoted-cr=}"
1360                 return
1361                 ;;
1362         --*)
1363                 __gitcomp_builtin am "" \
1364                         "$__git_am_inprogress_options"
1365                 return
1366         esac
1367 }
1368
1369 _git_apply ()
1370 {
1371         case "$cur" in
1372         --whitespace=*)
1373                 __gitcomp "$__git_whitespacelist" "" "${cur##--whitespace=}"
1374                 return
1375                 ;;
1376         --*)
1377                 __gitcomp_builtin apply
1378                 return
1379         esac
1380 }
1381
1382 _git_add ()
1383 {
1384         case "$cur" in
1385         --chmod=*)
1386                 __gitcomp "+x -x" "" "${cur##--chmod=}"
1387                 return
1388                 ;;
1389         --*)
1390                 __gitcomp_builtin add
1391                 return
1392         esac
1393
1394         local complete_opt="--others --modified --directory --no-empty-directory"
1395         if test -n "$(__git_find_on_cmdline "-u --update")"
1396         then
1397                 complete_opt="--modified"
1398         fi
1399         __git_complete_index_file "$complete_opt"
1400 }
1401
1402 _git_archive ()
1403 {
1404         case "$cur" in
1405         --format=*)
1406                 __gitcomp "$(git archive --list)" "" "${cur##--format=}"
1407                 return
1408                 ;;
1409         --remote=*)
1410                 __gitcomp_nl "$(__git_remotes)" "" "${cur##--remote=}"
1411                 return
1412                 ;;
1413         --*)
1414                 __gitcomp_builtin archive "--format= --list --verbose --prefix= --worktree-attributes"
1415                 return
1416                 ;;
1417         esac
1418         __git_complete_file
1419 }
1420
1421 _git_bisect ()
1422 {
1423         __git_has_doubledash && return
1424
1425         local subcommands="start bad good skip reset visualize replay log run"
1426         local subcommand="$(__git_find_on_cmdline "$subcommands")"
1427         if [ -z "$subcommand" ]; then
1428                 __git_find_repo_path
1429                 if [ -f "$__git_repo_path"/BISECT_START ]; then
1430                         __gitcomp "$subcommands"
1431                 else
1432                         __gitcomp "replay start"
1433                 fi
1434                 return
1435         fi
1436
1437         case "$subcommand" in
1438         bad|good|reset|skip|start)
1439                 __git_complete_refs
1440                 ;;
1441         *)
1442                 ;;
1443         esac
1444 }
1445
1446 __git_ref_fieldlist="refname objecttype objectsize objectname upstream push HEAD symref"
1447
1448 _git_branch ()
1449 {
1450         local i c="$__git_cmd_idx" only_local_ref="n" has_r="n"
1451
1452         while [ $c -lt $cword ]; do
1453                 i="${words[c]}"
1454                 case "$i" in
1455                 -d|-D|--delete|-m|-M|--move|-c|-C|--copy)
1456                         only_local_ref="y" ;;
1457                 -r|--remotes)
1458                         has_r="y" ;;
1459                 esac
1460                 ((c++))
1461         done
1462
1463         case "$cur" in
1464         --set-upstream-to=*)
1465                 __git_complete_refs --cur="${cur##--set-upstream-to=}"
1466                 ;;
1467         --*)
1468                 __gitcomp_builtin branch
1469                 ;;
1470         *)
1471                 if [ $only_local_ref = "y" -a $has_r = "n" ]; then
1472                         __gitcomp_direct "$(__git_heads "" "$cur" " ")"
1473                 else
1474                         __git_complete_refs
1475                 fi
1476                 ;;
1477         esac
1478 }
1479
1480 _git_bundle ()
1481 {
1482         local cmd="${words[__git_cmd_idx+1]}"
1483         case "$cword" in
1484         $((__git_cmd_idx+1)))
1485                 __gitcomp "create list-heads verify unbundle"
1486                 ;;
1487         $((__git_cmd_idx+2)))
1488                 # looking for a file
1489                 ;;
1490         *)
1491                 case "$cmd" in
1492                         create)
1493                                 __git_complete_revlist
1494                         ;;
1495                 esac
1496                 ;;
1497         esac
1498 }
1499
1500 # Helper function to decide whether or not we should enable DWIM logic for
1501 # git-switch and git-checkout.
1502 #
1503 # To decide between the following rules in decreasing priority order:
1504 # - the last provided of "--guess" or "--no-guess" explicitly enable or
1505 #   disable completion of DWIM logic respectively.
1506 # - If checkout.guess is false, disable completion of DWIM logic.
1507 # - If the --no-track option is provided, take this as a hint to disable the
1508 #   DWIM completion logic
1509 # - If GIT_COMPLETION_CHECKOUT_NO_GUESS is set, disable the DWIM completion
1510 #   logic, as requested by the user.
1511 # - Enable DWIM logic otherwise.
1512 #
1513 __git_checkout_default_dwim_mode ()
1514 {
1515         local last_option dwim_opt="--dwim"
1516
1517         if [ "${GIT_COMPLETION_CHECKOUT_NO_GUESS-}" = "1" ]; then
1518                 dwim_opt=""
1519         fi
1520
1521         # --no-track disables DWIM, but with lower priority than
1522         # --guess/--no-guess/checkout.guess
1523         if [ -n "$(__git_find_on_cmdline "--no-track")" ]; then
1524                 dwim_opt=""
1525         fi
1526
1527         # checkout.guess = false disables DWIM, but with lower priority than
1528         # --guess/--no-guess
1529         if [ "$(__git config --type=bool checkout.guess)" = "false" ]; then
1530                 dwim_opt=""
1531         fi
1532
1533         # Find the last provided --guess or --no-guess
1534         last_option="$(__git_find_last_on_cmdline "--guess --no-guess")"
1535         case "$last_option" in
1536                 --guess)
1537                         dwim_opt="--dwim"
1538                         ;;
1539                 --no-guess)
1540                         dwim_opt=""
1541                         ;;
1542         esac
1543
1544         echo "$dwim_opt"
1545 }
1546
1547 _git_checkout ()
1548 {
1549         __git_has_doubledash && return
1550
1551         local dwim_opt="$(__git_checkout_default_dwim_mode)"
1552
1553         case "$prev" in
1554         -b|-B|--orphan)
1555                 # Complete local branches (and DWIM branch
1556                 # remote branch names) for an option argument
1557                 # specifying a new branch name. This is for
1558                 # convenience, assuming new branches are
1559                 # possibly based on pre-existing branch names.
1560                 __git_complete_refs $dwim_opt --mode="heads"
1561                 return
1562                 ;;
1563         *)
1564                 ;;
1565         esac
1566
1567         case "$cur" in
1568         --conflict=*)
1569                 __gitcomp "diff3 merge" "" "${cur##--conflict=}"
1570                 ;;
1571         --*)
1572                 __gitcomp_builtin checkout
1573                 ;;
1574         *)
1575                 # At this point, we've already handled special completion for
1576                 # the arguments to -b/-B, and --orphan. There are 3 main
1577                 # things left we can possibly complete:
1578                 # 1) a start-point for -b/-B, -d/--detach, or --orphan
1579                 # 2) a remote head, for --track
1580                 # 3) an arbitrary reference, possibly including DWIM names
1581                 #
1582
1583                 if [ -n "$(__git_find_on_cmdline "-b -B -d --detach --orphan")" ]; then
1584                         __git_complete_refs --mode="refs"
1585                 elif [ -n "$(__git_find_on_cmdline "--track")" ]; then
1586                         __git_complete_refs --mode="remote-heads"
1587                 else
1588                         __git_complete_refs $dwim_opt --mode="refs"
1589                 fi
1590                 ;;
1591         esac
1592 }
1593
1594 __git_sequencer_inprogress_options="--continue --quit --abort --skip"
1595
1596 __git_cherry_pick_inprogress_options=$__git_sequencer_inprogress_options
1597
1598 _git_cherry_pick ()
1599 {
1600         __git_find_repo_path
1601         if [ -f "$__git_repo_path"/CHERRY_PICK_HEAD ]; then
1602                 __gitcomp "$__git_cherry_pick_inprogress_options"
1603                 return
1604         fi
1605
1606         __git_complete_strategy && return
1607
1608         case "$cur" in
1609         --*)
1610                 __gitcomp_builtin cherry-pick "" \
1611                         "$__git_cherry_pick_inprogress_options"
1612                 ;;
1613         *)
1614                 __git_complete_refs
1615                 ;;
1616         esac
1617 }
1618
1619 _git_clean ()
1620 {
1621         case "$cur" in
1622         --*)
1623                 __gitcomp_builtin clean
1624                 return
1625                 ;;
1626         esac
1627
1628         # XXX should we check for -x option ?
1629         __git_complete_index_file "--others --directory"
1630 }
1631
1632 _git_clone ()
1633 {
1634         case "$prev" in
1635         -c|--config)
1636                 __git_complete_config_variable_name_and_value
1637                 return
1638                 ;;
1639         esac
1640         case "$cur" in
1641         --config=*)
1642                 __git_complete_config_variable_name_and_value \
1643                         --cur="${cur##--config=}"
1644                 return
1645                 ;;
1646         --*)
1647                 __gitcomp_builtin clone
1648                 return
1649                 ;;
1650         esac
1651 }
1652
1653 __git_untracked_file_modes="all no normal"
1654
1655 _git_commit ()
1656 {
1657         case "$prev" in
1658         -c|-C)
1659                 __git_complete_refs
1660                 return
1661                 ;;
1662         esac
1663
1664         case "$cur" in
1665         --cleanup=*)
1666                 __gitcomp "default scissors strip verbatim whitespace
1667                         " "" "${cur##--cleanup=}"
1668                 return
1669                 ;;
1670         --reuse-message=*|--reedit-message=*|\
1671         --fixup=*|--squash=*)
1672                 __git_complete_refs --cur="${cur#*=}"
1673                 return
1674                 ;;
1675         --untracked-files=*)
1676                 __gitcomp "$__git_untracked_file_modes" "" "${cur##--untracked-files=}"
1677                 return
1678                 ;;
1679         --*)
1680                 __gitcomp_builtin commit
1681                 return
1682         esac
1683
1684         if __git rev-parse --verify --quiet HEAD >/dev/null; then
1685                 __git_complete_index_file "--committable"
1686         else
1687                 # This is the first commit
1688                 __git_complete_index_file "--cached"
1689         fi
1690 }
1691
1692 _git_describe ()
1693 {
1694         case "$cur" in
1695         --*)
1696                 __gitcomp_builtin describe
1697                 return
1698         esac
1699         __git_complete_refs
1700 }
1701
1702 __git_diff_algorithms="myers minimal patience histogram"
1703
1704 __git_diff_submodule_formats="diff log short"
1705
1706 __git_color_moved_opts="no default plain blocks zebra dimmed-zebra"
1707
1708 __git_color_moved_ws_opts="no ignore-space-at-eol ignore-space-change
1709                         ignore-all-space allow-indentation-change"
1710
1711 __git_diff_common_options="--stat --numstat --shortstat --summary
1712                         --patch-with-stat --name-only --name-status --color
1713                         --no-color --color-words --no-renames --check
1714                         --color-moved --color-moved= --no-color-moved
1715                         --color-moved-ws= --no-color-moved-ws
1716                         --full-index --binary --abbrev --diff-filter=
1717                         --find-copies-harder --ignore-cr-at-eol
1718                         --text --ignore-space-at-eol --ignore-space-change
1719                         --ignore-all-space --ignore-blank-lines --exit-code
1720                         --quiet --ext-diff --no-ext-diff
1721                         --no-prefix --src-prefix= --dst-prefix=
1722                         --inter-hunk-context=
1723                         --patience --histogram --minimal
1724                         --raw --word-diff --word-diff-regex=
1725                         --dirstat --dirstat= --dirstat-by-file
1726                         --dirstat-by-file= --cumulative
1727                         --diff-algorithm=
1728                         --submodule --submodule= --ignore-submodules
1729                         --indent-heuristic --no-indent-heuristic
1730                         --textconv --no-textconv
1731                         --patch --no-patch
1732 "
1733
1734 __git_diff_difftool_options="--cached --staged --pickaxe-all --pickaxe-regex
1735                         --base --ours --theirs --no-index --relative --merge-base
1736                         $__git_diff_common_options"
1737
1738 _git_diff ()
1739 {
1740         __git_has_doubledash && return
1741
1742         case "$cur" in
1743         --diff-algorithm=*)
1744                 __gitcomp "$__git_diff_algorithms" "" "${cur##--diff-algorithm=}"
1745                 return
1746                 ;;
1747         --submodule=*)
1748                 __gitcomp "$__git_diff_submodule_formats" "" "${cur##--submodule=}"
1749                 return
1750                 ;;
1751         --color-moved=*)
1752                 __gitcomp "$__git_color_moved_opts" "" "${cur##--color-moved=}"
1753                 return
1754                 ;;
1755         --color-moved-ws=*)
1756                 __gitcomp "$__git_color_moved_ws_opts" "" "${cur##--color-moved-ws=}"
1757                 return
1758                 ;;
1759         --*)
1760                 __gitcomp "$__git_diff_difftool_options"
1761                 return
1762                 ;;
1763         esac
1764         __git_complete_revlist_file
1765 }
1766
1767 __git_mergetools_common="diffuse diffmerge ecmerge emerge kdiff3 meld opendiff
1768                         tkdiff vimdiff nvimdiff gvimdiff xxdiff araxis p4merge
1769                         bc codecompare smerge
1770 "
1771
1772 _git_difftool ()
1773 {
1774         __git_has_doubledash && return
1775
1776         case "$cur" in
1777         --tool=*)
1778                 __gitcomp "$__git_mergetools_common kompare" "" "${cur##--tool=}"
1779                 return
1780                 ;;
1781         --*)
1782                 __gitcomp_builtin difftool "$__git_diff_difftool_options"
1783                 return
1784                 ;;
1785         esac
1786         __git_complete_revlist_file
1787 }
1788
1789 __git_fetch_recurse_submodules="yes on-demand no"
1790
1791 _git_fetch ()
1792 {
1793         case "$cur" in
1794         --recurse-submodules=*)
1795                 __gitcomp "$__git_fetch_recurse_submodules" "" "${cur##--recurse-submodules=}"
1796                 return
1797                 ;;
1798         --filter=*)
1799                 __gitcomp "blob:none blob:limit= sparse:oid=" "" "${cur##--filter=}"
1800                 return
1801                 ;;
1802         --*)
1803                 __gitcomp_builtin fetch
1804                 return
1805                 ;;
1806         esac
1807         __git_complete_remote_or_refspec
1808 }
1809
1810 __git_format_patch_extra_options="
1811         --full-index --not --all --no-prefix --src-prefix=
1812         --dst-prefix= --notes
1813 "
1814
1815 _git_format_patch ()
1816 {
1817         case "$cur" in
1818         --thread=*)
1819                 __gitcomp "
1820                         deep shallow
1821                         " "" "${cur##--thread=}"
1822                 return
1823                 ;;
1824         --base=*|--interdiff=*|--range-diff=*)
1825                 __git_complete_refs --cur="${cur#--*=}"
1826                 return
1827                 ;;
1828         --*)
1829                 __gitcomp_builtin format-patch "$__git_format_patch_extra_options"
1830                 return
1831                 ;;
1832         esac
1833         __git_complete_revlist
1834 }
1835
1836 _git_fsck ()
1837 {
1838         case "$cur" in
1839         --*)
1840                 __gitcomp_builtin fsck
1841                 return
1842                 ;;
1843         esac
1844 }
1845
1846 _git_gitk ()
1847 {
1848         __gitk_main
1849 }
1850
1851 # Lists matching symbol names from a tag (as in ctags) file.
1852 # 1: List symbol names matching this word.
1853 # 2: The tag file to list symbol names from.
1854 # 3: A prefix to be added to each listed symbol name (optional).
1855 # 4: A suffix to be appended to each listed symbol name (optional).
1856 __git_match_ctag () {
1857         awk -v pfx="${3-}" -v sfx="${4-}" "
1858                 /^${1//\//\\/}/ { print pfx \$1 sfx }
1859                 " "$2"
1860 }
1861
1862 # Complete symbol names from a tag file.
1863 # Usage: __git_complete_symbol [<option>]...
1864 # --tags=<file>: The tag file to list symbol names from instead of the
1865 #                default "tags".
1866 # --pfx=<prefix>: A prefix to be added to each symbol name.
1867 # --cur=<word>: The current symbol name to be completed.  Defaults to
1868 #               the current word to be completed.
1869 # --sfx=<suffix>: A suffix to be appended to each symbol name instead
1870 #                 of the default space.
1871 __git_complete_symbol () {
1872         local tags=tags pfx="" cur_="${cur-}" sfx=" "
1873
1874         while test $# != 0; do
1875                 case "$1" in
1876                 --tags=*)       tags="${1##--tags=}" ;;
1877                 --pfx=*)        pfx="${1##--pfx=}" ;;
1878                 --cur=*)        cur_="${1##--cur=}" ;;
1879                 --sfx=*)        sfx="${1##--sfx=}" ;;
1880                 *)              return 1 ;;
1881                 esac
1882                 shift
1883         done
1884
1885         if test -r "$tags"; then
1886                 __gitcomp_direct "$(__git_match_ctag "$cur_" "$tags" "$pfx" "$sfx")"
1887         fi
1888 }
1889
1890 _git_grep ()
1891 {
1892         __git_has_doubledash && return
1893
1894         case "$cur" in
1895         --*)
1896                 __gitcomp_builtin grep
1897                 return
1898                 ;;
1899         esac
1900
1901         case "$cword,$prev" in
1902         $((__git_cmd_idx+1)),*|*,-*)
1903                 __git_complete_symbol && return
1904                 ;;
1905         esac
1906
1907         __git_complete_refs
1908 }
1909
1910 _git_help ()
1911 {
1912         case "$cur" in
1913         --*)
1914                 __gitcomp_builtin help
1915                 return
1916                 ;;
1917         esac
1918         if test -n "${GIT_TESTING_ALL_COMMAND_LIST-}"
1919         then
1920                 __gitcomp "$GIT_TESTING_ALL_COMMAND_LIST $(__git --list-cmds=alias,list-guide) gitk"
1921         else
1922                 __gitcomp "$(__git --list-cmds=main,nohelpers,alias,list-guide) gitk"
1923         fi
1924 }
1925
1926 _git_init ()
1927 {
1928         case "$cur" in
1929         --shared=*)
1930                 __gitcomp "
1931                         false true umask group all world everybody
1932                         " "" "${cur##--shared=}"
1933                 return
1934                 ;;
1935         --*)
1936                 __gitcomp_builtin init
1937                 return
1938                 ;;
1939         esac
1940 }
1941
1942 _git_ls_files ()
1943 {
1944         case "$cur" in
1945         --*)
1946                 __gitcomp_builtin ls-files
1947                 return
1948                 ;;
1949         esac
1950
1951         # XXX ignore options like --modified and always suggest all cached
1952         # files.
1953         __git_complete_index_file "--cached"
1954 }
1955
1956 _git_ls_remote ()
1957 {
1958         case "$cur" in
1959         --*)
1960                 __gitcomp_builtin ls-remote
1961                 return
1962                 ;;
1963         esac
1964         __gitcomp_nl "$(__git_remotes)"
1965 }
1966
1967 _git_ls_tree ()
1968 {
1969         case "$cur" in
1970         --*)
1971                 __gitcomp_builtin ls-tree
1972                 return
1973                 ;;
1974         esac
1975
1976         __git_complete_file
1977 }
1978
1979 # Options that go well for log, shortlog and gitk
1980 __git_log_common_options="
1981         --not --all
1982         --branches --tags --remotes
1983         --first-parent --merges --no-merges
1984         --max-count=
1985         --max-age= --since= --after=
1986         --min-age= --until= --before=
1987         --min-parents= --max-parents=
1988         --no-min-parents --no-max-parents
1989 "
1990 # Options that go well for log and gitk (not shortlog)
1991 __git_log_gitk_options="
1992         --dense --sparse --full-history
1993         --simplify-merges --simplify-by-decoration
1994         --left-right --notes --no-notes
1995 "
1996 # Options that go well for log and shortlog (not gitk)
1997 __git_log_shortlog_options="
1998         --author= --committer= --grep=
1999         --all-match --invert-grep
2000 "
2001
2002 __git_log_pretty_formats="oneline short medium full fuller reference email raw format: tformat: mboxrd"
2003 __git_log_date_formats="relative iso8601 iso8601-strict rfc2822 short local default raw unix format:"
2004
2005 _git_log ()
2006 {
2007         __git_has_doubledash && return
2008         __git_find_repo_path
2009
2010         local merge=""
2011         if [ -f "$__git_repo_path/MERGE_HEAD" ]; then
2012                 merge="--merge"
2013         fi
2014         case "$prev,$cur" in
2015         -L,:*:*)
2016                 return  # fall back to Bash filename completion
2017                 ;;
2018         -L,:*)
2019                 __git_complete_symbol --cur="${cur#:}" --sfx=":"
2020                 return
2021                 ;;
2022         -G,*|-S,*)
2023                 __git_complete_symbol
2024                 return
2025                 ;;
2026         esac
2027         case "$cur" in
2028         --pretty=*|--format=*)
2029                 __gitcomp "$__git_log_pretty_formats $(__git_pretty_aliases)
2030                         " "" "${cur#*=}"
2031                 return
2032                 ;;
2033         --date=*)
2034                 __gitcomp "$__git_log_date_formats" "" "${cur##--date=}"
2035                 return
2036                 ;;
2037         --decorate=*)
2038                 __gitcomp "full short no" "" "${cur##--decorate=}"
2039                 return
2040                 ;;
2041         --diff-algorithm=*)
2042                 __gitcomp "$__git_diff_algorithms" "" "${cur##--diff-algorithm=}"
2043                 return
2044                 ;;
2045         --submodule=*)
2046                 __gitcomp "$__git_diff_submodule_formats" "" "${cur##--submodule=}"
2047                 return
2048                 ;;
2049         --no-walk=*)
2050                 __gitcomp "sorted unsorted" "" "${cur##--no-walk=}"
2051                 return
2052                 ;;
2053         --*)
2054                 __gitcomp "
2055                         $__git_log_common_options
2056                         $__git_log_shortlog_options
2057                         $__git_log_gitk_options
2058                         --root --topo-order --date-order --reverse
2059                         --follow --full-diff
2060                         --abbrev-commit --no-abbrev-commit --abbrev=
2061                         --relative-date --date=
2062                         --pretty= --format= --oneline
2063                         --show-signature
2064                         --cherry-mark
2065                         --cherry-pick
2066                         --graph
2067                         --decorate --decorate= --no-decorate
2068                         --walk-reflogs
2069                         --no-walk --no-walk= --do-walk
2070                         --parents --children
2071                         --expand-tabs --expand-tabs= --no-expand-tabs
2072                         $merge
2073                         $__git_diff_common_options
2074                         --pickaxe-all --pickaxe-regex
2075                         "
2076                 return
2077                 ;;
2078         -L:*:*)
2079                 return  # fall back to Bash filename completion
2080                 ;;
2081         -L:*)
2082                 __git_complete_symbol --cur="${cur#-L:}" --sfx=":"
2083                 return
2084                 ;;
2085         -G*)
2086                 __git_complete_symbol --pfx="-G" --cur="${cur#-G}"
2087                 return
2088                 ;;
2089         -S*)
2090                 __git_complete_symbol --pfx="-S" --cur="${cur#-S}"
2091                 return
2092                 ;;
2093         esac
2094         __git_complete_revlist
2095 }
2096
2097 _git_merge ()
2098 {
2099         __git_complete_strategy && return
2100
2101         case "$cur" in
2102         --*)
2103                 __gitcomp_builtin merge
2104                 return
2105         esac
2106         __git_complete_refs
2107 }
2108
2109 _git_mergetool ()
2110 {
2111         case "$cur" in
2112         --tool=*)
2113                 __gitcomp "$__git_mergetools_common tortoisemerge" "" "${cur##--tool=}"
2114                 return
2115                 ;;
2116         --*)
2117                 __gitcomp "--tool= --prompt --no-prompt --gui --no-gui"
2118                 return
2119                 ;;
2120         esac
2121 }
2122
2123 _git_merge_base ()
2124 {
2125         case "$cur" in
2126         --*)
2127                 __gitcomp_builtin merge-base
2128                 return
2129                 ;;
2130         esac
2131         __git_complete_refs
2132 }
2133
2134 _git_mv ()
2135 {
2136         case "$cur" in
2137         --*)
2138                 __gitcomp_builtin mv
2139                 return
2140                 ;;
2141         esac
2142
2143         if [ $(__git_count_arguments "mv") -gt 0 ]; then
2144                 # We need to show both cached and untracked files (including
2145                 # empty directories) since this may not be the last argument.
2146                 __git_complete_index_file "--cached --others --directory"
2147         else
2148                 __git_complete_index_file "--cached"
2149         fi
2150 }
2151
2152 _git_notes ()
2153 {
2154         local subcommands='add append copy edit get-ref list merge prune remove show'
2155         local subcommand="$(__git_find_on_cmdline "$subcommands")"
2156
2157         case "$subcommand,$cur" in
2158         ,--*)
2159                 __gitcomp_builtin notes
2160                 ;;
2161         ,*)
2162                 case "$prev" in
2163                 --ref)
2164                         __git_complete_refs
2165                         ;;
2166                 *)
2167                         __gitcomp "$subcommands --ref"
2168                         ;;
2169                 esac
2170                 ;;
2171         *,--reuse-message=*|*,--reedit-message=*)
2172                 __git_complete_refs --cur="${cur#*=}"
2173                 ;;
2174         *,--*)
2175                 __gitcomp_builtin notes_$subcommand
2176                 ;;
2177         prune,*|get-ref,*)
2178                 # this command does not take a ref, do not complete it
2179                 ;;
2180         *)
2181                 case "$prev" in
2182                 -m|-F)
2183                         ;;
2184                 *)
2185                         __git_complete_refs
2186                         ;;
2187                 esac
2188                 ;;
2189         esac
2190 }
2191
2192 _git_pull ()
2193 {
2194         __git_complete_strategy && return
2195
2196         case "$cur" in
2197         --recurse-submodules=*)
2198                 __gitcomp "$__git_fetch_recurse_submodules" "" "${cur##--recurse-submodules=}"
2199                 return
2200                 ;;
2201         --*)
2202                 __gitcomp_builtin pull
2203
2204                 return
2205                 ;;
2206         esac
2207         __git_complete_remote_or_refspec
2208 }
2209
2210 __git_push_recurse_submodules="check on-demand only"
2211
2212 __git_complete_force_with_lease ()
2213 {
2214         local cur_=$1
2215
2216         case "$cur_" in
2217         --*=)
2218                 ;;
2219         *:*)
2220                 __git_complete_refs --cur="${cur_#*:}"
2221                 ;;
2222         *)
2223                 __git_complete_refs --cur="$cur_"
2224                 ;;
2225         esac
2226 }
2227
2228 _git_push ()
2229 {
2230         case "$prev" in
2231         --repo)
2232                 __gitcomp_nl "$(__git_remotes)"
2233                 return
2234                 ;;
2235         --recurse-submodules)
2236                 __gitcomp "$__git_push_recurse_submodules"
2237                 return
2238                 ;;
2239         esac
2240         case "$cur" in
2241         --repo=*)
2242                 __gitcomp_nl "$(__git_remotes)" "" "${cur##--repo=}"
2243                 return
2244                 ;;
2245         --recurse-submodules=*)
2246                 __gitcomp "$__git_push_recurse_submodules" "" "${cur##--recurse-submodules=}"
2247                 return
2248                 ;;
2249         --force-with-lease=*)
2250                 __git_complete_force_with_lease "${cur##--force-with-lease=}"
2251                 return
2252                 ;;
2253         --*)
2254                 __gitcomp_builtin push
2255                 return
2256                 ;;
2257         esac
2258         __git_complete_remote_or_refspec
2259 }
2260
2261 _git_range_diff ()
2262 {
2263         case "$cur" in
2264         --*)
2265                 __gitcomp "
2266                         --creation-factor= --no-dual-color
2267                         $__git_diff_common_options
2268                 "
2269                 return
2270                 ;;
2271         esac
2272         __git_complete_revlist
2273 }
2274
2275 __git_rebase_inprogress_options="--continue --skip --abort --quit --show-current-patch"
2276 __git_rebase_interactive_inprogress_options="$__git_rebase_inprogress_options --edit-todo"
2277
2278 _git_rebase ()
2279 {
2280         __git_find_repo_path
2281         if [ -f "$__git_repo_path"/rebase-merge/interactive ]; then
2282                 __gitcomp "$__git_rebase_interactive_inprogress_options"
2283                 return
2284         elif [ -d "$__git_repo_path"/rebase-apply ] || \
2285              [ -d "$__git_repo_path"/rebase-merge ]; then
2286                 __gitcomp "$__git_rebase_inprogress_options"
2287                 return
2288         fi
2289         __git_complete_strategy && return
2290         case "$cur" in
2291         --whitespace=*)
2292                 __gitcomp "$__git_whitespacelist" "" "${cur##--whitespace=}"
2293                 return
2294                 ;;
2295         --onto=*)
2296                 __git_complete_refs --cur="${cur##--onto=}"
2297                 return
2298                 ;;
2299         --*)
2300                 __gitcomp_builtin rebase "" \
2301                         "$__git_rebase_interactive_inprogress_options"
2302
2303                 return
2304         esac
2305         __git_complete_refs
2306 }
2307
2308 _git_reflog ()
2309 {
2310         local subcommands="show delete expire"
2311         local subcommand="$(__git_find_on_cmdline "$subcommands")"
2312
2313         if [ -z "$subcommand" ]; then
2314                 __gitcomp "$subcommands"
2315         else
2316                 __git_complete_refs
2317         fi
2318 }
2319
2320 __git_send_email_confirm_options="always never auto cc compose"
2321 __git_send_email_suppresscc_options="author self cc bodycc sob cccmd body all"
2322
2323 _git_send_email ()
2324 {
2325         case "$prev" in
2326         --to|--cc|--bcc|--from)
2327                 __gitcomp "$(__git send-email --dump-aliases)"
2328                 return
2329                 ;;
2330         esac
2331
2332         case "$cur" in
2333         --confirm=*)
2334                 __gitcomp "
2335                         $__git_send_email_confirm_options
2336                         " "" "${cur##--confirm=}"
2337                 return
2338                 ;;
2339         --suppress-cc=*)
2340                 __gitcomp "
2341                         $__git_send_email_suppresscc_options
2342                         " "" "${cur##--suppress-cc=}"
2343
2344                 return
2345                 ;;
2346         --smtp-encryption=*)
2347                 __gitcomp "ssl tls" "" "${cur##--smtp-encryption=}"
2348                 return
2349                 ;;
2350         --thread=*)
2351                 __gitcomp "
2352                         deep shallow
2353                         " "" "${cur##--thread=}"
2354                 return
2355                 ;;
2356         --to=*|--cc=*|--bcc=*|--from=*)
2357                 __gitcomp "$(__git send-email --dump-aliases)" "" "${cur#--*=}"
2358                 return
2359                 ;;
2360         --*)
2361                 __gitcomp_builtin send-email "--annotate --bcc --cc --cc-cmd --chain-reply-to
2362                         --compose --confirm= --dry-run --envelope-sender
2363                         --from --identity
2364                         --in-reply-to --no-chain-reply-to --no-signed-off-by-cc
2365                         --no-suppress-from --no-thread --quiet --reply-to
2366                         --signed-off-by-cc --smtp-pass --smtp-server
2367                         --smtp-server-port --smtp-encryption= --smtp-user
2368                         --subject --suppress-cc= --suppress-from --thread --to
2369                         --validate --no-validate
2370                         $__git_format_patch_extra_options"
2371                 return
2372                 ;;
2373         esac
2374         __git_complete_revlist
2375 }
2376
2377 _git_stage ()
2378 {
2379         _git_add
2380 }
2381
2382 _git_status ()
2383 {
2384         local complete_opt
2385         local untracked_state
2386
2387         case "$cur" in
2388         --ignore-submodules=*)
2389                 __gitcomp "none untracked dirty all" "" "${cur##--ignore-submodules=}"
2390                 return
2391                 ;;
2392         --untracked-files=*)
2393                 __gitcomp "$__git_untracked_file_modes" "" "${cur##--untracked-files=}"
2394                 return
2395                 ;;
2396         --column=*)
2397                 __gitcomp "
2398                         always never auto column row plain dense nodense
2399                         " "" "${cur##--column=}"
2400                 return
2401                 ;;
2402         --*)
2403                 __gitcomp_builtin status
2404                 return
2405                 ;;
2406         esac
2407
2408         untracked_state="$(__git_get_option_value "-u" "--untracked-files=" \
2409                 "$__git_untracked_file_modes" "status.showUntrackedFiles")"
2410
2411         case "$untracked_state" in
2412         no)
2413                 # --ignored option does not matter
2414                 complete_opt=
2415                 ;;
2416         all|normal|*)
2417                 complete_opt="--cached --directory --no-empty-directory --others"
2418
2419                 if [ -n "$(__git_find_on_cmdline "--ignored")" ]; then
2420                         complete_opt="$complete_opt --ignored --exclude=*"
2421                 fi
2422                 ;;
2423         esac
2424
2425         __git_complete_index_file "$complete_opt"
2426 }
2427
2428 _git_switch ()
2429 {
2430         local dwim_opt="$(__git_checkout_default_dwim_mode)"
2431
2432         case "$prev" in
2433         -c|-C|--orphan)
2434                 # Complete local branches (and DWIM branch
2435                 # remote branch names) for an option argument
2436                 # specifying a new branch name. This is for
2437                 # convenience, assuming new branches are
2438                 # possibly based on pre-existing branch names.
2439                 __git_complete_refs $dwim_opt --mode="heads"
2440                 return
2441                 ;;
2442         *)
2443                 ;;
2444         esac
2445
2446         case "$cur" in
2447         --conflict=*)
2448                 __gitcomp "diff3 merge" "" "${cur##--conflict=}"
2449                 ;;
2450         --*)
2451                 __gitcomp_builtin switch
2452                 ;;
2453         *)
2454                 # Unlike in git checkout, git switch --orphan does not take
2455                 # a start point. Thus we really have nothing to complete after
2456                 # the branch name.
2457                 if [ -n "$(__git_find_on_cmdline "--orphan")" ]; then
2458                         return
2459                 fi
2460
2461                 # At this point, we've already handled special completion for
2462                 # -c/-C, and --orphan. There are 3 main things left to
2463                 # complete:
2464                 # 1) a start-point for -c/-C or -d/--detach
2465                 # 2) a remote head, for --track
2466                 # 3) a branch name, possibly including DWIM remote branches
2467
2468                 if [ -n "$(__git_find_on_cmdline "-c -C -d --detach")" ]; then
2469                         __git_complete_refs --mode="refs"
2470                 elif [ -n "$(__git_find_on_cmdline "--track")" ]; then
2471                         __git_complete_refs --mode="remote-heads"
2472                 else
2473                         __git_complete_refs $dwim_opt --mode="heads"
2474                 fi
2475                 ;;
2476         esac
2477 }
2478
2479 __git_config_get_set_variables ()
2480 {
2481         local prevword word config_file= c=$cword
2482         while [ $c -gt "$__git_cmd_idx" ]; do
2483                 word="${words[c]}"
2484                 case "$word" in
2485                 --system|--global|--local|--file=*)
2486                         config_file="$word"
2487                         break
2488                         ;;
2489                 -f|--file)
2490                         config_file="$word $prevword"
2491                         break
2492                         ;;
2493                 esac
2494                 prevword=$word
2495                 c=$((--c))
2496         done
2497
2498         __git config $config_file --name-only --list
2499 }
2500
2501 __git_config_vars=
2502 __git_compute_config_vars ()
2503 {
2504         test -n "$__git_config_vars" ||
2505         __git_config_vars="$(git help --config-for-completion | sort -u)"
2506 }
2507
2508 # Completes possible values of various configuration variables.
2509 #
2510 # Usage: __git_complete_config_variable_value [<option>]...
2511 # --varname=<word>: The name of the configuration variable whose value is
2512 #                   to be completed.  Defaults to the previous word on the
2513 #                   command line.
2514 # --cur=<word>: The current value to be completed.  Defaults to the current
2515 #               word to be completed.
2516 __git_complete_config_variable_value ()
2517 {
2518         local varname="$prev" cur_="$cur"
2519
2520         while test $# != 0; do
2521                 case "$1" in
2522                 --varname=*)    varname="${1##--varname=}" ;;
2523                 --cur=*)        cur_="${1##--cur=}" ;;
2524                 *)              return 1 ;;
2525                 esac
2526                 shift
2527         done
2528
2529         if [ "${BASH_VERSINFO[0]:-0}" -ge 4 ]; then
2530                 varname="${varname,,}"
2531         else
2532                 varname="$(echo "$varname" |tr A-Z a-z)"
2533         fi
2534
2535         case "$varname" in
2536         branch.*.remote|branch.*.pushremote)
2537                 __gitcomp_nl "$(__git_remotes)" "" "$cur_"
2538                 return
2539                 ;;
2540         branch.*.merge)
2541                 __git_complete_refs --cur="$cur_"
2542                 return
2543                 ;;
2544         branch.*.rebase)
2545                 __gitcomp "false true merges preserve interactive" "" "$cur_"
2546                 return
2547                 ;;
2548         remote.pushdefault)
2549                 __gitcomp_nl "$(__git_remotes)" "" "$cur_"
2550                 return
2551                 ;;
2552         remote.*.fetch)
2553                 local remote="${varname#remote.}"
2554                 remote="${remote%.fetch}"
2555                 if [ -z "$cur_" ]; then
2556                         __gitcomp_nl "refs/heads/" "" "" ""
2557                         return
2558                 fi
2559                 __gitcomp_nl "$(__git_refs_remotes "$remote")" "" "$cur_"
2560                 return
2561                 ;;
2562         remote.*.push)
2563                 local remote="${varname#remote.}"
2564                 remote="${remote%.push}"
2565                 __gitcomp_nl "$(__git for-each-ref \
2566                         --format='%(refname):%(refname)' refs/heads)" "" "$cur_"
2567                 return
2568                 ;;
2569         pull.twohead|pull.octopus)
2570                 __git_compute_merge_strategies
2571                 __gitcomp "$__git_merge_strategies" "" "$cur_"
2572                 return
2573                 ;;
2574         color.pager)
2575                 __gitcomp "false true" "" "$cur_"
2576                 return
2577                 ;;
2578         color.*.*)
2579                 __gitcomp "
2580                         normal black red green yellow blue magenta cyan white
2581                         bold dim ul blink reverse
2582                         " "" "$cur_"
2583                 return
2584                 ;;
2585         color.*)
2586                 __gitcomp "false true always never auto" "" "$cur_"
2587                 return
2588                 ;;
2589         diff.submodule)
2590                 __gitcomp "$__git_diff_submodule_formats" "" "$cur_"
2591                 return
2592                 ;;
2593         help.format)
2594                 __gitcomp "man info web html" "" "$cur_"
2595                 return
2596                 ;;
2597         log.date)
2598                 __gitcomp "$__git_log_date_formats" "" "$cur_"
2599                 return
2600                 ;;
2601         sendemail.aliasfiletype)
2602                 __gitcomp "mutt mailrc pine elm gnus" "" "$cur_"
2603                 return
2604                 ;;
2605         sendemail.confirm)
2606                 __gitcomp "$__git_send_email_confirm_options" "" "$cur_"
2607                 return
2608                 ;;
2609         sendemail.suppresscc)
2610                 __gitcomp "$__git_send_email_suppresscc_options" "" "$cur_"
2611                 return
2612                 ;;
2613         sendemail.transferencoding)
2614                 __gitcomp "7bit 8bit quoted-printable base64" "" "$cur_"
2615                 return
2616                 ;;
2617         *.*)
2618                 return
2619                 ;;
2620         esac
2621 }
2622
2623 # Completes configuration sections, subsections, variable names.
2624 #
2625 # Usage: __git_complete_config_variable_name [<option>]...
2626 # --cur=<word>: The current configuration section/variable name to be
2627 #               completed.  Defaults to the current word to be completed.
2628 # --sfx=<suffix>: A suffix to be appended to each fully completed
2629 #                 configuration variable name (but not to sections or
2630 #                 subsections) instead of the default space.
2631 __git_complete_config_variable_name ()
2632 {
2633         local cur_="$cur" sfx
2634
2635         while test $# != 0; do
2636                 case "$1" in
2637                 --cur=*)        cur_="${1##--cur=}" ;;
2638                 --sfx=*)        sfx="${1##--sfx=}" ;;
2639                 *)              return 1 ;;
2640                 esac
2641                 shift
2642         done
2643
2644         case "$cur_" in
2645         branch.*.*)
2646                 local pfx="${cur_%.*}."
2647                 cur_="${cur_##*.}"
2648                 __gitcomp "remote pushRemote merge mergeOptions rebase" "$pfx" "$cur_" "$sfx"
2649                 return
2650                 ;;
2651         branch.*)
2652                 local pfx="${cur%.*}."
2653                 cur_="${cur#*.}"
2654                 __gitcomp_direct "$(__git_heads "$pfx" "$cur_" ".")"
2655                 __gitcomp_nl_append $'autoSetupMerge\nautoSetupRebase\n' "$pfx" "$cur_" "$sfx"
2656                 return
2657                 ;;
2658         guitool.*.*)
2659                 local pfx="${cur_%.*}."
2660                 cur_="${cur_##*.}"
2661                 __gitcomp "
2662                         argPrompt cmd confirm needsFile noConsole noRescan
2663                         prompt revPrompt revUnmerged title
2664                         " "$pfx" "$cur_" "$sfx"
2665                 return
2666                 ;;
2667         difftool.*.*)
2668                 local pfx="${cur_%.*}."
2669                 cur_="${cur_##*.}"
2670                 __gitcomp "cmd path" "$pfx" "$cur_" "$sfx"
2671                 return
2672                 ;;
2673         man.*.*)
2674                 local pfx="${cur_%.*}."
2675                 cur_="${cur_##*.}"
2676                 __gitcomp "cmd path" "$pfx" "$cur_" "$sfx"
2677                 return
2678                 ;;
2679         mergetool.*.*)
2680                 local pfx="${cur_%.*}."
2681                 cur_="${cur_##*.}"
2682                 __gitcomp "cmd path trustExitCode" "$pfx" "$cur_" "$sfx"
2683                 return
2684                 ;;
2685         pager.*)
2686                 local pfx="${cur_%.*}."
2687                 cur_="${cur_#*.}"
2688                 __git_compute_all_commands
2689                 __gitcomp_nl "$__git_all_commands" "$pfx" "$cur_" "$sfx"
2690                 return
2691                 ;;
2692         remote.*.*)
2693                 local pfx="${cur_%.*}."
2694                 cur_="${cur_##*.}"
2695                 __gitcomp "
2696                         url proxy fetch push mirror skipDefaultUpdate
2697                         receivepack uploadpack tagOpt pushurl
2698                         " "$pfx" "$cur_" "$sfx"
2699                 return
2700                 ;;
2701         remote.*)
2702                 local pfx="${cur_%.*}."
2703                 cur_="${cur_#*.}"
2704                 __gitcomp_nl "$(__git_remotes)" "$pfx" "$cur_" "."
2705                 __gitcomp_nl_append "pushDefault" "$pfx" "$cur_" "$sfx"
2706                 return
2707                 ;;
2708         url.*.*)
2709                 local pfx="${cur_%.*}."
2710                 cur_="${cur_##*.}"
2711                 __gitcomp "insteadOf pushInsteadOf" "$pfx" "$cur_" "$sfx"
2712                 return
2713                 ;;
2714         *.*)
2715                 __git_compute_config_vars
2716                 __gitcomp "$__git_config_vars" "" "$cur_" "$sfx"
2717                 ;;
2718         *)
2719                 __git_compute_config_vars
2720                 __gitcomp "$(echo "$__git_config_vars" |
2721                                 awk -F . '{
2722                                         sections[$1] = 1
2723                                 }
2724                                 END {
2725                                         for (s in sections)
2726                                                 print s "."
2727                                 }
2728                                 ')" "" "$cur_"
2729                 ;;
2730         esac
2731 }
2732
2733 # Completes '='-separated configuration sections/variable names and values
2734 # for 'git -c section.name=value'.
2735 #
2736 # Usage: __git_complete_config_variable_name_and_value [<option>]...
2737 # --cur=<word>: The current configuration section/variable name/value to be
2738 #               completed. Defaults to the current word to be completed.
2739 __git_complete_config_variable_name_and_value ()
2740 {
2741         local cur_="$cur"
2742
2743         while test $# != 0; do
2744                 case "$1" in
2745                 --cur=*)        cur_="${1##--cur=}" ;;
2746                 *)              return 1 ;;
2747                 esac
2748                 shift
2749         done
2750
2751         case "$cur_" in
2752         *=*)
2753                 __git_complete_config_variable_value \
2754                         --varname="${cur_%%=*}" --cur="${cur_#*=}"
2755                 ;;
2756         *)
2757                 __git_complete_config_variable_name --cur="$cur_" --sfx='='
2758                 ;;
2759         esac
2760 }
2761
2762 _git_config ()
2763 {
2764         case "$prev" in
2765         --get|--get-all|--unset|--unset-all)
2766                 __gitcomp_nl "$(__git_config_get_set_variables)"
2767                 return
2768                 ;;
2769         *.*)
2770                 __git_complete_config_variable_value
2771                 return
2772                 ;;
2773         esac
2774         case "$cur" in
2775         --*)
2776                 __gitcomp_builtin config
2777                 ;;
2778         *)
2779                 __git_complete_config_variable_name
2780                 ;;
2781         esac
2782 }
2783
2784 _git_remote ()
2785 {
2786         local subcommands="
2787                 add rename remove set-head set-branches
2788                 get-url set-url show prune update
2789                 "
2790         local subcommand="$(__git_find_on_cmdline "$subcommands")"
2791         if [ -z "$subcommand" ]; then
2792                 case "$cur" in
2793                 --*)
2794                         __gitcomp_builtin remote
2795                         ;;
2796                 *)
2797                         __gitcomp "$subcommands"
2798                         ;;
2799                 esac
2800                 return
2801         fi
2802
2803         case "$subcommand,$cur" in
2804         add,--*)
2805                 __gitcomp_builtin remote_add
2806                 ;;
2807         add,*)
2808                 ;;
2809         set-head,--*)
2810                 __gitcomp_builtin remote_set-head
2811                 ;;
2812         set-branches,--*)
2813                 __gitcomp_builtin remote_set-branches
2814                 ;;
2815         set-head,*|set-branches,*)
2816                 __git_complete_remote_or_refspec
2817                 ;;
2818         update,--*)
2819                 __gitcomp_builtin remote_update
2820                 ;;
2821         update,*)
2822                 __gitcomp "$(__git_remotes) $(__git_get_config_variables "remotes")"
2823                 ;;
2824         set-url,--*)
2825                 __gitcomp_builtin remote_set-url
2826                 ;;
2827         get-url,--*)
2828                 __gitcomp_builtin remote_get-url
2829                 ;;
2830         prune,--*)
2831                 __gitcomp_builtin remote_prune
2832                 ;;
2833         *)
2834                 __gitcomp_nl "$(__git_remotes)"
2835                 ;;
2836         esac
2837 }
2838
2839 _git_replace ()
2840 {
2841         case "$cur" in
2842         --format=*)
2843                 __gitcomp "short medium long" "" "${cur##--format=}"
2844                 return
2845                 ;;
2846         --*)
2847                 __gitcomp_builtin replace
2848                 return
2849                 ;;
2850         esac
2851         __git_complete_refs
2852 }
2853
2854 _git_rerere ()
2855 {
2856         local subcommands="clear forget diff remaining status gc"
2857         local subcommand="$(__git_find_on_cmdline "$subcommands")"
2858         if test -z "$subcommand"
2859         then
2860                 __gitcomp "$subcommands"
2861                 return
2862         fi
2863 }
2864
2865 _git_reset ()
2866 {
2867         __git_has_doubledash && return
2868
2869         case "$cur" in
2870         --*)
2871                 __gitcomp_builtin reset
2872                 return
2873                 ;;
2874         esac
2875         __git_complete_refs
2876 }
2877
2878 _git_restore ()
2879 {
2880         case "$prev" in
2881         -s)
2882                 __git_complete_refs
2883                 return
2884                 ;;
2885         esac
2886
2887         case "$cur" in
2888         --conflict=*)
2889                 __gitcomp "diff3 merge" "" "${cur##--conflict=}"
2890                 ;;
2891         --source=*)
2892                 __git_complete_refs --cur="${cur##--source=}"
2893                 ;;
2894         --*)
2895                 __gitcomp_builtin restore
2896                 ;;
2897         esac
2898 }
2899
2900 __git_revert_inprogress_options=$__git_sequencer_inprogress_options
2901
2902 _git_revert ()
2903 {
2904         __git_find_repo_path
2905         if [ -f "$__git_repo_path"/REVERT_HEAD ]; then
2906                 __gitcomp "$__git_revert_inprogress_options"
2907                 return
2908         fi
2909         __git_complete_strategy && return
2910         case "$cur" in
2911         --*)
2912                 __gitcomp_builtin revert "" \
2913                         "$__git_revert_inprogress_options"
2914                 return
2915                 ;;
2916         esac
2917         __git_complete_refs
2918 }
2919
2920 _git_rm ()
2921 {
2922         case "$cur" in
2923         --*)
2924                 __gitcomp_builtin rm
2925                 return
2926                 ;;
2927         esac
2928
2929         __git_complete_index_file "--cached"
2930 }
2931
2932 _git_shortlog ()
2933 {
2934         __git_has_doubledash && return
2935
2936         case "$cur" in
2937         --*)
2938                 __gitcomp "
2939                         $__git_log_common_options
2940                         $__git_log_shortlog_options
2941                         --numbered --summary --email
2942                         "
2943                 return
2944                 ;;
2945         esac
2946         __git_complete_revlist
2947 }
2948
2949 _git_show ()
2950 {
2951         __git_has_doubledash && return
2952
2953         case "$cur" in
2954         --pretty=*|--format=*)
2955                 __gitcomp "$__git_log_pretty_formats $(__git_pretty_aliases)
2956                         " "" "${cur#*=}"
2957                 return
2958                 ;;
2959         --diff-algorithm=*)
2960                 __gitcomp "$__git_diff_algorithms" "" "${cur##--diff-algorithm=}"
2961                 return
2962                 ;;
2963         --submodule=*)
2964                 __gitcomp "$__git_diff_submodule_formats" "" "${cur##--submodule=}"
2965                 return
2966                 ;;
2967         --color-moved=*)
2968                 __gitcomp "$__git_color_moved_opts" "" "${cur##--color-moved=}"
2969                 return
2970                 ;;
2971         --color-moved-ws=*)
2972                 __gitcomp "$__git_color_moved_ws_opts" "" "${cur##--color-moved-ws=}"
2973                 return
2974                 ;;
2975         --*)
2976                 __gitcomp "--pretty= --format= --abbrev-commit --no-abbrev-commit
2977                         --oneline --show-signature
2978                         --expand-tabs --expand-tabs= --no-expand-tabs
2979                         $__git_diff_common_options
2980                         "
2981                 return
2982                 ;;
2983         esac
2984         __git_complete_revlist_file
2985 }
2986
2987 _git_show_branch ()
2988 {
2989         case "$cur" in
2990         --*)
2991                 __gitcomp_builtin show-branch
2992                 return
2993                 ;;
2994         esac
2995         __git_complete_revlist
2996 }
2997
2998 _git_sparse_checkout ()
2999 {
3000         local subcommands="list init set disable"
3001         local subcommand="$(__git_find_on_cmdline "$subcommands")"
3002         if [ -z "$subcommand" ]; then
3003                 __gitcomp "$subcommands"
3004                 return
3005         fi
3006
3007         case "$subcommand,$cur" in
3008         init,--*)
3009                 __gitcomp "--cone"
3010                 ;;
3011         set,--*)
3012                 __gitcomp "--stdin"
3013                 ;;
3014         *)
3015                 ;;
3016         esac
3017 }
3018
3019 _git_stash ()
3020 {
3021         local subcommands='push list show apply clear drop pop create branch'
3022         local subcommand="$(__git_find_on_cmdline "$subcommands save")"
3023
3024         if [ -z "$subcommand" ]; then
3025                 case "$((cword - __git_cmd_idx)),$cur" in
3026                 *,--*)
3027                         __gitcomp_builtin stash_push
3028                         ;;
3029                 1,sa*)
3030                         __gitcomp "save"
3031                         ;;
3032                 1,*)
3033                         __gitcomp "$subcommands"
3034                         ;;
3035                 esac
3036                 return
3037         fi
3038
3039         case "$subcommand,$cur" in
3040         list,--*)
3041                 # NEEDSWORK: can we somehow unify this with the options in _git_log() and _git_show()
3042                 __gitcomp_builtin stash_list "$__git_log_common_options $__git_diff_common_options"
3043                 ;;
3044         show,--*)
3045                 __gitcomp_builtin stash_show "$__git_diff_common_options"
3046                 ;;
3047         *,--*)
3048                 __gitcomp_builtin "stash_$subcommand"
3049                 ;;
3050         branch,*)
3051                 if [ $cword -eq $((__git_cmd_idx+2)) ]; then
3052                         __git_complete_refs
3053                 else
3054                         __gitcomp_nl "$(__git stash list \
3055                                         | sed -n -e 's/:.*//p')"
3056                 fi
3057                 ;;
3058         show,*|apply,*|drop,*|pop,*)
3059                 __gitcomp_nl "$(__git stash list \
3060                                 | sed -n -e 's/:.*//p')"
3061                 ;;
3062         esac
3063 }
3064
3065 _git_submodule ()
3066 {
3067         __git_has_doubledash && return
3068
3069         local subcommands="add status init deinit update set-branch set-url summary foreach sync absorbgitdirs"
3070         local subcommand="$(__git_find_on_cmdline "$subcommands")"
3071         if [ -z "$subcommand" ]; then
3072                 case "$cur" in
3073                 --*)
3074                         __gitcomp "--quiet"
3075                         ;;
3076                 *)
3077                         __gitcomp "$subcommands"
3078                         ;;
3079                 esac
3080                 return
3081         fi
3082
3083         case "$subcommand,$cur" in
3084         add,--*)
3085                 __gitcomp "--branch --force --name --reference --depth"
3086                 ;;
3087         status,--*)
3088                 __gitcomp "--cached --recursive"
3089                 ;;
3090         deinit,--*)
3091                 __gitcomp "--force --all"
3092                 ;;
3093         update,--*)
3094                 __gitcomp "
3095                         --init --remote --no-fetch
3096                         --recommend-shallow --no-recommend-shallow
3097                         --force --rebase --merge --reference --depth --recursive --jobs
3098                 "
3099                 ;;
3100         set-branch,--*)
3101                 __gitcomp "--default --branch"
3102                 ;;
3103         summary,--*)
3104                 __gitcomp "--cached --files --summary-limit"
3105                 ;;
3106         foreach,--*|sync,--*)
3107                 __gitcomp "--recursive"
3108                 ;;
3109         *)
3110                 ;;
3111         esac
3112 }
3113
3114 _git_svn ()
3115 {
3116         local subcommands="
3117                 init fetch clone rebase dcommit log find-rev
3118                 set-tree commit-diff info create-ignore propget
3119                 proplist show-ignore show-externals branch tag blame
3120                 migrate mkdirs reset gc
3121                 "
3122         local subcommand="$(__git_find_on_cmdline "$subcommands")"
3123         if [ -z "$subcommand" ]; then
3124                 __gitcomp "$subcommands"
3125         else
3126                 local remote_opts="--username= --config-dir= --no-auth-cache"
3127                 local fc_opts="
3128                         --follow-parent --authors-file= --repack=
3129                         --no-metadata --use-svm-props --use-svnsync-props
3130                         --log-window-size= --no-checkout --quiet
3131                         --repack-flags --use-log-author --localtime
3132                         --add-author-from
3133                         --recursive
3134                         --ignore-paths= --include-paths= $remote_opts
3135                         "
3136                 local init_opts="
3137                         --template= --shared= --trunk= --tags=
3138                         --branches= --stdlayout --minimize-url
3139                         --no-metadata --use-svm-props --use-svnsync-props
3140                         --rewrite-root= --prefix= $remote_opts
3141                         "
3142                 local cmt_opts="
3143                         --edit --rmdir --find-copies-harder --copy-similarity=
3144                         "
3145
3146                 case "$subcommand,$cur" in
3147                 fetch,--*)
3148                         __gitcomp "--revision= --fetch-all $fc_opts"
3149                         ;;
3150                 clone,--*)
3151                         __gitcomp "--revision= $fc_opts $init_opts"
3152                         ;;
3153                 init,--*)
3154                         __gitcomp "$init_opts"
3155                         ;;
3156                 dcommit,--*)
3157                         __gitcomp "
3158                                 --merge --strategy= --verbose --dry-run
3159                                 --fetch-all --no-rebase --commit-url
3160                                 --revision --interactive $cmt_opts $fc_opts
3161                                 "
3162                         ;;
3163                 set-tree,--*)
3164                         __gitcomp "--stdin $cmt_opts $fc_opts"
3165                         ;;
3166                 create-ignore,--*|propget,--*|proplist,--*|show-ignore,--*|\
3167                 show-externals,--*|mkdirs,--*)
3168                         __gitcomp "--revision="
3169                         ;;
3170                 log,--*)
3171                         __gitcomp "
3172                                 --limit= --revision= --verbose --incremental
3173                                 --oneline --show-commit --non-recursive
3174                                 --authors-file= --color
3175                                 "
3176                         ;;
3177                 rebase,--*)
3178                         __gitcomp "
3179                                 --merge --verbose --strategy= --local
3180                                 --fetch-all --dry-run $fc_opts
3181                                 "
3182                         ;;
3183                 commit-diff,--*)
3184                         __gitcomp "--message= --file= --revision= $cmt_opts"
3185                         ;;
3186                 info,--*)
3187                         __gitcomp "--url"
3188                         ;;
3189                 branch,--*)
3190                         __gitcomp "--dry-run --message --tag"
3191                         ;;
3192                 tag,--*)
3193                         __gitcomp "--dry-run --message"
3194                         ;;
3195                 blame,--*)
3196                         __gitcomp "--git-format"
3197                         ;;
3198                 migrate,--*)
3199                         __gitcomp "
3200                                 --config-dir= --ignore-paths= --minimize
3201                                 --no-auth-cache --username=
3202                                 "
3203                         ;;
3204                 reset,--*)
3205                         __gitcomp "--revision= --parent"
3206                         ;;
3207                 *)
3208                         ;;
3209                 esac
3210         fi
3211 }
3212
3213 _git_tag ()
3214 {
3215         local i c="$__git_cmd_idx" f=0
3216         while [ $c -lt $cword ]; do
3217                 i="${words[c]}"
3218                 case "$i" in
3219                 -d|--delete|-v|--verify)
3220                         __gitcomp_direct "$(__git_tags "" "$cur" " ")"
3221                         return
3222                         ;;
3223                 -f)
3224                         f=1
3225                         ;;
3226                 esac
3227                 ((c++))
3228         done
3229
3230         case "$prev" in
3231         -m|-F)
3232                 ;;
3233         -*|tag)
3234                 if [ $f = 1 ]; then
3235                         __gitcomp_direct "$(__git_tags "" "$cur" " ")"
3236                 fi
3237                 ;;
3238         *)
3239                 __git_complete_refs
3240                 ;;
3241         esac
3242
3243         case "$cur" in
3244         --*)
3245                 __gitcomp_builtin tag
3246                 ;;
3247         esac
3248 }
3249
3250 _git_whatchanged ()
3251 {
3252         _git_log
3253 }
3254
3255 __git_complete_worktree_paths ()
3256 {
3257         local IFS=$'\n'
3258         # Generate completion reply from worktree list skipping the first
3259         # entry: it's the path of the main worktree, which can't be moved,
3260         # removed, locked, etc.
3261         __gitcomp_nl "$(git worktree list --porcelain |
3262                 sed -n -e '2,$ s/^worktree //p')"
3263 }
3264
3265 _git_worktree ()
3266 {
3267         local subcommands="add list lock move prune remove unlock"
3268         local subcommand subcommand_idx
3269
3270         subcommand="$(__git_find_on_cmdline --show-idx "$subcommands")"
3271         subcommand_idx="${subcommand% *}"
3272         subcommand="${subcommand#* }"
3273
3274         case "$subcommand,$cur" in
3275         ,*)
3276                 __gitcomp "$subcommands"
3277                 ;;
3278         *,--*)
3279                 __gitcomp_builtin worktree_$subcommand
3280                 ;;
3281         add,*)  # usage: git worktree add [<options>] <path> [<commit-ish>]
3282                 # Here we are not completing an --option, it's either the
3283                 # path or a ref.
3284                 case "$prev" in
3285                 -b|-B)  # Complete refs for branch to be created/reseted.
3286                         __git_complete_refs
3287                         ;;
3288                 -*)     # The previous word is an -o|--option without an
3289                         # unstuck argument: have to complete the path for
3290                         # the new worktree, so don't list anything, but let
3291                         # Bash fall back to filename completion.
3292                         ;;
3293                 *)      # The previous word is not an --option, so it must
3294                         # be either the 'add' subcommand, the unstuck
3295                         # argument of an option (e.g. branch for -b|-B), or
3296                         # the path for the new worktree.
3297                         if [ $cword -eq $((subcommand_idx+1)) ]; then
3298                                 # Right after the 'add' subcommand: have to
3299                                 # complete the path, so fall back to Bash
3300                                 # filename completion.
3301                                 :
3302                         else
3303                                 case "${words[cword-2]}" in
3304                                 -b|-B)  # After '-b <branch>': have to
3305                                         # complete the path, so fall back
3306                                         # to Bash filename completion.
3307                                         ;;
3308                                 *)      # After the path: have to complete
3309                                         # the ref to be checked out.
3310                                         __git_complete_refs
3311                                         ;;
3312                                 esac
3313                         fi
3314                         ;;
3315                 esac
3316                 ;;
3317         lock,*|remove,*|unlock,*)
3318                 __git_complete_worktree_paths
3319                 ;;
3320         move,*)
3321                 if [ $cword -eq $((subcommand_idx+1)) ]; then
3322                         # The first parameter must be an existing working
3323                         # tree to be moved.
3324                         __git_complete_worktree_paths
3325                 else
3326                         # The second parameter is the destination: it could
3327                         # be any path, so don't list anything, but let Bash
3328                         # fall back to filename completion.
3329                         :
3330                 fi
3331                 ;;
3332         esac
3333 }
3334
3335 __git_complete_common () {
3336         local command="$1"
3337
3338         case "$cur" in
3339         --*)
3340                 __gitcomp_builtin "$command"
3341                 ;;
3342         esac
3343 }
3344
3345 __git_cmds_with_parseopt_helper=
3346 __git_support_parseopt_helper () {
3347         test -n "$__git_cmds_with_parseopt_helper" ||
3348                 __git_cmds_with_parseopt_helper="$(__git --list-cmds=parseopt)"
3349
3350         case " $__git_cmds_with_parseopt_helper " in
3351         *" $1 "*)
3352                 return 0
3353                 ;;
3354         *)
3355                 return 1
3356                 ;;
3357         esac
3358 }
3359
3360 __git_have_func () {
3361         declare -f -- "$1" >/dev/null 2>&1
3362 }
3363
3364 __git_complete_command () {
3365         local command="$1"
3366         local completion_func="_git_${command//-/_}"
3367         if ! __git_have_func $completion_func &&
3368                 __git_have_func _completion_loader
3369         then
3370                 _completion_loader "git-$command"
3371         fi
3372         if __git_have_func $completion_func
3373         then
3374                 $completion_func
3375                 return 0
3376         elif __git_support_parseopt_helper "$command"
3377         then
3378                 __git_complete_common "$command"
3379                 return 0
3380         else
3381                 return 1
3382         fi
3383 }
3384
3385 __git_main ()
3386 {
3387         local i c=1 command __git_dir __git_repo_path
3388         local __git_C_args C_args_count=0
3389         local __git_cmd_idx
3390
3391         while [ $c -lt $cword ]; do
3392                 i="${words[c]}"
3393                 case "$i" in
3394                 --git-dir=*)
3395                         __git_dir="${i#--git-dir=}"
3396                         ;;
3397                 --git-dir)
3398                         ((c++))
3399                         __git_dir="${words[c]}"
3400                         ;;
3401                 --bare)
3402                         __git_dir="."
3403                         ;;
3404                 --help)
3405                         command="help"
3406                         break
3407                         ;;
3408                 -c|--work-tree|--namespace)
3409                         ((c++))
3410                         ;;
3411                 -C)
3412                         __git_C_args[C_args_count++]=-C
3413                         ((c++))
3414                         __git_C_args[C_args_count++]="${words[c]}"
3415                         ;;
3416                 -*)
3417                         ;;
3418                 *)
3419                         command="$i"
3420                         __git_cmd_idx="$c"
3421                         break
3422                         ;;
3423                 esac
3424                 ((c++))
3425         done
3426
3427         if [ -z "${command-}" ]; then
3428                 case "$prev" in
3429                 --git-dir|-C|--work-tree)
3430                         # these need a path argument, let's fall back to
3431                         # Bash filename completion
3432                         return
3433                         ;;
3434                 -c)
3435                         __git_complete_config_variable_name_and_value
3436                         return
3437                         ;;
3438                 --namespace)
3439                         # we don't support completing these options' arguments
3440                         return
3441                         ;;
3442                 esac
3443                 case "$cur" in
3444                 --*)
3445                         __gitcomp "
3446                         --paginate
3447                         --no-pager
3448                         --git-dir=
3449                         --bare
3450                         --version
3451                         --exec-path
3452                         --exec-path=
3453                         --html-path
3454                         --man-path
3455                         --info-path
3456                         --work-tree=
3457                         --namespace=
3458                         --no-replace-objects
3459                         --help
3460                         "
3461                         ;;
3462                 *)
3463                         if test -n "${GIT_TESTING_PORCELAIN_COMMAND_LIST-}"
3464                         then
3465                                 __gitcomp "$GIT_TESTING_PORCELAIN_COMMAND_LIST"
3466                         else
3467                                 __gitcomp "$(__git --list-cmds=list-mainporcelain,others,nohelpers,alias,list-complete,config)"
3468                         fi
3469                         ;;
3470                 esac
3471                 return
3472         fi
3473
3474         __git_complete_command "$command" && return
3475
3476         local expansion=$(__git_aliased_command "$command")
3477         if [ -n "$expansion" ]; then
3478                 words[1]=$expansion
3479                 __git_complete_command "$expansion"
3480         fi
3481 }
3482
3483 __gitk_main ()
3484 {
3485         __git_has_doubledash && return
3486
3487         local __git_repo_path
3488         __git_find_repo_path
3489
3490         local merge=""
3491         if [ -f "$__git_repo_path/MERGE_HEAD" ]; then
3492                 merge="--merge"
3493         fi
3494         case "$cur" in
3495         --*)
3496                 __gitcomp "
3497                         $__git_log_common_options
3498                         $__git_log_gitk_options
3499                         $merge
3500                         "
3501                 return
3502                 ;;
3503         esac
3504         __git_complete_revlist
3505 }
3506
3507 if [[ -n ${ZSH_VERSION-} && -z ${GIT_SOURCING_ZSH_COMPLETION-} ]]; then
3508         echo "ERROR: this script is obsolete, please see git-completion.zsh" 1>&2
3509         return
3510 fi
3511
3512 __git_func_wrap ()
3513 {
3514         local cur words cword prev
3515         _get_comp_words_by_ref -n =: cur words cword prev
3516         $1
3517 }
3518
3519 ___git_complete ()
3520 {
3521         local wrapper="__git_wrap${2}"
3522         eval "$wrapper () { __git_func_wrap $2 ; }"
3523         complete -o bashdefault -o default -o nospace -F $wrapper $1 2>/dev/null \
3524                 || complete -o default -o nospace -F $wrapper $1
3525 }
3526
3527 # Setup the completion for git commands
3528 # 1: command or alias
3529 # 2: function to call (e.g. `git`, `gitk`, `git_fetch`)
3530 __git_complete ()
3531 {
3532         local func
3533
3534         if __git_have_func $2; then
3535                 func=$2
3536         elif __git_have_func __$2_main; then
3537                 func=__$2_main
3538         elif __git_have_func _$2; then
3539                 func=_$2
3540         else
3541                 echo "ERROR: could not find function '$2'" 1>&2
3542                 return 1
3543         fi
3544         ___git_complete $1 $func
3545 }
3546
3547 ___git_complete git __git_main
3548 ___git_complete gitk __gitk_main
3549
3550 # The following are necessary only for Cygwin, and only are needed
3551 # when the user has tab-completed the executable name and consequently
3552 # included the '.exe' suffix.
3553 #
3554 if [ "$OSTYPE" = cygwin ]; then
3555         ___git_complete git.exe __git_main
3556 fi