Skip to content
Myr

completion.bash

This file

Path

shell/completion.bash

625 lines · 18.0 KiB · Shell

Last changed by

[bash] Fix $FZF_COMPLETION_{DIR,PATH}_OPTS to support non-trivial argumentsJunegunn Choibefore adoption923c3a8

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)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# To redraw line after fzf closes (printf '\e[5n')35bind '"\e[0n": redraw-current-line' 2> /dev/null3637__fzf_defaults() {38  # $1: Prepend to FZF_DEFAULT_OPTS_FILE and FZF_DEFAULT_OPTS39  # $2: Append to FZF_DEFAULT_OPTS_FILE and FZF_DEFAULT_OPTS40  echo "--height ${FZF_TMUX_HEIGHT:-40%} --min-height 20+ --bind=ctrl-z:ignore $1"41  command cat "${FZF_DEFAULT_OPTS_FILE-}" 2> /dev/null42  echo "${FZF_DEFAULT_OPTS-} $2"43}4445__fzf_comprun() {46  if [[ "$(type -t _fzf_comprun 2>&1)" = function ]]; then47    _fzf_comprun "$@"48  elif [[ -n "${TMUX_PANE-}" ]] && { [[ "${FZF_TMUX:-0}" != 0 ]] || [[ -n "${FZF_TMUX_OPTS-}" ]]; }; then49    shift50    fzf-tmux ${FZF_TMUX_OPTS:--d${FZF_TMUX_HEIGHT:-40%}} -- "$@"51  else52    shift53    fzf "$@"54  fi55}5657__fzf_orig_completion() {58  local l comp f cmd59  while read -r l; do60    if [[ "$l" =~ ^(.*\ -F)\ *([^ ]*).*\ ([^ ]*)$ ]]; then61      comp="${BASH_REMATCH[1]}"62      f="${BASH_REMATCH[2]}"63      cmd="${BASH_REMATCH[3]}"64      [[ "$f" = _fzf_* ]] && continue65      printf -v "_fzf_orig_completion_${cmd//[^A-Za-z0-9_]/_}" "%s" "${comp} %s ${cmd} #${f}"66      if [[ "$l" = *" -o nospace "* ]] && [[ ! "${__fzf_nospace_commands-}" = *" $cmd "* ]]; then67        __fzf_nospace_commands="${__fzf_nospace_commands-} $cmd "68      fi69    fi70  done71}7273# @param $1 cmd - Command name for which the original completion is searched74# @var[out] REPLY - Original function name is returned75__fzf_orig_completion_get_orig_func() {76  local cmd orig_var orig77  cmd=$178  orig_var="_fzf_orig_completion_${cmd//[^A-Za-z0-9_]/_}"79  orig="${!orig_var-}"80  REPLY="${orig##*#}"81  [[ $REPLY ]] && type "$REPLY" &> /dev/null82}8384# @param $1 cmd - Command name for which the original completion is searched85# @param $2 func - Fzf's completion function to replace the original function86# @var[out] REPLY - Completion setting is returned as a string to "eval"87__fzf_orig_completion_instantiate() {88  local cmd func orig_var orig89  cmd=$190  func=$291  orig_var="_fzf_orig_completion_${cmd//[^A-Za-z0-9_]/_}"92  orig="${!orig_var-}"93  orig="${orig%#*}"94  [[ $orig == *' %s '* ]] || return 195  printf -v REPLY "$orig" "$func"96}9798_fzf_opts_completion() {99  local cur prev opts100  COMPREPLY=()101  cur="${COMP_WORDS[COMP_CWORD]}"102  prev="${COMP_WORDS[COMP_CWORD-1]}"103  opts="104    +c --no-color105    +i --no-ignore-case106    +s --no-sort107    +x --no-extended108    --ansi109    --bash110    --bind111    --border112    --border-label113    --border-label-pos114    --color115    --cycle116    --disabled117    --ellipsis118    --expect119    --filepath-word120    --fish121    --header122    --header-first123    --header-lines124    --height125    --highlight-line126    --history127    --history-size128    --hscroll-off129    --info130    --jump-labels131    --keep-right132    --layout133    --listen134    --listen-unsafe135    --literal136    --man137    --margin138    --marker139    --min-height140    --no-bold141    --no-clear142    --no-hscroll143    --no-mouse144    --no-scrollbar145    --no-separator146    --no-unicode147    --padding148    --pointer149    --preview150    --preview-label151    --preview-label-pos152    --preview-window153    --print-query154    --print0155    --prompt156    --read0157    --reverse158    --scheme159    --scroll-off160    --separator161    --sync162    --tabstop163    --tac164    --tiebreak165    --tmux166    --track167    --version168    --with-nth169    --with-shell170    --wrap171    --zsh172    -0 --exit-0173    -1 --select-1174    -d --delimiter175    -e --exact176    -f --filter177    -h --help178    -i --ignore-case179    -m --multi180    -n --nth181    -q --query182    --"183184  case "${prev}" in185  --scheme)186    COMPREPLY=( $(compgen -W "default path history" -- "$cur") )187    return 0188    ;;189  --tiebreak)190    COMPREPLY=( $(compgen -W "length chunk begin end index" -- "$cur") )191    return 0192    ;;193  --color)194    COMPREPLY=( $(compgen -W "dark light 16 bw no" -- "$cur") )195    return 0196    ;;197  --layout)198    COMPREPLY=( $(compgen -W "default reverse reverse-list" -- "$cur") )199    return 0200    ;;201  --info)202    COMPREPLY=( $(compgen -W "default right hidden inline inline-right" -- "$cur") )203    return 0204    ;;205  --preview-window)206    COMPREPLY=( $(compgen -W "207      default208      hidden209      nohidden210      wrap211      nowrap212      cycle213      nocycle214      up top215      down bottom216      left217      right218      rounded border border-rounded219      sharp border-sharp220      border-bold221      border-block222      border-thinblock223      border-double224      noborder border-none225      border-horizontal226      border-vertical227      border-up border-top228      border-down border-bottom229      border-left230      border-right231      follow232      nofollow" -- "$cur") )233    return 0234    ;;235  --border)236    COMPREPLY=( $(compgen -W "rounded sharp bold block thinblock double horizontal vertical top bottom left right none" -- "$cur") )237    return 0238    ;;239  --border-label-pos|--preview-label-pos)240    COMPREPLY=( $(compgen -W "center bottom top" -- "$cur") )241    return 0242    ;;243  esac244245  if [[ "$cur" =~ ^-|\+ ]]; then246    COMPREPLY=( $(compgen -W "${opts}" -- "$cur") )247    return 0248  fi249250  return 0251}252253_fzf_handle_dynamic_completion() {254  local cmd ret REPLY orig_cmd orig_complete255  cmd="$1"256  shift257  orig_cmd="$1"258  if __fzf_orig_completion_get_orig_func "$cmd"; then259    "$REPLY" "$@"260  elif [[ -n "${_fzf_completion_loader-}" ]]; then261    orig_complete=$(complete -p "$orig_cmd" 2> /dev/null)262    $_fzf_completion_loader "$@"263    ret=$?264    # _completion_loader may not have updated completion for the command265    if [[ "$(complete -p "$orig_cmd" 2> /dev/null)" != "$orig_complete" ]]; then266      __fzf_orig_completion < <(complete -p "$orig_cmd" 2> /dev/null)267      __fzf_orig_completion_get_orig_func "$cmd" || ret=1268269      # Update orig_complete by _fzf_orig_completion entry270      [[ $orig_complete =~ ' -F '(_fzf_[^ ]+)' ' ]] &&271        __fzf_orig_completion_instantiate "$cmd" "${BASH_REMATCH[1]}" &&272        orig_complete=$REPLY273274      if [[ "${__fzf_nospace_commands-}" = *" $orig_cmd "* ]]; then275        eval "${orig_complete/ -F / -o nospace -F }"276      else277        eval "$orig_complete"278      fi279    fi280    [[ $ret -eq 0 ]] && return 124281    return $ret282  fi283}284285__fzf_generic_path_completion() {286  local cur base dir leftover matches trigger cmd287  cmd="${COMP_WORDS[0]}"288  if [[ $cmd == \\* ]]; then289    cmd="${cmd:1}"290  fi291  COMPREPLY=()292  trigger=${FZF_COMPLETION_TRIGGER-'**'}293  [[ $COMP_CWORD -ge 0 ]] && cur="${COMP_WORDS[COMP_CWORD]}"294  if [[ "$cur" == *"$trigger" ]] && [[ $cur != *'$('* ]] && [[ $cur != *':='* ]] && [[ $cur != *'`'* ]]; then295    base=${cur:0:${#cur}-${#trigger}}296    eval "base=$base" 2> /dev/null || return297298    dir=299    [[ $base = *"/"* ]] && dir="$base"300    while true; do301      if [[ -z "$dir" ]] || [[ -d "$dir" ]]; then302        leftover=${base/#"$dir"}303        leftover=${leftover/#\/}304        [[ -z "$dir" ]] && dir='.'305        [[ "$dir" != "/" ]] && dir="${dir/%\//}"306        matches=$(307          export FZF_DEFAULT_OPTS=$(__fzf_defaults "--reverse --scheme=path" "${FZF_COMPLETION_OPTS-} $2")308          unset FZF_DEFAULT_COMMAND FZF_DEFAULT_OPTS_FILE309          if declare -F "$1" > /dev/null; then310            eval "$1 $(printf %q "$dir")" | __fzf_comprun "$4" -q "$leftover"311          else312            if [[ $1 =~ dir ]]; then313              walker=dir,follow314              eval "rest=(${FZF_COMPLETION_DIR_OPTS-})"315            else316              walker=file,dir,follow,hidden317              eval "rest=(${FZF_COMPLETION_PATH_OPTS-})"318            fi319            __fzf_comprun "$4" -q "$leftover" --walker "$walker" --walker-root="$dir" "${rest[@]}"320          fi | while read -r item; do321            printf "%q " "${item%$3}$3"322          done323        )324        matches=${matches% }325        [[ -z "$3" ]] && [[ "${__fzf_nospace_commands-}" = *" ${COMP_WORDS[0]} "* ]] && matches="$matches "326        if [[ -n "$matches" ]]; then327          COMPREPLY=( "$matches" )328        else329          COMPREPLY=( "$cur" )330        fi331        printf '\e[5n'332        return 0333      fi334      dir=$(command dirname "$dir")335      [[ "$dir" =~ /$ ]] || dir="$dir"/336    done337  else338    shift339    shift340    shift341    _fzf_handle_dynamic_completion "$cmd" "$@"342  fi343}344345_fzf_complete() {346  # Split arguments around --347  local args rest str_arg i sep348  args=("$@")349  sep=350  for i in "${!args[@]}"; do351    if [[ "${args[$i]}" = -- ]]; then352      sep=$i353      break354    fi355  done356  if [[ -n "$sep" ]]; then357    str_arg=358    rest=("${args[@]:$((sep + 1)):${#args[@]}}")359    args=("${args[@]:0:$sep}")360  else361    str_arg=$1362    args=()363    shift364    rest=("$@")365  fi366367  local cur selected trigger cmd post368  post="$(caller 0 | command awk '{print $2}')_post"369  type -t "$post" > /dev/null 2>&1 || post='command cat'370371  trigger=${FZF_COMPLETION_TRIGGER-'**'}372  cmd="${COMP_WORDS[0]}"373  cur="${COMP_WORDS[COMP_CWORD]}"374  if [[ "$cur" == *"$trigger" ]] && [[ $cur != *'$('* ]] && [[ $cur != *':='* ]] && [[ $cur != *'`'* ]]; then375    cur=${cur:0:${#cur}-${#trigger}}376377    selected=$(378      FZF_DEFAULT_OPTS=$(__fzf_defaults "--reverse" "${FZF_COMPLETION_OPTS-} $str_arg") \379      FZF_DEFAULT_OPTS_FILE='' \380        __fzf_comprun "${rest[0]}" "${args[@]}" -q "$cur" | eval "$post" | command tr '\n' ' ')381    selected=${selected% } # Strip trailing space not to repeat "-o nospace"382    if [[ -n "$selected" ]]; then383      COMPREPLY=("$selected")384    else385      COMPREPLY=("$cur")386    fi387    printf '\e[5n'388    return 0389  else390    _fzf_handle_dynamic_completion "$cmd" "${rest[@]}"391  fi392}393394_fzf_path_completion() {395  __fzf_generic_path_completion _fzf_compgen_path "-m" "" "$@"396}397398# Deprecated. No file only completion.399_fzf_file_completion() {400  _fzf_path_completion "$@"401}402403_fzf_dir_completion() {404  __fzf_generic_path_completion _fzf_compgen_dir "" "/" "$@"405}406407_fzf_complete_kill() {408  _fzf_proc_completion "$@"409}410411_fzf_proc_completion() {412  local transformer413  transformer='414    if [[ $FZF_KEY =~ ctrl|alt|shift ]] && [[ -n $FZF_NTH ]]; then415      nths=( ${FZF_NTH//,/ } )416      new_nths=()417      found=0418      for nth in ${nths[@]}; do419        if [[ $nth = $FZF_CLICK_HEADER_NTH ]]; then420          found=1421        else422          new_nths+=($nth)423        fi424      done425      [[ $found = 0 ]] && new_nths+=($FZF_CLICK_HEADER_NTH)426      new_nths=${new_nths[*]}427      new_nths=${new_nths// /,}428      echo "change-nth($new_nths)+change-prompt($new_nths> )"429    else430      if [[ $FZF_NTH = $FZF_CLICK_HEADER_NTH ]]; then431        echo "change-nth()+change-prompt(> )"432      else433        echo "change-nth($FZF_CLICK_HEADER_NTH)+change-prompt($FZF_CLICK_HEADER_WORD> )"434      fi435    fi436  '437  _fzf_complete -m --header-lines=1 --no-preview --wrap --color fg:dim,nth:regular \438    --bind "click-header:transform:$transformer" -- "$@" < <(439    command ps -eo user,pid,ppid,start,time,command 2> /dev/null ||440      command ps -eo user,pid,ppid,time,args 2> /dev/null || # For BusyBox441      command ps --everyone --full --windows # For cygwin442  )443}444445_fzf_proc_completion_post() {446  command awk '{print $2}'447}448449# To use custom hostname lists, override __fzf_list_hosts.450# The function is expected to print hostnames, one per line as well as in the451# desired sorting and with any duplicates removed, to standard output.452#453# e.g.454#   # Use bash-completions’s _known_hosts_real() for getting the list of hosts455#   __fzf_list_hosts() {456#     # Set the local attribute for any non-local variable that is set by _known_hosts_real()457#     local COMPREPLY=()458#     _known_hosts_real ''459#     printf '%s\n' "${COMPREPLY[@]}" | command sort -u --version-sort460#   }461if ! declare -F __fzf_list_hosts > /dev/null; then462  __fzf_list_hosts() {463    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 '[*?%]') \464      <(command grep -oE '^[[a-z0-9.,:-]+' ~/.ssh/known_hosts 2> /dev/null | command tr ',' '\n' | command tr -d '[' | command awk '{ print $1 " " $1 }') \465      <(command grep -v '^\s*\(#\|$\)' /etc/hosts 2> /dev/null | command grep -Fv '0.0.0.0' | command sed 's/#.*//') |466      command awk '{for (i = 2; i <= NF; i++) print $i}' | command sort -u467  }468fi469470_fzf_host_completion() {471  _fzf_complete +m -- "$@" < <(__fzf_list_hosts)472}473474# Values for $1 $2 $3 are described here475# https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion.html476# > the first argument ($1) is the name of the command whose arguments are being completed,477# > the second argument ($2) is the word being completed,478# > and the third argument ($3) is the word preceding the word being completed on the current command line.479_fzf_complete_ssh() {480  case $3 in481    -i|-F|-E)482      _fzf_path_completion "$@"483      ;;484    *)485      local user=486      [[ "$2" =~ '@' ]] && user="${2%%@*}@"487      _fzf_complete +m -- "$@" < <(__fzf_list_hosts | command awk -v user="$user" '{print user $0}')488      ;;489  esac490}491492_fzf_var_completion() {493  _fzf_complete -m -- "$@" < <(494    declare -xp | command sed -En 's|^declare [^ ]+ ([^=]+).*|\1|p'495  )496}497498_fzf_alias_completion() {499  _fzf_complete -m -- "$@" < <(500    alias | command sed -En 's|^alias ([^=]+).*|\1|p'501  )502}503504# fzf options505complete -o default -F _fzf_opts_completion fzf506# fzf-tmux is a thin fzf wrapper that has only a few more options than fzf507# itself. As a quick improvement we take fzf's completion. Adding the few extra508# fzf-tmux specific options (like `-w WIDTH`) are left as a future patch.509complete -o default -F _fzf_opts_completion fzf-tmux510511# Default path completion512__fzf_default_completion() {513  __fzf_generic_path_completion _fzf_compgen_path "-m" "" "$@"514515  # Dynamic completion loader has updated the completion for the command516  if [[ $? -eq 124 ]]; then517    # We trigger _fzf_setup_completion so that fuzzy completion for the command518    # still works. However, loader can update the completion for multiple519    # commands at once, and fuzzy completion will no longer work for those520    # other commands. e.g. pytest -> py.test, pytest-2, pytest-3, etc521    _fzf_setup_completion path "$1"522    return 124523  fi524}525526# Set fuzzy path completion as the default completion for all commands.527# We can't set up default completion,528# 1. if it's already set up by another script529# 2. or if the current version of bash doesn't support -D option530complete | command grep -q __fzf_default_completion ||531  complete | command grep -- '-D$' | command grep -qv _comp_complete_load ||532  complete -D -F __fzf_default_completion -o default -o bashdefault 2> /dev/null533534d_cmds="${FZF_COMPLETION_DIR_COMMANDS-cd pushd rmdir}"535536# NOTE: $FZF_COMPLETION_PATH_COMMANDS and $FZF_COMPLETION_VAR_COMMANDS are537# undocumented and subject to change in the future.538#539# NOTE: Although we have default completion, we still need to set up completion540# for each command in case they already have completion set up by another script.541a_cmds="${FZF_COMPLETION_PATH_COMMANDS-"542  awk bat cat code diff diff3543  emacs emacsclient ex file ftp g++ gcc gvim head hg hx java544  javac ld less more mvim nvim patch perl python ruby545  sed sftp sort source tail tee uniq vi view vim wc xdg-open546  basename bunzip2 bzip2 chmod chown curl cp dirname du547  find git grep gunzip gzip hg jar548  ln ls mv open rm rsync scp549  svn tar unzip zip"}"550v_cmds="${FZF_COMPLETION_VAR_COMMANDS-export unset printenv}"551552# Preserve existing completion553__fzf_orig_completion < <(complete -p $d_cmds $a_cmds $v_cmds unalias kill ssh 2> /dev/null)554555if type _comp_load > /dev/null 2>&1; then556  # _comp_load was added in bash-completion 2.12 to replace _completion_loader.557  # We use it without -D option so that it does not use _comp_complete_minimal as the fallback.558  _fzf_completion_loader=_comp_load559elif type __load_completion > /dev/null 2>&1; then560  # In bash-completion 2.11, _completion_loader internally calls __load_completion561  # and if it returns a non-zero status, it sets the default 'minimal' completion.562  _fzf_completion_loader=__load_completion563elif type _completion_loader > /dev/null 2>&1; then564  _fzf_completion_loader=_completion_loader565fi566567__fzf_defc() {568  local cmd func opts REPLY569  cmd="$1"570  func="$2"571  opts="$3"572  if __fzf_orig_completion_instantiate "$cmd" "$func"; then573    eval "$REPLY"574  else575    complete -F "$func" $opts "$cmd"576  fi577}578579# Anything580for cmd in $a_cmds; do581  __fzf_defc "$cmd" _fzf_path_completion "-o default -o bashdefault"582done583584# Directory585for cmd in $d_cmds; do586  __fzf_defc "$cmd" _fzf_dir_completion "-o bashdefault -o nospace -o dirnames"587done588589# Variables590for cmd in $v_cmds; do591  __fzf_defc "$cmd" _fzf_var_completion "-o default -o nospace -v"592done593594# Aliases595__fzf_defc unalias _fzf_alias_completion "-a"596597# Processes598__fzf_defc kill _fzf_proc_completion "-o default -o bashdefault"599600# ssh601__fzf_defc ssh _fzf_complete_ssh "-o default -o bashdefault"602603unset cmd d_cmds a_cmds v_cmds604605_fzf_setup_completion() {606  local kind fn cmd607  kind=$1608  fn=_fzf_${1}_completion609  if [[ $# -lt 2 ]] || ! type -t "$fn" > /dev/null; then610    echo "usage: ${FUNCNAME[0]} path|dir|var|alias|host|proc COMMANDS..."611    return 1612  fi613  shift614  __fzf_orig_completion < <(complete -p "$@" 2> /dev/null)615  for cmd in "$@"; do616    case "$kind" in617      dir)   __fzf_defc "$cmd" "$fn" "-o nospace -o dirnames" ;;618      var)   __fzf_defc "$cmd" "$fn" "-o default -o nospace -v" ;;619      alias) __fzf_defc "$cmd" "$fn" "-a" ;;620      *)     __fzf_defc "$cmd" "$fn" "-o default -o bashdefault" ;;621    esac622  done623}624625fi