Skip to content
Myr

completion.bash

This file

Path

shell/completion.bash

574 lines 路 15.2 KiB 路 Shell

Last changed by

Add walker options and replace 'find' with the built-in walker (#3649)Junegunn Choibefore adoptiond282a16

History of this file

Take 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)1112[[ $- =~ i ]] || return 0131415# To use custom commands instead of find, override _fzf_compgen_{path,dir}16#17#   _fzf_compgen_path() {18#     echo "$1"19#     command find -L "$1" \20#       -name .git -prune -o -name .hg -prune -o -name .svn -prune -o \( -type d -o -type f -o -type l \) \21#       -a -not -path "$1" -print 2> /dev/null | command sed 's@^\./@@'22#   }23#24#   _fzf_compgen_dir() {25#     command find -L "$1" \26#       -name .git -prune -o -name .hg -prune -o -name .svn -prune -o -type d \27#       -a -not -path "$1" -print 2> /dev/null | command sed 's@^\./@@'28#   }2930###########################################################3132# To redraw line after fzf closes (printf '\e[5n')33bind '"\e[0n": redraw-current-line' 2> /dev/null3435__fzf_comprun() {36  if [[ "$(type -t _fzf_comprun 2>&1)" = function ]]; then37    _fzf_comprun "$@"38  elif [[ -n "${TMUX_PANE-}" ]] && { [[ "${FZF_TMUX:-0}" != 0 ]] || [[ -n "${FZF_TMUX_OPTS-}" ]]; }; then39    shift40    fzf-tmux ${FZF_TMUX_OPTS:--d${FZF_TMUX_HEIGHT:-40%}} -- "$@"41  else42    shift43    fzf "$@"44  fi45}4647__fzf_orig_completion() {48  local l comp f cmd49  while read -r l; do50    if [[ "$l" =~ ^(.*\ -F)\ *([^ ]*).*\ ([^ ]*)$ ]]; then51      comp="${BASH_REMATCH[1]}"52      f="${BASH_REMATCH[2]}"53      cmd="${BASH_REMATCH[3]}"54      [[ "$f" = _fzf_* ]] && continue55      printf -v "_fzf_orig_completion_${cmd//[^A-Za-z0-9_]/_}" "%s" "${comp} %s ${cmd} #${f}"56      if [[ "$l" = *" -o nospace "* ]] && [[ ! "${__fzf_nospace_commands-}" = *" $cmd "* ]]; then57        __fzf_nospace_commands="${__fzf_nospace_commands-} $cmd "58      fi59    fi60  done61}6263# @param $1 cmd - Command name for which the original completion is searched64# @var[out] REPLY - Original function name is returned65__fzf_orig_completion_get_orig_func() {66  local cmd orig_var orig67  cmd=$168  orig_var="_fzf_orig_completion_${cmd//[^A-Za-z0-9_]/_}"69  orig="${!orig_var-}"70  REPLY="${orig##*#}"71  [[ $REPLY ]] && type "$REPLY" &> /dev/null72}7374# @param $1 cmd - Command name for which the original completion is searched75# @param $2 func - Fzf's completion function to replace the original function76# @var[out] REPLY - Completion setting is returned as a string to "eval"77__fzf_orig_completion_instantiate() {78  local cmd func orig_var orig79  cmd=$180  func=$281  orig_var="_fzf_orig_completion_${cmd//[^A-Za-z0-9_]/_}"82  orig="${!orig_var-}"83  orig="${orig%#*}"84  [[ $orig == *' %s '* ]] || return 185  printf -v REPLY "$orig" "$func"86}8788_fzf_opts_completion() {89  local cur prev opts90  COMPREPLY=()91  cur="${COMP_WORDS[COMP_CWORD]}"92  prev="${COMP_WORDS[COMP_CWORD-1]}"93  opts="94    -h --help95    -x --extended96    -e --exact97    --extended-exact98    +x --no-extended99    +e --no-exact100    -q --query101    -f --filter102    --literal103    --no-literal104    --algo105    --scheme106    --expect107    --no-expect108    --enabled --no-phony109    --disabled --phony110    --tiebreak111    --bind112    --color113    --toggle-sort114    -d --delimiter115    -n --nth116    --with-nth117    -s --sort118    +s --no-sort119    --track120    --no-track121    --tac122    --no-tac123    -i124    +i125    -m --multi126    +m --no-multi127    --ansi128    --no-ansi129    --no-mouse130    +c --no-color131    +2 --no-256132    --black133    --no-black134    --bold135    --no-bold136    --layout137    --reverse138    --no-reverse139    --cycle140    --no-cycle141    --keep-right142    --no-keep-right143    --hscroll144    --no-hscroll145    --hscroll-off146    --scroll-off147    --filepath-word148    --no-filepath-word149    --info150    --no-info151    --inline-info152    --no-inline-info153    --separator154    --no-separator155    --scrollbar156    --no-scrollbar157    --jump-labels158    -1 --select-1159    +1 --no-select-1160    -0 --exit-0161    +0 --no-exit-0162    --read0163    --no-read0164    --print0165    --no-print0166    --print-query167    --no-print-query168    --prompt169    --pointer170    --marker171    --sync172    --no-sync173    --async174    --no-history175    --history176    --history-size177    --no-header178    --no-header-lines179    --header180    --header-lines181    --header-first182    --no-header-first183    --ellipsis184    --preview185    --no-preview186    --preview-window187    --height188    --min-height189    --no-height190    --no-margin191    --no-padding192    --no-border193    --border194    --no-border-label195    --border-label196    --border-label-pos197    --no-preview-label198    --preview-label199    --preview-label-pos200    --no-unicode201    --unicode202    --margin203    --padding204    --tabstop205    --listen206    --no-listen207    --clear208    --no-clear209    --version210    --"211212  case "${prev}" in213  --algo)214    COMPREPLY=( $(compgen -W "v1 v2" -- "$cur") )215    return 0216    ;;217  --scheme)218    COMPREPLY=( $(compgen -W "default path history" -- "$cur") )219    return 0220    ;;221  --tiebreak)222    COMPREPLY=( $(compgen -W "length chunk begin end index" -- "$cur") )223    return 0224    ;;225  --color)226    COMPREPLY=( $(compgen -W "dark light 16 bw no" -- "$cur") )227    return 0228    ;;229  --layout)230    COMPREPLY=( $(compgen -W "default reverse reverse-list" -- "$cur") )231    return 0232    ;;233  --info)234    COMPREPLY=( $(compgen -W "default right hidden inline inline-right" -- "$cur") )235    return 0236    ;;237  --preview-window)238    COMPREPLY=( $(compgen -W "239      default240      hidden241      nohidden242      wrap243      nowrap244      cycle245      nocycle246      up top247      down bottom248      left249      right250      rounded border border-rounded251      sharp border-sharp252      border-bold253      border-block254      border-thinblock255      border-double256      noborder border-none257      border-horizontal258      border-vertical259      border-up border-top260      border-down border-bottom261      border-left262      border-right263      follow264      nofollow" -- "$cur") )265    return 0266    ;;267  --border)268    COMPREPLY=( $(compgen -W "rounded sharp bold block thinblock double horizontal vertical top bottom left right none" -- "$cur") )269    return 0270    ;;271  --border-label-pos|--preview-label-pos)272    COMPREPLY=( $(compgen -W "center bottom top" -- "$cur") )273    return 0274    ;;275  esac276277  if [[ "$cur" =~ ^-|\+ ]]; then278    COMPREPLY=( $(compgen -W "${opts}" -- "$cur") )279    return 0280  fi281282  return 0283}284285_fzf_handle_dynamic_completion() {286  local cmd ret REPLY orig_cmd orig_complete287  cmd="$1"288  shift289  orig_cmd="$1"290  if __fzf_orig_completion_get_orig_func "$cmd"; then291    "$REPLY" "$@"292  elif [[ -n "${_fzf_completion_loader-}" ]]; then293    orig_complete=$(complete -p "$orig_cmd" 2> /dev/null)294    _completion_loader "$@"295    ret=$?296    # _completion_loader may not have updated completion for the command297    if [[ "$(complete -p "$orig_cmd" 2> /dev/null)" != "$orig_complete" ]]; then298      __fzf_orig_completion < <(complete -p "$orig_cmd" 2> /dev/null)299300      # Update orig_complete by _fzf_orig_completion entry301      [[ $orig_complete =~ ' -F '(_fzf_[^ ]+)' ' ]] &&302        __fzf_orig_completion_instantiate "$cmd" "${BASH_REMATCH[1]}" &&303        orig_complete=$REPLY304305      if [[ "${__fzf_nospace_commands-}" = *" $orig_cmd "* ]]; then306        eval "${orig_complete/ -F / -o nospace -F }"307      else308        eval "$orig_complete"309      fi310    fi311    return $ret312  fi313}314315__fzf_generic_path_completion() {316  local cur base dir leftover matches trigger cmd317  cmd="${COMP_WORDS[0]}"318  if [[ $cmd == \\* ]]; then319    cmd="${cmd:1}"320  fi321  COMPREPLY=()322  trigger=${FZF_COMPLETION_TRIGGER-'**'}323  cur="${COMP_WORDS[COMP_CWORD]}"324  if [[ "$cur" == *"$trigger" ]] && [[ $cur != *'$('* ]] && [[ $cur != *':='* ]] && [[ $cur != *'`'* ]]; then325    base=${cur:0:${#cur}-${#trigger}}326    eval "base=$base" 2> /dev/null || return327328    dir=329    [[ $base = *"/"* ]] && dir="$base"330    while true; do331      if [[ -z "$dir" ]] || [[ -d "$dir" ]]; then332        leftover=${base/#"$dir"}333        leftover=${leftover/#\/}334        [[ -z "$dir" ]] && dir='.'335        [[ "$dir" != "/" ]] && dir="${dir/%\//}"336        matches=$(337          unset FZF_DEFAULT_COMMAND338          export FZF_DEFAULT_OPTS="--height ${FZF_TMUX_HEIGHT:-40%} --reverse --scheme=path --bind=ctrl-z:ignore ${FZF_DEFAULT_OPTS-} ${FZF_COMPLETION_OPTS-} $2"339          if declare -F "$1" > /dev/null; then340            eval "$1 $(printf %q "$dir")" | __fzf_comprun "$4" -q "$leftover"341          else342            [[ $1 =~ dir ]] && walker=dir,follow || walker=file,dir,follow,hidden343            __fzf_comprun "$4" -q "$leftover" --walker "$walker" --walker-root="$dir"344          fi | while read -r item; do345            printf "%q " "${item%$3}$3"346          done347        )348        matches=${matches% }349        [[ -z "$3" ]] && [[ "${__fzf_nospace_commands-}" = *" ${COMP_WORDS[0]} "* ]] && matches="$matches "350        if [[ -n "$matches" ]]; then351          COMPREPLY=( "$matches" )352        else353          COMPREPLY=( "$cur" )354        fi355        printf '\e[5n'356        return 0357      fi358      dir=$(command dirname "$dir")359      [[ "$dir" =~ /$ ]] || dir="$dir"/360    done361  else362    shift363    shift364    shift365    _fzf_handle_dynamic_completion "$cmd" "$@"366  fi367}368369_fzf_complete() {370  # Split arguments around --371  local args rest str_arg i sep372  args=("$@")373  sep=374  for i in "${!args[@]}"; do375    if [[ "${args[$i]}" = -- ]]; then376      sep=$i377      break378    fi379  done380  if [[ -n "$sep" ]]; then381    str_arg=382    rest=("${args[@]:$((sep + 1)):${#args[@]}}")383    args=("${args[@]:0:$sep}")384  else385    str_arg=$1386    args=()387    shift388    rest=("$@")389  fi390391  local cur selected trigger cmd post392  post="$(caller 0 | command awk '{print $2}')_post"393  type -t "$post" > /dev/null 2>&1 || post='command cat'394395  trigger=${FZF_COMPLETION_TRIGGER-'**'}396  cmd="${COMP_WORDS[0]}"397  cur="${COMP_WORDS[COMP_CWORD]}"398  if [[ "$cur" == *"$trigger" ]] && [[ $cur != *'$('* ]] && [[ $cur != *':='* ]] && [[ $cur != *'`'* ]]; then399    cur=${cur:0:${#cur}-${#trigger}}400401    selected=$(FZF_DEFAULT_OPTS="--height ${FZF_TMUX_HEIGHT:-40%} --reverse --bind=ctrl-z:ignore ${FZF_DEFAULT_OPTS-} ${FZF_COMPLETION_OPTS-} $str_arg" __fzf_comprun "${rest[0]}" "${args[@]}" -q "$cur" | $post | command tr '\n' ' ')402    selected=${selected% } # Strip trailing space not to repeat "-o nospace"403    if [[ -n "$selected" ]]; then404      COMPREPLY=("$selected")405    else406      COMPREPLY=("$cur")407    fi408    printf '\e[5n'409    return 0410  else411    _fzf_handle_dynamic_completion "$cmd" "${rest[@]}"412  fi413}414415_fzf_path_completion() {416  __fzf_generic_path_completion _fzf_compgen_path "-m" "" "$@"417}418419# Deprecated. No file only completion.420_fzf_file_completion() {421  _fzf_path_completion "$@"422}423424_fzf_dir_completion() {425  __fzf_generic_path_completion _fzf_compgen_dir "" "/" "$@"426}427428_fzf_complete_kill() {429  _fzf_proc_completion "$@"430}431432_fzf_proc_completion() {433  _fzf_complete -m --header-lines=1 --preview 'echo {}' --preview-window down:3:wrap --min-height 15 -- "$@" < <(434    command ps -eo user,pid,ppid,start,time,command 2> /dev/null ||435      command ps -eo user,pid,ppid,time,args # For BusyBox436  )437}438439_fzf_proc_completion_post() {440  command awk '{print $2}'441}442443# To use custom hostname lists, override __fzf_list_hosts.444# The function is expected to print hostnames, one per line as well as in the445# desired sorting and with any duplicates removed, to standard output.446#447# e.g.448#   # Use bash-completions鈥檚 _known_hosts_real() for getting the list of hosts449#   __fzf_list_hosts() {450#     # Set the local attribute for any non-local variable that is set by _known_hosts_real()451#     local COMPREPLY=()452#     _known_hosts_real ''453#     printf '%s\n' "${COMPREPLY[@]}" | command sort -u --version-sort454#   }455if ! declare -F __fzf_list_hosts > /dev/null; then456  __fzf_list_hosts() {457    command cat <(command tail -n +1 ~/.ssh/config ~/.ssh/config.d/* /etc/ssh/ssh_config 2> /dev/null | command grep -i '^\s*host\(name\)\? ' | command awk '{for (i = 2; i <= NF; i++) print $1 " " $i}' | command grep -v '[*?%]') \458      <(command grep -oE '^[[a-z0-9.,:-]+' ~/.ssh/known_hosts 2> /dev/null | command tr ',' '\n' | command tr -d '[' | command awk '{ print $1 " " $1 }') \459      <(command grep -v '^\s*\(#\|$\)' /etc/hosts 2> /dev/null | command grep -Fv '0.0.0.0' | command sed 's/#.*//') |460      command awk '{for (i = 2; i <= NF; i++) print $i}' | command sort -u461  }462fi463464_fzf_host_completion() {465  _fzf_complete +m -- "$@" < <(__fzf_list_hosts)466}467468# Values for $1 $2 $3 are described here469# https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion.html470# > the first argument ($1) is the name of the command whose arguments are being completed,471# > the second argument ($2) is the word being completed,472# > and the third argument ($3) is the word preceding the word being completed on the current command line.473_fzf_complete_ssh() {474  case $3 in475    -i|-F|-E)476      _fzf_path_completion "$@"477      ;;478    *)479      local user=480      [[ "$2" =~ '@' ]] && user="${2%%@*}@"481      _fzf_complete +m -- "$@" < <(__fzf_list_hosts | command awk -v user="$user" '{print user $0}')482      ;;483  esac484}485486_fzf_var_completion() {487  _fzf_complete -m -- "$@" < <(488    declare -xp | command sed -En 's|^declare [^ ]+ ([^=]+).*|\1|p'489  )490}491492_fzf_alias_completion() {493  _fzf_complete -m -- "$@" < <(494    alias | command sed -En 's|^alias ([^=]+).*|\1|p'495  )496}497498# fzf options499complete -o default -F _fzf_opts_completion fzf500# fzf-tmux is a thin fzf wrapper that has only a few more options than fzf501# itself. As a quick improvement we take fzf's completion. Adding the few extra502# fzf-tmux specific options (like `-w WIDTH`) are left as a future patch.503complete -o default -F _fzf_opts_completion fzf-tmux504505d_cmds="${FZF_COMPLETION_DIR_COMMANDS:-cd pushd rmdir}"506a_cmds="507  awk bat cat diff diff3508  emacs emacsclient ex file ftp g++ gcc gvim head hg hx java509  javac ld less more mvim nvim patch perl python ruby510  sed sftp sort source tail tee uniq vi view vim wc xdg-open511  basename bunzip2 bzip2 chmod chown curl cp dirname du512  find git grep gunzip gzip hg jar513  ln ls mv open rm rsync scp514  svn tar unzip zip"515516# Preserve existing completion517__fzf_orig_completion < <(complete -p $d_cmds $a_cmds ssh 2> /dev/null)518519if type _completion_loader > /dev/null 2>&1; then520  _fzf_completion_loader=1521fi522523__fzf_defc() {524  local cmd func opts REPLY525  cmd="$1"526  func="$2"527  opts="$3"528  if __fzf_orig_completion_instantiate "$cmd" "$func"; then529    eval "$REPLY"530  else531    complete -F "$func" $opts "$cmd"532  fi533}534535# Anything536for cmd in $a_cmds; do537  __fzf_defc "$cmd" _fzf_path_completion "-o default -o bashdefault"538done539540# Directory541for cmd in $d_cmds; do542  __fzf_defc "$cmd" _fzf_dir_completion "-o nospace -o dirnames"543done544545# ssh546__fzf_defc ssh _fzf_complete_ssh "-o default -o bashdefault"547548unset cmd d_cmds a_cmds549550_fzf_setup_completion() {551  local kind fn cmd552  kind=$1553  fn=_fzf_${1}_completion554  if [[ $# -lt 2 ]] || ! type -t "$fn" > /dev/null; then555    echo "usage: ${FUNCNAME[0]} path|dir|var|alias|host|proc COMMANDS..."556    return 1557  fi558  shift559  __fzf_orig_completion < <(complete -p "$@" 2> /dev/null)560  for cmd in "$@"; do561    case "$kind" in562      dir)   __fzf_defc "$cmd" "$fn" "-o nospace -o dirnames" ;;563      var)   __fzf_defc "$cmd" "$fn" "-o default -o nospace -v" ;;564      alias) __fzf_defc "$cmd" "$fn" "-a" ;;565      *)     __fzf_defc "$cmd" "$fn" "-o default -o bashdefault" ;;566    esac567  done568}569570# Environment variables / Aliases / Hosts / Process571_fzf_setup_completion 'var'   export unset printenv572_fzf_setup_completion 'alias' unalias573_fzf_setup_completion 'host'  telnet574_fzf_setup_completion 'proc'  kill