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