Skip to content
Myr

completion.bash

This file

Path

shell/completion.bash

599 lines · 17.1 KiB · Shell

Last changed by

Use eval to evaluate $post variable as command. (#4023)Thomas Martitzbefore adoption97f1dae

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%} --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              rest=${FZF_COMPLETION_DIR_OPTS-}315            else316              walker=file,dir,follow,hidden317              rest=${FZF_COMPLETION_PATH_OPTS-}318            fi319            __fzf_comprun "$4" -q "$leftover" --walker "$walker" --walker-root="$dir" $rest320          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  _fzf_complete -m --header-lines=1 --no-preview --wrap -- "$@" < <(413    command ps -eo user,pid,ppid,start,time,command 2> /dev/null ||414      command ps -eo user,pid,ppid,time,args 2> /dev/null || # For BusyBox415      command ps --everyone --full --windows # For cygwin416  )417}418419_fzf_proc_completion_post() {420  command awk '{print $2}'421}422423# To use custom hostname lists, override __fzf_list_hosts.424# The function is expected to print hostnames, one per line as well as in the425# desired sorting and with any duplicates removed, to standard output.426#427# e.g.428#   # Use bash-completions’s _known_hosts_real() for getting the list of hosts429#   __fzf_list_hosts() {430#     # Set the local attribute for any non-local variable that is set by _known_hosts_real()431#     local COMPREPLY=()432#     _known_hosts_real ''433#     printf '%s\n' "${COMPREPLY[@]}" | command sort -u --version-sort434#   }435if ! declare -F __fzf_list_hosts > /dev/null; then436  __fzf_list_hosts() {437    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 '[*?%]') \438      <(command grep -oE '^[[a-z0-9.,:-]+' ~/.ssh/known_hosts 2> /dev/null | command tr ',' '\n' | command tr -d '[' | command awk '{ print $1 " " $1 }') \439      <(command grep -v '^\s*\(#\|$\)' /etc/hosts 2> /dev/null | command grep -Fv '0.0.0.0' | command sed 's/#.*//') |440      command awk '{for (i = 2; i <= NF; i++) print $i}' | command sort -u441  }442fi443444_fzf_host_completion() {445  _fzf_complete +m -- "$@" < <(__fzf_list_hosts)446}447448# Values for $1 $2 $3 are described here449# https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion.html450# > the first argument ($1) is the name of the command whose arguments are being completed,451# > the second argument ($2) is the word being completed,452# > and the third argument ($3) is the word preceding the word being completed on the current command line.453_fzf_complete_ssh() {454  case $3 in455    -i|-F|-E)456      _fzf_path_completion "$@"457      ;;458    *)459      local user=460      [[ "$2" =~ '@' ]] && user="${2%%@*}@"461      _fzf_complete +m -- "$@" < <(__fzf_list_hosts | command awk -v user="$user" '{print user $0}')462      ;;463  esac464}465466_fzf_var_completion() {467  _fzf_complete -m -- "$@" < <(468    declare -xp | command sed -En 's|^declare [^ ]+ ([^=]+).*|\1|p'469  )470}471472_fzf_alias_completion() {473  _fzf_complete -m -- "$@" < <(474    alias | command sed -En 's|^alias ([^=]+).*|\1|p'475  )476}477478# fzf options479complete -o default -F _fzf_opts_completion fzf480# fzf-tmux is a thin fzf wrapper that has only a few more options than fzf481# itself. As a quick improvement we take fzf's completion. Adding the few extra482# fzf-tmux specific options (like `-w WIDTH`) are left as a future patch.483complete -o default -F _fzf_opts_completion fzf-tmux484485# Default path completion486__fzf_default_completion() {487  __fzf_generic_path_completion _fzf_compgen_path "-m" "" "$@"488489  # Dynamic completion loader has updated the completion for the command490  if [[ $? -eq 124 ]]; then491    # We trigger _fzf_setup_completion so that fuzzy completion for the command492    # still works. However, loader can update the completion for multiple493    # commands at once, and fuzzy completion will no longer work for those494    # other commands. e.g. pytest -> py.test, pytest-2, pytest-3, etc495    _fzf_setup_completion path "$1"496    return 124497  fi498}499500# Set fuzzy path completion as the default completion for all commands.501# We can't set up default completion,502# 1. if it's already set up by another script503# 2. or if the current version of bash doesn't support -D option504complete | command grep -q __fzf_default_completion ||505  complete | command grep -- '-D$' | command grep -qv _comp_complete_load ||506  complete -D -F __fzf_default_completion -o default -o bashdefault 2> /dev/null507508d_cmds="${FZF_COMPLETION_DIR_COMMANDS-cd pushd rmdir}"509510# NOTE: $FZF_COMPLETION_PATH_COMMANDS and $FZF_COMPLETION_VAR_COMMANDS are511# undocumented and subject to change in the future.512#513# NOTE: Although we have default completion, we still need to set up completion514# for each command in case they already have completion set up by another script.515a_cmds="${FZF_COMPLETION_PATH_COMMANDS-"516  awk bat cat code diff diff3517  emacs emacsclient ex file ftp g++ gcc gvim head hg hx java518  javac ld less more mvim nvim patch perl python ruby519  sed sftp sort source tail tee uniq vi view vim wc xdg-open520  basename bunzip2 bzip2 chmod chown curl cp dirname du521  find git grep gunzip gzip hg jar522  ln ls mv open rm rsync scp523  svn tar unzip zip"}"524v_cmds="${FZF_COMPLETION_VAR_COMMANDS-export unset printenv}"525526# Preserve existing completion527__fzf_orig_completion < <(complete -p $d_cmds $a_cmds $v_cmds unalias kill ssh 2> /dev/null)528529if type _comp_load > /dev/null 2>&1; then530  # _comp_load was added in bash-completion 2.12 to replace _completion_loader.531  # We use it without -D option so that it does not use _comp_complete_minimal as the fallback.532  _fzf_completion_loader=_comp_load533elif type __load_completion > /dev/null 2>&1; then534  # In bash-completion 2.11, _completion_loader internally calls __load_completion535  # and if it returns a non-zero status, it sets the default 'minimal' completion.536  _fzf_completion_loader=__load_completion537elif type _completion_loader > /dev/null 2>&1; then538  _fzf_completion_loader=_completion_loader539fi540541__fzf_defc() {542  local cmd func opts REPLY543  cmd="$1"544  func="$2"545  opts="$3"546  if __fzf_orig_completion_instantiate "$cmd" "$func"; then547    eval "$REPLY"548  else549    complete -F "$func" $opts "$cmd"550  fi551}552553# Anything554for cmd in $a_cmds; do555  __fzf_defc "$cmd" _fzf_path_completion "-o default -o bashdefault"556done557558# Directory559for cmd in $d_cmds; do560  __fzf_defc "$cmd" _fzf_dir_completion "-o bashdefault -o nospace -o dirnames"561done562563# Variables564for cmd in $v_cmds; do565  __fzf_defc "$cmd" _fzf_var_completion "-o default -o nospace -v"566done567568# Aliases569__fzf_defc unalias _fzf_alias_completion "-a"570571# Processes572__fzf_defc kill _fzf_proc_completion "-o default -o bashdefault"573574# ssh575__fzf_defc ssh _fzf_complete_ssh "-o default -o bashdefault"576577unset cmd d_cmds a_cmds v_cmds578579_fzf_setup_completion() {580  local kind fn cmd581  kind=$1582  fn=_fzf_${1}_completion583  if [[ $# -lt 2 ]] || ! type -t "$fn" > /dev/null; then584    echo "usage: ${FUNCNAME[0]} path|dir|var|alias|host|proc COMMANDS..."585    return 1586  fi587  shift588  __fzf_orig_completion < <(complete -p "$@" 2> /dev/null)589  for cmd in "$@"; do590    case "$kind" in591      dir)   __fzf_defc "$cmd" "$fn" "-o nospace -o dirnames" ;;592      var)   __fzf_defc "$cmd" "$fn" "-o default -o nospace -v" ;;593      alias) __fzf_defc "$cmd" "$fn" "-a" ;;594      *)     __fzf_defc "$cmd" "$fn" "-o default -o bashdefault" ;;595    esac596  done597}598599fi