completion.bash
This file
Path
shell/completion.bash
693 lines · 20.1 KiB · Shell
Last changed by
[bash,zsh] Fix the version check for mawk (#4574)Koichi Murasebefore adoption5cb6957
History of this fileTake it
1# ____ ____2# / __/___ / __/3# / /_/_ / / /_4# / __/ / /_/ __/5# /_/ /___/_/ completion.bash6#7# - $FZF_TMUX (default: 0)8# - $FZF_TMUX_OPTS (default: empty)9# - $FZF_COMPLETION_TRIGGER (default: '**')10# - $FZF_COMPLETION_OPTS (default: empty)11# - $FZF_COMPLETION_PATH_OPTS (default: empty)12# - $FZF_COMPLETION_DIR_OPTS (default: empty)1314if [[ $- =~ i ]]; then151617# To use custom commands instead of find, override _fzf_compgen_{path,dir}18#19# _fzf_compgen_path() {20# echo "$1"21# command find -L "$1" \22# -name .git -prune -o -name .hg -prune -o -name .svn -prune -o \( -type d -o -type f -o -type l \) \23# -a -not -path "$1" -print 2> /dev/null | command sed 's@^\./@@'24# }25#26# _fzf_compgen_dir() {27# command find -L "$1" \28# -name .git -prune -o -name .hg -prune -o -name .svn -prune -o -type d \29# -a -not -path "$1" -print 2> /dev/null | command sed 's@^\./@@'30# }3132###########################################################3334#----BEGIN shfmt35#----BEGIN INCLUDE common.sh36# NOTE: Do not directly edit this section, which is copied from "common.sh".37# To modify it, one can edit "common.sh" and run "./update.sh" to apply38# the changes. See code comments in "common.sh" for the implementation details.3940__fzf_defaults() {41 printf '%s\n' "--height ${FZF_TMUX_HEIGHT:-40%} --min-height 20+ --bind=ctrl-z:ignore $1"42 command cat "${FZF_DEFAULT_OPTS_FILE-}" 2> /dev/null43 printf '%s\n' "${FZF_DEFAULT_OPTS-} $2"44}4546__fzf_exec_awk() {47 if [[ -z ${__fzf_awk-} ]]; then48 __fzf_awk=awk49 if [[ $OSTYPE == solaris* && -x /usr/xpg4/bin/awk ]]; then50 __fzf_awk=/usr/xpg4/bin/awk51 elif command -v mawk > /dev/null 2>&1; then52 local n x y z d53 IFS=' .' read -r n x y z d <<< $(command mawk -W version 2> /dev/null)54 [[ $n == mawk ]] &&55 (((x * 1000 + y) * 1000 + z >= 1003004)) 2> /dev/null &&56 ((d >= 20230302)) 2> /dev/null &&57 __fzf_awk=mawk58 fi59 fi60 LC_ALL=C exec "$__fzf_awk" "$@"61}62#----END INCLUDE6364__fzf_comprun() {65 if [[ "$(type -t _fzf_comprun 2>&1)" == function ]]; then66 _fzf_comprun "$@"67 elif [[ -n ${TMUX_PANE-} ]] && { [[ ${FZF_TMUX:-0} != 0 ]] || [[ -n ${FZF_TMUX_OPTS-} ]]; }; then68 shift69 fzf-tmux ${FZF_TMUX_OPTS:--d${FZF_TMUX_HEIGHT:-40%}} -- "$@"70 else71 shift72 fzf "$@"73 fi74}7576__fzf_orig_completion() {77 local l comp f cmd78 while read -r l; do79 if [[ $l =~ ^(.*\ -F)\ *([^ ]*).*\ ([^ ]*)$ ]]; then80 comp="${BASH_REMATCH[1]}"81 f="${BASH_REMATCH[2]}"82 cmd="${BASH_REMATCH[3]}"83 [[ $f == _fzf_* ]] && continue84 printf -v "_fzf_orig_completion_${cmd//[^A-Za-z0-9_]/_}" "%s" "${comp} %s ${cmd} #${f}"85 if [[ $l == *" -o nospace "* ]] && [[ ${__fzf_nospace_commands-} != *" $cmd "* ]]; then86 __fzf_nospace_commands="${__fzf_nospace_commands-} $cmd "87 fi88 fi89 done90}9192# @param $1 cmd - Command name for which the original completion is searched93# @var[out] REPLY - Original function name is returned94__fzf_orig_completion_get_orig_func() {95 local cmd orig_var orig96 cmd=$197 orig_var="_fzf_orig_completion_${cmd//[^A-Za-z0-9_]/_}"98 orig="${!orig_var-}"99 REPLY="${orig##*#}"100 [[ $REPLY ]] && type "$REPLY" &> /dev/null101}102103# @param $1 cmd - Command name for which the original completion is searched104# @param $2 func - Fzf's completion function to replace the original function105# @var[out] REPLY - Completion setting is returned as a string to "eval"106__fzf_orig_completion_instantiate() {107 local cmd func orig_var orig108 cmd=$1109 func=$2110 orig_var="_fzf_orig_completion_${cmd//[^A-Za-z0-9_]/_}"111 orig="${!orig_var-}"112 orig="${orig%#*}"113 [[ $orig == *' %s '* ]] || return 1114 printf -v REPLY "$orig" "$func"115}116117_fzf_opts_completion() {118 local cur prev opts119 COMPREPLY=()120 cur="${COMP_WORDS[COMP_CWORD]}"121 prev="${COMP_WORDS[COMP_CWORD - 1]}"122 opts="123 +c --no-color124 +i --no-ignore-case125 +s --no-sort126 +x --no-extended127 --ansi128 --bash129 --bind130 --border131 --border-label132 --border-label-pos133 --color134 --cycle135 --disabled136 --ellipsis137 --expect138 --filepath-word139 --fish140 --header141 --header-first142 --header-lines143 --height144 --highlight-line145 --history146 --history-size147 --hscroll-off148 --info149 --jump-labels150 --keep-right151 --layout152 --listen153 --listen-unsafe154 --literal155 --man156 --margin157 --marker158 --min-height159 --no-bold160 --no-clear161 --no-hscroll162 --no-mouse163 --no-scrollbar164 --no-separator165 --no-unicode166 --padding167 --pointer168 --preview169 --preview-label170 --preview-label-pos171 --preview-window172 --print-query173 --print0174 --prompt175 --read0176 --reverse177 --scheme178 --scroll-off179 --separator180 --sync181 --tabstop182 --tac183 --tiebreak184 --tmux185 --track186 --version187 --with-nth188 --with-shell189 --wrap190 --zsh191 -0 --exit-0192 -1 --select-1193 -d --delimiter194 -e --exact195 -f --filter196 -h --help197 -i --ignore-case198 -m --multi199 -n --nth200 -q --query201 --"202203 case "${prev}" in204 --scheme)205 COMPREPLY=($(compgen -W "default path history" -- "$cur"))206 return 0207 ;;208 --tiebreak)209 COMPREPLY=($(compgen -W "length chunk begin end index" -- "$cur"))210 return 0211 ;;212 --color)213 COMPREPLY=($(compgen -W "dark light 16 bw no" -- "$cur"))214 return 0215 ;;216 --layout)217 COMPREPLY=($(compgen -W "default reverse reverse-list" -- "$cur"))218 return 0219 ;;220 --info)221 COMPREPLY=($(compgen -W "default right hidden inline inline-right" -- "$cur"))222 return 0223 ;;224 --preview-window)225 COMPREPLY=($(compgen -W "226 default227 hidden228 nohidden229 wrap230 nowrap231 cycle232 nocycle233 up top234 down bottom235 left236 right237 rounded border border-rounded238 sharp border-sharp239 border-bold240 border-block241 border-thinblock242 border-double243 noborder border-none244 border-horizontal245 border-vertical246 border-up border-top247 border-down border-bottom248 border-left249 border-right250 follow251 nofollow" -- "$cur"))252 return 0253 ;;254 --border)255 COMPREPLY=($(compgen -W "rounded sharp bold block thinblock double horizontal vertical top bottom left right none" -- "$cur"))256 return 0257 ;;258 --border-label-pos | --preview-label-pos)259 COMPREPLY=($(compgen -W "center bottom top" -- "$cur"))260 return 0261 ;;262 esac263264 if [[ $cur =~ ^-|\+ ]]; then265 COMPREPLY=($(compgen -W "${opts}" -- "$cur"))266 return 0267 fi268269 return 0270}271272_fzf_handle_dynamic_completion() {273 local cmd ret REPLY orig_cmd orig_complete274 cmd="$1"275 shift276 orig_cmd="$1"277 if __fzf_orig_completion_get_orig_func "$cmd"; then278 "$REPLY" "$@"279 elif [[ -n ${_fzf_completion_loader-} ]]; then280 orig_complete=$(complete -p "$orig_cmd" 2> /dev/null)281 $_fzf_completion_loader "$@"282 ret=$?283 # _completion_loader may not have updated completion for the command284 if [[ "$(complete -p "$orig_cmd" 2> /dev/null)" != "$orig_complete" ]]; then285 __fzf_orig_completion < <(complete -p "$orig_cmd" 2> /dev/null)286 __fzf_orig_completion_get_orig_func "$cmd" || ret=1287288 # Update orig_complete by _fzf_orig_completion entry289 [[ $orig_complete =~ ' -F '(_fzf_[^ ]+)' ' ]] &&290 __fzf_orig_completion_instantiate "$cmd" "${BASH_REMATCH[1]}" &&291 orig_complete=$REPLY292293 if [[ ${__fzf_nospace_commands-} == *" $orig_cmd "* ]]; then294 eval "${orig_complete/ -F / -o nospace -F }"295 else296 eval "$orig_complete"297 fi298 fi299 [[ $ret -eq 0 ]] && return 124300 return $ret301 fi302}303304__fzf_generic_path_completion() {305 local cur base dir leftover matches trigger cmd306 cmd="${COMP_WORDS[0]}"307 if [[ $cmd == \\* ]]; then308 cmd="${cmd:1}"309 fi310 COMPREPLY=()311 trigger=${FZF_COMPLETION_TRIGGER-'**'}312 [[ $COMP_CWORD -ge 0 ]] && cur="${COMP_WORDS[COMP_CWORD]}"313 if [[ $cur == *"$trigger" ]] && [[ $cur != *'$('* ]] && [[ $cur != *':='* ]] && [[ $cur != *'`'* ]]; then314 base=${cur:0:${#cur}-${#trigger}}315 eval "base=$base" 2> /dev/null || return316317 dir=318 [[ $base == *"/"* ]] && dir="$base"319 while true; do320 if [[ -z $dir ]] || [[ -d $dir ]]; then321 leftover=${base/#"$dir"/}322 leftover=${leftover/#\//}323 [[ -z $dir ]] && dir='.'324 [[ $dir != "/" ]] && dir="${dir/%\//}"325 matches=$(326 export FZF_DEFAULT_OPTS=$(__fzf_defaults "--reverse --scheme=path" "${FZF_COMPLETION_OPTS-} $2")327 unset FZF_DEFAULT_COMMAND FZF_DEFAULT_OPTS_FILE328 if declare -F "$1" > /dev/null; then329 eval "$1 $(printf %q "$dir")" | __fzf_comprun "$4" -q "$leftover"330 else331 if [[ $1 =~ dir ]]; then332 walker=dir,follow333 eval "rest=(${FZF_COMPLETION_DIR_OPTS-})"334 else335 walker=file,dir,follow,hidden336 eval "rest=(${FZF_COMPLETION_PATH_OPTS-})"337 fi338 __fzf_comprun "$4" -q "$leftover" --walker "$walker" --walker-root="$dir" "${rest[@]}"339 fi | while read -r item; do340 printf "%q " "${item%$3}$3"341 done342 )343 matches=${matches% }344 [[ -z $3 ]] && [[ ${__fzf_nospace_commands-} == *" ${COMP_WORDS[0]} "* ]] && matches="$matches "345 if [[ -n $matches ]]; then346 COMPREPLY=("$matches")347 else348 COMPREPLY=("$cur")349 fi350 # To redraw line after fzf closes (printf '\e[5n')351 bind '"\e[0n": redraw-current-line' 2> /dev/null352 printf '\e[5n'353 return 0354 fi355 dir=$(command dirname "$dir")356 [[ $dir =~ /$ ]] || dir="$dir"/357 done358 else359 shift360 shift361 shift362 _fzf_handle_dynamic_completion "$cmd" "$@"363 fi364}365366_fzf_complete() {367 # Split arguments around --368 local args rest str_arg i sep369 args=("$@")370 sep=371 for i in "${!args[@]}"; do372 if [[ ${args[$i]} == -- ]]; then373 sep=$i374 break375 fi376 done377 if [[ -n $sep ]]; then378 str_arg=379 rest=("${args[@]:$((sep + 1)):${#args[@]}}")380 args=("${args[@]:0:sep}")381 else382 str_arg=$1383 args=()384 shift385 rest=("$@")386 fi387388 local cur selected trigger cmd post389 post="$(caller 0 | __fzf_exec_awk '{print $2}')_post"390 type -t "$post" > /dev/null 2>&1 || post='command cat'391392 trigger=${FZF_COMPLETION_TRIGGER-'**'}393 cmd="${COMP_WORDS[0]}"394 cur="${COMP_WORDS[COMP_CWORD]}"395 if [[ $cur == *"$trigger" ]] && [[ $cur != *'$('* ]] && [[ $cur != *':='* ]] && [[ $cur != *'`'* ]]; then396 cur=${cur:0:${#cur}-${#trigger}}397398 selected=$(399 FZF_DEFAULT_OPTS=$(__fzf_defaults "--reverse" "${FZF_COMPLETION_OPTS-} $str_arg") \400 FZF_DEFAULT_OPTS_FILE='' \401 __fzf_comprun "${rest[0]}" "${args[@]}" -q "$cur" | eval "$post" | command tr '\n' ' '402 )403 selected=${selected% } # Strip trailing space not to repeat "-o nospace"404 if [[ -n $selected ]]; then405 COMPREPLY=("$selected")406 else407 COMPREPLY=("$cur")408 fi409 bind '"\e[0n": redraw-current-line' 2> /dev/null410 printf '\e[5n'411 return 0412 else413 _fzf_handle_dynamic_completion "$cmd" "${rest[@]}"414 fi415}416417_fzf_path_completion() {418 __fzf_generic_path_completion _fzf_compgen_path "-m" "" "$@"419}420421# Deprecated. No file only completion.422_fzf_file_completion() {423 _fzf_path_completion "$@"424}425426_fzf_dir_completion() {427 __fzf_generic_path_completion _fzf_compgen_dir "" "/" "$@"428}429430_fzf_complete_kill() {431 _fzf_proc_completion "$@"432}433434_fzf_proc_completion() {435 local transformer436 transformer='437 if [[ $FZF_KEY =~ ctrl|alt|shift ]] && [[ -n $FZF_NTH ]]; then438 nths=( ${FZF_NTH//,/ } )439 new_nths=()440 found=0441 for nth in ${nths[@]}; do442 if [[ $nth = $FZF_CLICK_HEADER_NTH ]]; then443 found=1444 else445 new_nths+=($nth)446 fi447 done448 [[ $found = 0 ]] && new_nths+=($FZF_CLICK_HEADER_NTH)449 new_nths=${new_nths[*]}450 new_nths=${new_nths// /,}451 echo "change-nth($new_nths)+change-prompt($new_nths> )"452 else453 if [[ $FZF_NTH = $FZF_CLICK_HEADER_NTH ]]; then454 echo "change-nth()+change-prompt(> )"455 else456 echo "change-nth($FZF_CLICK_HEADER_NTH)+change-prompt($FZF_CLICK_HEADER_WORD> )"457 fi458 fi459 '460 _fzf_complete -m --header-lines=1 --no-preview --wrap --color fg:dim,nth:regular \461 --bind "click-header:transform:$transformer" -- "$@" < <(462 command ps -eo user,pid,ppid,start,time,command 2> /dev/null ||463 command ps -eo user,pid,ppid,time,args 2> /dev/null || # For BusyBox464 command ps --everyone --full --windows # For cygwin465 )466}467468_fzf_proc_completion_post() {469 __fzf_exec_awk '{print $2}'470}471472# To use custom hostname lists, override __fzf_list_hosts.473# The function is expected to print hostnames, one per line as well as in the474# desired sorting and with any duplicates removed, to standard output.475#476# e.g.477# # Use bash-completions’s _known_hosts_real() for getting the list of hosts478# __fzf_list_hosts() {479# # Set the local attribute for any non-local variable that is set by _known_hosts_real()480# local COMPREPLY=()481# _known_hosts_real ''482# printf '%s\n' "${COMPREPLY[@]}" | command sort -u --version-sort483# }484if ! declare -F __fzf_list_hosts > /dev/null; then485 __fzf_list_hosts() {486 command sort -u \487 <(488 # Note: To make the pathname expansion of "~/.ssh/config.d/*" work489 # properly, we need to adjust the related shell options. We need to490 # unset "set -f" and "GLOBIGNORE", which disable the pathname expansion491 # totally or partially. We need to unset "dotglob" and "nocaseglob" to492 # avoid matching unwanted files. We need to unset "failglob" to avoid493 # outputting the error messages to the terminal when no matching is494 # found. We need to set "nullglob" to avoid attempting to read the495 # literal filename '~/.ssh/config.d/*' when no matching is found.496 set +f497 GLOBIGNORE=498 shopt -u dotglob nocaseglob failglob499 shopt -s nullglob500501 __fzf_exec_awk '502 # Note: mawk <= 1.3.3-20090705 does not support the POSIX brackets of503 # the form [[:blank:]], and Ubuntu 18.04 LTS still uses this504 # 16-year-old mawk unfortunately. We need to use [ \t] instead.505 match(tolower($0), /^[ \t]*host(name)?[ \t]*[ \t=]/) {506 $0 = substr($0, RLENGTH + 1) # Remove "Host(name)?=?"507 sub(/#.*/, "")508 for (i = 1; i <= NF; i++)509 if ($i !~ /[*?%]/)510 print $i511 }512 ' ~/.ssh/config ~/.ssh/config.d/* /etc/ssh/ssh_config 2> /dev/null513 ) \514 <(515 __fzf_exec_awk -F ',' '516 match($0, /^[][a-zA-Z0-9.,:-]+/) {517 $0 = substr($0, 1, RLENGTH)518 gsub(/[][]|:[^,]*/, "")519 for (i = 1; i <= NF; i++)520 print $i521 }522 ' ~/.ssh/known_hosts 2> /dev/null523 ) \524 <(525 __fzf_exec_awk '526 {527 sub(/#.*/, "")528 for (i = 2; i <= NF; i++)529 if ($i != "0.0.0.0")530 print $i531 }532 ' /etc/hosts 2> /dev/null533 )534 }535fi536537_fzf_host_completion() {538 _fzf_complete +m -- "$@" < <(__fzf_list_hosts)539}540541# Values for $1 $2 $3 are described here542# https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion.html543# > the first argument ($1) is the name of the command whose arguments are being completed,544# > the second argument ($2) is the word being completed,545# > and the third argument ($3) is the word preceding the word being completed on the current command line.546_fzf_complete_ssh() {547 case $3 in548 -i | -F | -E)549 _fzf_path_completion "$@"550 ;;551 *)552 local user=553 [[ $2 =~ '@' ]] && user="${2%%@*}@"554 _fzf_complete +m -- "$@" < <(__fzf_list_hosts | __fzf_exec_awk -v user="$user" '{print user $0}')555 ;;556 esac557}558559_fzf_var_completion() {560 _fzf_complete -m -- "$@" < <(561 declare -xp | command sed -En 's|^declare [^ ]+ ([^=]+).*|\1|p'562 )563}564565_fzf_alias_completion() {566 _fzf_complete -m -- "$@" < <(567 alias | command sed -En 's|^alias ([^=]+).*|\1|p'568 )569}570571# fzf options572complete -o default -F _fzf_opts_completion fzf573# fzf-tmux is a thin fzf wrapper that has only a few more options than fzf574# itself. As a quick improvement we take fzf's completion. Adding the few extra575# fzf-tmux specific options (like `-w WIDTH`) are left as a future patch.576complete -o default -F _fzf_opts_completion fzf-tmux577578# Default path completion579__fzf_default_completion() {580 __fzf_generic_path_completion _fzf_compgen_path "-m" "" "$@"581582 # Dynamic completion loader has updated the completion for the command583 if [[ $? -eq 124 ]]; then584 # We trigger _fzf_setup_completion so that fuzzy completion for the command585 # still works. However, loader can update the completion for multiple586 # commands at once, and fuzzy completion will no longer work for those587 # other commands. e.g. pytest -> py.test, pytest-2, pytest-3, etc588 _fzf_setup_completion path "$1"589 return 124590 fi591}592593# Set fuzzy path completion as the default completion for all commands.594# We can't set up default completion,595# 1. if it's already set up by another script596# 2. or if the current version of bash doesn't support -D option597complete | command grep -q __fzf_default_completion ||598 complete | command grep -- '-D$' | command grep -qv _comp_complete_load ||599 complete -D -F __fzf_default_completion -o default -o bashdefault 2> /dev/null600601d_cmds="${FZF_COMPLETION_DIR_COMMANDS-cd pushd rmdir}"602603# NOTE: $FZF_COMPLETION_PATH_COMMANDS and $FZF_COMPLETION_VAR_COMMANDS are604# undocumented and subject to change in the future.605#606# NOTE: Although we have default completion, we still need to set up completion607# for each command in case they already have completion set up by another script.608a_cmds="${FZF_COMPLETION_PATH_COMMANDS-"609 awk bat cat code diff diff3610 emacs emacsclient ex file ftp g++ gcc gvim head hg hx java611 javac ld less more mvim nvim patch perl python ruby612 sed sftp sort source tail tee uniq vi view vim wc xdg-open613 basename bunzip2 bzip2 chmod chown curl cp dirname du614 find git grep gunzip gzip hg jar615 ln ls mv open rm rsync scp616 svn tar unzip zip"}"617v_cmds="${FZF_COMPLETION_VAR_COMMANDS-export unset printenv}"618619# Preserve existing completion620__fzf_orig_completion < <(complete -p $d_cmds $a_cmds $v_cmds unalias kill ssh 2> /dev/null)621622if type _comp_load > /dev/null 2>&1; then623 # _comp_load was added in bash-completion 2.12 to replace _completion_loader.624 # We use it without -D option so that it does not use _comp_complete_minimal as the fallback.625 _fzf_completion_loader=_comp_load626elif type __load_completion > /dev/null 2>&1; then627 # In bash-completion 2.11, _completion_loader internally calls __load_completion628 # and if it returns a non-zero status, it sets the default 'minimal' completion.629 _fzf_completion_loader=__load_completion630elif type _completion_loader > /dev/null 2>&1; then631 _fzf_completion_loader=_completion_loader632fi633634__fzf_defc() {635 local cmd func opts REPLY636 cmd="$1"637 func="$2"638 opts="$3"639 if __fzf_orig_completion_instantiate "$cmd" "$func"; then640 eval "$REPLY"641 else642 eval "complete -F \"$func\" $opts \"$cmd\""643 fi644}645646# Anything647for cmd in $a_cmds; do648 __fzf_defc "$cmd" _fzf_path_completion "-o default -o bashdefault"649done650651# Directory652for cmd in $d_cmds; do653 __fzf_defc "$cmd" _fzf_dir_completion "-o bashdefault -o nospace -o dirnames"654done655656# Variables657for cmd in $v_cmds; do658 __fzf_defc "$cmd" _fzf_var_completion "-o default -o nospace -v"659done660661# Aliases662__fzf_defc unalias _fzf_alias_completion "-a"663664# Processes665__fzf_defc kill _fzf_proc_completion "-o default -o bashdefault"666667# ssh668__fzf_defc ssh _fzf_complete_ssh "-o default -o bashdefault"669670unset cmd d_cmds a_cmds v_cmds671672_fzf_setup_completion() {673 local kind fn cmd674 kind=$1675 fn=_fzf_${1}_completion676 if [[ $# -lt 2 ]] || ! type -t "$fn" > /dev/null; then677 echo "usage: ${FUNCNAME[0]} path|dir|var|alias|host|proc COMMANDS..."678 return 1679 fi680 shift681 __fzf_orig_completion < <(complete -p "$@" 2> /dev/null)682 for cmd in "$@"; do683 case "$kind" in684 dir) __fzf_defc "$cmd" "$fn" "-o nospace -o dirnames" ;;685 var) __fzf_defc "$cmd" "$fn" "-o default -o nospace -v" ;;686 alias) __fzf_defc "$cmd" "$fn" "-a" ;;687 *) __fzf_defc "$cmd" "$fn" "-o default -o bashdefault" ;;688 esac689 done690}691#----END shfmt692693fi