Skip to content
Myr

completion.bash

This file

Path

shell/completion.bash

690 lines · 20.0 KiB · Shell

Last changed by

Apply shfmt to bash script files (make fmt)Junegunn Choibefore adoptione8cb315

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#----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 ]] && ((d >= 20230302 && (x * 1000 + y) * 1000 + z >= 1003004)) && __fzf_awk=mawk55    fi56  fi57  LC_ALL=C exec "$__fzf_awk" "$@"58}59#----END INCLUDE6061__fzf_comprun() {62  if [[ "$(type -t _fzf_comprun 2>&1)" == function ]]; then63    _fzf_comprun "$@"64  elif [[ -n ${TMUX_PANE-} ]] && { [[ ${FZF_TMUX:-0} != 0 ]] || [[ -n ${FZF_TMUX_OPTS-} ]]; }; then65    shift66    fzf-tmux ${FZF_TMUX_OPTS:--d${FZF_TMUX_HEIGHT:-40%}} -- "$@"67  else68    shift69    fzf "$@"70  fi71}7273__fzf_orig_completion() {74  local l comp f cmd75  while read -r l; do76    if [[ $l =~ ^(.*\ -F)\ *([^ ]*).*\ ([^ ]*)$ ]]; then77      comp="${BASH_REMATCH[1]}"78      f="${BASH_REMATCH[2]}"79      cmd="${BASH_REMATCH[3]}"80      [[ $f == _fzf_* ]] && continue81      printf -v "_fzf_orig_completion_${cmd//[^A-Za-z0-9_]/_}" "%s" "${comp} %s ${cmd} #${f}"82      if [[ $l == *" -o nospace "* ]] && [[ ${__fzf_nospace_commands-} != *" $cmd "* ]]; then83        __fzf_nospace_commands="${__fzf_nospace_commands-} $cmd "84      fi85    fi86  done87}8889# @param $1 cmd - Command name for which the original completion is searched90# @var[out] REPLY - Original function name is returned91__fzf_orig_completion_get_orig_func() {92  local cmd orig_var orig93  cmd=$194  orig_var="_fzf_orig_completion_${cmd//[^A-Za-z0-9_]/_}"95  orig="${!orig_var-}"96  REPLY="${orig##*#}"97  [[ $REPLY ]] && type "$REPLY" &> /dev/null98}99100# @param $1 cmd - Command name for which the original completion is searched101# @param $2 func - Fzf's completion function to replace the original function102# @var[out] REPLY - Completion setting is returned as a string to "eval"103__fzf_orig_completion_instantiate() {104  local cmd func orig_var orig105  cmd=$1106  func=$2107  orig_var="_fzf_orig_completion_${cmd//[^A-Za-z0-9_]/_}"108  orig="${!orig_var-}"109  orig="${orig%#*}"110  [[ $orig == *' %s '* ]] || return 1111  printf -v REPLY "$orig" "$func"112}113114_fzf_opts_completion() {115  local cur prev opts116  COMPREPLY=()117  cur="${COMP_WORDS[COMP_CWORD]}"118  prev="${COMP_WORDS[COMP_CWORD - 1]}"119  opts="120    +c --no-color121    +i --no-ignore-case122    +s --no-sort123    +x --no-extended124    --ansi125    --bash126    --bind127    --border128    --border-label129    --border-label-pos130    --color131    --cycle132    --disabled133    --ellipsis134    --expect135    --filepath-word136    --fish137    --header138    --header-first139    --header-lines140    --height141    --highlight-line142    --history143    --history-size144    --hscroll-off145    --info146    --jump-labels147    --keep-right148    --layout149    --listen150    --listen-unsafe151    --literal152    --man153    --margin154    --marker155    --min-height156    --no-bold157    --no-clear158    --no-hscroll159    --no-mouse160    --no-scrollbar161    --no-separator162    --no-unicode163    --padding164    --pointer165    --preview166    --preview-label167    --preview-label-pos168    --preview-window169    --print-query170    --print0171    --prompt172    --read0173    --reverse174    --scheme175    --scroll-off176    --separator177    --sync178    --tabstop179    --tac180    --tiebreak181    --tmux182    --track183    --version184    --with-nth185    --with-shell186    --wrap187    --zsh188    -0 --exit-0189    -1 --select-1190    -d --delimiter191    -e --exact192    -f --filter193    -h --help194    -i --ignore-case195    -m --multi196    -n --nth197    -q --query198    --"199200  case "${prev}" in201    --scheme)202      COMPREPLY=($(compgen -W "default path history" -- "$cur"))203      return 0204      ;;205    --tiebreak)206      COMPREPLY=($(compgen -W "length chunk begin end index" -- "$cur"))207      return 0208      ;;209    --color)210      COMPREPLY=($(compgen -W "dark light 16 bw no" -- "$cur"))211      return 0212      ;;213    --layout)214      COMPREPLY=($(compgen -W "default reverse reverse-list" -- "$cur"))215      return 0216      ;;217    --info)218      COMPREPLY=($(compgen -W "default right hidden inline inline-right" -- "$cur"))219      return 0220      ;;221    --preview-window)222      COMPREPLY=($(compgen -W "223      default224      hidden225      nohidden226      wrap227      nowrap228      cycle229      nocycle230      up top231      down bottom232      left233      right234      rounded border border-rounded235      sharp border-sharp236      border-bold237      border-block238      border-thinblock239      border-double240      noborder border-none241      border-horizontal242      border-vertical243      border-up border-top244      border-down border-bottom245      border-left246      border-right247      follow248      nofollow" -- "$cur"))249      return 0250      ;;251    --border)252      COMPREPLY=($(compgen -W "rounded sharp bold block thinblock double horizontal vertical top bottom left right none" -- "$cur"))253      return 0254      ;;255    --border-label-pos | --preview-label-pos)256      COMPREPLY=($(compgen -W "center bottom top" -- "$cur"))257      return 0258      ;;259  esac260261  if [[ $cur =~ ^-|\+ ]]; then262    COMPREPLY=($(compgen -W "${opts}" -- "$cur"))263    return 0264  fi265266  return 0267}268269_fzf_handle_dynamic_completion() {270  local cmd ret REPLY orig_cmd orig_complete271  cmd="$1"272  shift273  orig_cmd="$1"274  if __fzf_orig_completion_get_orig_func "$cmd"; then275    "$REPLY" "$@"276  elif [[ -n ${_fzf_completion_loader-} ]]; then277    orig_complete=$(complete -p "$orig_cmd" 2> /dev/null)278    $_fzf_completion_loader "$@"279    ret=$?280    # _completion_loader may not have updated completion for the command281    if [[ "$(complete -p "$orig_cmd" 2> /dev/null)" != "$orig_complete" ]]; then282      __fzf_orig_completion < <(complete -p "$orig_cmd" 2> /dev/null)283      __fzf_orig_completion_get_orig_func "$cmd" || ret=1284285      # Update orig_complete by _fzf_orig_completion entry286      [[ $orig_complete =~ ' -F '(_fzf_[^ ]+)' ' ]] &&287        __fzf_orig_completion_instantiate "$cmd" "${BASH_REMATCH[1]}" &&288        orig_complete=$REPLY289290      if [[ ${__fzf_nospace_commands-} == *" $orig_cmd "* ]]; then291        eval "${orig_complete/ -F / -o nospace -F }"292      else293        eval "$orig_complete"294      fi295    fi296    [[ $ret -eq 0 ]] && return 124297    return $ret298  fi299}300301__fzf_generic_path_completion() {302  local cur base dir leftover matches trigger cmd303  cmd="${COMP_WORDS[0]}"304  if [[ $cmd == \\* ]]; then305    cmd="${cmd:1}"306  fi307  COMPREPLY=()308  trigger=${FZF_COMPLETION_TRIGGER-'**'}309  [[ $COMP_CWORD -ge 0 ]] && cur="${COMP_WORDS[COMP_CWORD]}"310  if [[ $cur == *"$trigger" ]] && [[ $cur != *'$('* ]] && [[ $cur != *':='* ]] && [[ $cur != *'`'* ]]; then311    base=${cur:0:${#cur}-${#trigger}}312    eval "base=$base" 2> /dev/null || return313314    dir=315    [[ $base == *"/"* ]] && dir="$base"316    while true; do317      if [[ -z $dir ]] || [[ -d $dir ]]; then318        leftover=${base/#"$dir"/}319        leftover=${leftover/#\//}320        [[ -z $dir ]] && dir='.'321        [[ $dir != "/" ]] && dir="${dir/%\//}"322        matches=$(323          export FZF_DEFAULT_OPTS=$(__fzf_defaults "--reverse --scheme=path" "${FZF_COMPLETION_OPTS-} $2")324          unset FZF_DEFAULT_COMMAND FZF_DEFAULT_OPTS_FILE325          if declare -F "$1" > /dev/null; then326            eval "$1 $(printf %q "$dir")" | __fzf_comprun "$4" -q "$leftover"327          else328            if [[ $1 =~ dir ]]; then329              walker=dir,follow330              eval "rest=(${FZF_COMPLETION_DIR_OPTS-})"331            else332              walker=file,dir,follow,hidden333              eval "rest=(${FZF_COMPLETION_PATH_OPTS-})"334            fi335            __fzf_comprun "$4" -q "$leftover" --walker "$walker" --walker-root="$dir" "${rest[@]}"336          fi | while read -r item; do337            printf "%q " "${item%$3}$3"338          done339        )340        matches=${matches% }341        [[ -z $3 ]] && [[ ${__fzf_nospace_commands-} == *" ${COMP_WORDS[0]} "* ]] && matches="$matches "342        if [[ -n $matches ]]; then343          COMPREPLY=("$matches")344        else345          COMPREPLY=("$cur")346        fi347        # To redraw line after fzf closes (printf '\e[5n')348        bind '"\e[0n": redraw-current-line' 2> /dev/null349        printf '\e[5n'350        return 0351      fi352      dir=$(command dirname "$dir")353      [[ $dir =~ /$ ]] || dir="$dir"/354    done355  else356    shift357    shift358    shift359    _fzf_handle_dynamic_completion "$cmd" "$@"360  fi361}362363_fzf_complete() {364  # Split arguments around --365  local args rest str_arg i sep366  args=("$@")367  sep=368  for i in "${!args[@]}"; do369    if [[ ${args[$i]} == -- ]]; then370      sep=$i371      break372    fi373  done374  if [[ -n $sep ]]; then375    str_arg=376    rest=("${args[@]:$((sep + 1)):${#args[@]}}")377    args=("${args[@]:0:sep}")378  else379    str_arg=$1380    args=()381    shift382    rest=("$@")383  fi384385  local cur selected trigger cmd post386  post="$(caller 0 | __fzf_exec_awk '{print $2}')_post"387  type -t "$post" > /dev/null 2>&1 || post='command cat'388389  trigger=${FZF_COMPLETION_TRIGGER-'**'}390  cmd="${COMP_WORDS[0]}"391  cur="${COMP_WORDS[COMP_CWORD]}"392  if [[ $cur == *"$trigger" ]] && [[ $cur != *'$('* ]] && [[ $cur != *':='* ]] && [[ $cur != *'`'* ]]; then393    cur=${cur:0:${#cur}-${#trigger}}394395    selected=$(396      FZF_DEFAULT_OPTS=$(__fzf_defaults "--reverse" "${FZF_COMPLETION_OPTS-} $str_arg") \397      FZF_DEFAULT_OPTS_FILE='' \398        __fzf_comprun "${rest[0]}" "${args[@]}" -q "$cur" | eval "$post" | command tr '\n' ' '399    )400    selected=${selected% } # Strip trailing space not to repeat "-o nospace"401    if [[ -n $selected ]]; then402      COMPREPLY=("$selected")403    else404      COMPREPLY=("$cur")405    fi406    bind '"\e[0n": redraw-current-line' 2> /dev/null407    printf '\e[5n'408    return 0409  else410    _fzf_handle_dynamic_completion "$cmd" "${rest[@]}"411  fi412}413414_fzf_path_completion() {415  __fzf_generic_path_completion _fzf_compgen_path "-m" "" "$@"416}417418# Deprecated. No file only completion.419_fzf_file_completion() {420  _fzf_path_completion "$@"421}422423_fzf_dir_completion() {424  __fzf_generic_path_completion _fzf_compgen_dir "" "/" "$@"425}426427_fzf_complete_kill() {428  _fzf_proc_completion "$@"429}430431_fzf_proc_completion() {432  local transformer433  transformer='434    if [[ $FZF_KEY =~ ctrl|alt|shift ]] && [[ -n $FZF_NTH ]]; then435      nths=( ${FZF_NTH//,/ } )436      new_nths=()437      found=0438      for nth in ${nths[@]}; do439        if [[ $nth = $FZF_CLICK_HEADER_NTH ]]; then440          found=1441        else442          new_nths+=($nth)443        fi444      done445      [[ $found = 0 ]] && new_nths+=($FZF_CLICK_HEADER_NTH)446      new_nths=${new_nths[*]}447      new_nths=${new_nths// /,}448      echo "change-nth($new_nths)+change-prompt($new_nths> )"449    else450      if [[ $FZF_NTH = $FZF_CLICK_HEADER_NTH ]]; then451        echo "change-nth()+change-prompt(> )"452      else453        echo "change-nth($FZF_CLICK_HEADER_NTH)+change-prompt($FZF_CLICK_HEADER_WORD> )"454      fi455    fi456  '457  _fzf_complete -m --header-lines=1 --no-preview --wrap --color fg:dim,nth:regular \458    --bind "click-header:transform:$transformer" -- "$@" < <(459      command ps -eo user,pid,ppid,start,time,command 2> /dev/null ||460        command ps -eo user,pid,ppid,time,args 2> /dev/null || # For BusyBox461        command ps --everyone --full --windows                 # For cygwin462    )463}464465_fzf_proc_completion_post() {466  __fzf_exec_awk '{print $2}'467}468469# To use custom hostname lists, override __fzf_list_hosts.470# The function is expected to print hostnames, one per line as well as in the471# desired sorting and with any duplicates removed, to standard output.472#473# e.g.474#   # Use bash-completions’s _known_hosts_real() for getting the list of hosts475#   __fzf_list_hosts() {476#     # Set the local attribute for any non-local variable that is set by _known_hosts_real()477#     local COMPREPLY=()478#     _known_hosts_real ''479#     printf '%s\n' "${COMPREPLY[@]}" | command sort -u --version-sort480#   }481if ! declare -F __fzf_list_hosts > /dev/null; then482  __fzf_list_hosts() {483    command sort -u \484      <(485        # Note: To make the pathname expansion of "~/.ssh/config.d/*" work486        # properly, we need to adjust the related shell options.  We need to487        # unset "set -f" and "GLOBIGNORE", which disable the pathname expansion488        # totally or partially.  We need to unset "dotglob" and "nocaseglob" to489        # avoid matching unwanted files.  We need to unset "failglob" to avoid490        # outputting the error messages to the terminal when no matching is491        # found.  We need to set "nullglob" to avoid attempting to read the492        # literal filename '~/.ssh/config.d/*' when no matching is found.493        set +f494        GLOBIGNORE=495        shopt -u dotglob nocaseglob failglob496        shopt -s nullglob497498        __fzf_exec_awk '499          # Note: mawk <= 1.3.3-20090705 does not support the POSIX brackets of500          # the form [[:blank:]], and Ubuntu 18.04 LTS still uses this501          # 16-year-old mawk unfortunately.  We need to use [ \t] instead.502          match(tolower($0), /^[ \t]*host(name)?[ \t]*[ \t=]/) {503            $0 = substr($0, RLENGTH + 1) # Remove "Host(name)?=?"504            sub(/#.*/, "")505            for (i = 1; i <= NF; i++)506              if ($i !~ /[*?%]/)507                print $i508          }509        ' ~/.ssh/config ~/.ssh/config.d/* /etc/ssh/ssh_config 2> /dev/null510      ) \511      <(512        __fzf_exec_awk -F ',' '513          match($0, /^[][a-zA-Z0-9.,:-]+/) {514            $0 = substr($0, 1, RLENGTH)515            gsub(/[][]|:[^,]*/, "")516            for (i = 1; i <= NF; i++)517              print $i518          }519        ' ~/.ssh/known_hosts 2> /dev/null520      ) \521      <(522        __fzf_exec_awk '523          {524            sub(/#.*/, "")525            for (i = 2; i <= NF; i++)526              if ($i != "0.0.0.0")527                print $i528          }529        ' /etc/hosts 2> /dev/null530      )531  }532fi533534_fzf_host_completion() {535  _fzf_complete +m -- "$@" < <(__fzf_list_hosts)536}537538# Values for $1 $2 $3 are described here539# https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion.html540# > the first argument ($1) is the name of the command whose arguments are being completed,541# > the second argument ($2) is the word being completed,542# > and the third argument ($3) is the word preceding the word being completed on the current command line.543_fzf_complete_ssh() {544  case $3 in545    -i | -F | -E)546      _fzf_path_completion "$@"547      ;;548    *)549      local user=550      [[ $2 =~ '@' ]] && user="${2%%@*}@"551      _fzf_complete +m -- "$@" < <(__fzf_list_hosts | __fzf_exec_awk -v user="$user" '{print user $0}')552      ;;553  esac554}555556_fzf_var_completion() {557  _fzf_complete -m -- "$@" < <(558    declare -xp | command sed -En 's|^declare [^ ]+ ([^=]+).*|\1|p'559  )560}561562_fzf_alias_completion() {563  _fzf_complete -m -- "$@" < <(564    alias | command sed -En 's|^alias ([^=]+).*|\1|p'565  )566}567568# fzf options569complete -o default -F _fzf_opts_completion fzf570# fzf-tmux is a thin fzf wrapper that has only a few more options than fzf571# itself. As a quick improvement we take fzf's completion. Adding the few extra572# fzf-tmux specific options (like `-w WIDTH`) are left as a future patch.573complete -o default -F _fzf_opts_completion fzf-tmux574575# Default path completion576__fzf_default_completion() {577  __fzf_generic_path_completion _fzf_compgen_path "-m" "" "$@"578579  # Dynamic completion loader has updated the completion for the command580  if [[ $? -eq 124 ]]; then581    # We trigger _fzf_setup_completion so that fuzzy completion for the command582    # still works. However, loader can update the completion for multiple583    # commands at once, and fuzzy completion will no longer work for those584    # other commands. e.g. pytest -> py.test, pytest-2, pytest-3, etc585    _fzf_setup_completion path "$1"586    return 124587  fi588}589590# Set fuzzy path completion as the default completion for all commands.591# We can't set up default completion,592# 1. if it's already set up by another script593# 2. or if the current version of bash doesn't support -D option594complete | command grep -q __fzf_default_completion ||595  complete | command grep -- '-D$' | command grep -qv _comp_complete_load ||596  complete -D -F __fzf_default_completion -o default -o bashdefault 2> /dev/null597598d_cmds="${FZF_COMPLETION_DIR_COMMANDS-cd pushd rmdir}"599600# NOTE: $FZF_COMPLETION_PATH_COMMANDS and $FZF_COMPLETION_VAR_COMMANDS are601# undocumented and subject to change in the future.602#603# NOTE: Although we have default completion, we still need to set up completion604# for each command in case they already have completion set up by another script.605a_cmds="${FZF_COMPLETION_PATH_COMMANDS-"606  awk bat cat code diff diff3607  emacs emacsclient ex file ftp g++ gcc gvim head hg hx java608  javac ld less more mvim nvim patch perl python ruby609  sed sftp sort source tail tee uniq vi view vim wc xdg-open610  basename bunzip2 bzip2 chmod chown curl cp dirname du611  find git grep gunzip gzip hg jar612  ln ls mv open rm rsync scp613  svn tar unzip zip"}"614v_cmds="${FZF_COMPLETION_VAR_COMMANDS-export unset printenv}"615616# Preserve existing completion617__fzf_orig_completion < <(complete -p $d_cmds $a_cmds $v_cmds unalias kill ssh 2> /dev/null)618619if type _comp_load > /dev/null 2>&1; then620  # _comp_load was added in bash-completion 2.12 to replace _completion_loader.621  # We use it without -D option so that it does not use _comp_complete_minimal as the fallback.622  _fzf_completion_loader=_comp_load623elif type __load_completion > /dev/null 2>&1; then624  # In bash-completion 2.11, _completion_loader internally calls __load_completion625  # and if it returns a non-zero status, it sets the default 'minimal' completion.626  _fzf_completion_loader=__load_completion627elif type _completion_loader > /dev/null 2>&1; then628  _fzf_completion_loader=_completion_loader629fi630631__fzf_defc() {632  local cmd func opts REPLY633  cmd="$1"634  func="$2"635  opts="$3"636  if __fzf_orig_completion_instantiate "$cmd" "$func"; then637    eval "$REPLY"638  else639    eval "complete -F \"$func\" $opts \"$cmd\""640  fi641}642643# Anything644for cmd in $a_cmds; do645  __fzf_defc "$cmd" _fzf_path_completion "-o default -o bashdefault"646done647648# Directory649for cmd in $d_cmds; do650  __fzf_defc "$cmd" _fzf_dir_completion "-o bashdefault -o nospace -o dirnames"651done652653# Variables654for cmd in $v_cmds; do655  __fzf_defc "$cmd" _fzf_var_completion "-o default -o nospace -v"656done657658# Aliases659__fzf_defc unalias _fzf_alias_completion "-a"660661# Processes662__fzf_defc kill _fzf_proc_completion "-o default -o bashdefault"663664# ssh665__fzf_defc ssh _fzf_complete_ssh "-o default -o bashdefault"666667unset cmd d_cmds a_cmds v_cmds668669_fzf_setup_completion() {670  local kind fn cmd671  kind=$1672  fn=_fzf_${1}_completion673  if [[ $# -lt 2 ]] || ! type -t "$fn" > /dev/null; then674    echo "usage: ${FUNCNAME[0]} path|dir|var|alias|host|proc COMMANDS..."675    return 1676  fi677  shift678  __fzf_orig_completion < <(complete -p "$@" 2> /dev/null)679  for cmd in "$@"; do680    case "$kind" in681      dir) __fzf_defc "$cmd" "$fn" "-o nospace -o dirnames" ;;682      var) __fzf_defc "$cmd" "$fn" "-o default -o nospace -v" ;;683      alias) __fzf_defc "$cmd" "$fn" "-a" ;;684      *) __fzf_defc "$cmd" "$fn" "-o default -o bashdefault" ;;685    esac686  done687}688#----END shfmt689690fi