Skip to content
Myr

completion.bash

This file

Path

shell/completion.bash

562 lines · 15.8 KiB · Shell

Last changed by

chore: Update flags to include long-form options for case (#3785)LangLangBartbefore adoption07880ca

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    -h --help105    -e --exact106    +x --no-extended107    -q --query108    -f --filter109    --literal110    --scheme111    --expect112    --disabled113    --tiebreak114    --bind115    --color116    -d --delimiter117    -n --nth118    --with-nth119    +s --no-sort120    --track121    --tac122    -i --ignore-case123    +i --no-ignore-case124    -m --multi125    --ansi126    --no-mouse127    +c --no-color128    --no-bold129    --layout130    --reverse131    --cycle132    --keep-right133    --no-hscroll134    --hscroll-off135    --scroll-off136    --filepath-word137    --info138    --separator139    --no-separator140    --no-scrollbar141    --jump-labels142    -1 --select-1143    -0 --exit-0144    --read0145    --print0146    --print-query147    --prompt148    --pointer149    --marker150    --sync151    --history152    --history-size153    --header154    --header-lines155    --header-first156    --ellipsis157    --preview158    --preview-window159    --height160    --min-height161    --border162    --border-label163    --border-label-pos164    --preview-label165    --preview-label-pos166    --no-unicode167    --margin168    --padding169    --tabstop170    --listen171    --no-clear172    --version173    --"174175  case "${prev}" in176  --scheme)177    COMPREPLY=( $(compgen -W "default path history" -- "$cur") )178    return 0179    ;;180  --tiebreak)181    COMPREPLY=( $(compgen -W "length chunk begin end index" -- "$cur") )182    return 0183    ;;184  --color)185    COMPREPLY=( $(compgen -W "dark light 16 bw no" -- "$cur") )186    return 0187    ;;188  --layout)189    COMPREPLY=( $(compgen -W "default reverse reverse-list" -- "$cur") )190    return 0191    ;;192  --info)193    COMPREPLY=( $(compgen -W "default right hidden inline inline-right" -- "$cur") )194    return 0195    ;;196  --preview-window)197    COMPREPLY=( $(compgen -W "198      default199      hidden200      nohidden201      wrap202      nowrap203      cycle204      nocycle205      up top206      down bottom207      left208      right209      rounded border border-rounded210      sharp border-sharp211      border-bold212      border-block213      border-thinblock214      border-double215      noborder border-none216      border-horizontal217      border-vertical218      border-up border-top219      border-down border-bottom220      border-left221      border-right222      follow223      nofollow" -- "$cur") )224    return 0225    ;;226  --border)227    COMPREPLY=( $(compgen -W "rounded sharp bold block thinblock double horizontal vertical top bottom left right none" -- "$cur") )228    return 0229    ;;230  --border-label-pos|--preview-label-pos)231    COMPREPLY=( $(compgen -W "center bottom top" -- "$cur") )232    return 0233    ;;234  esac235236  if [[ "$cur" =~ ^-|\+ ]]; then237    COMPREPLY=( $(compgen -W "${opts}" -- "$cur") )238    return 0239  fi240241  return 0242}243244_fzf_handle_dynamic_completion() {245  local cmd ret REPLY orig_cmd orig_complete246  cmd="$1"247  shift248  orig_cmd="$1"249  if __fzf_orig_completion_get_orig_func "$cmd"; then250    "$REPLY" "$@"251  elif [[ -n "${_fzf_completion_loader-}" ]]; then252    orig_complete=$(complete -p "$orig_cmd" 2> /dev/null)253    $_fzf_completion_loader "$@"254    ret=$?255    # _completion_loader may not have updated completion for the command256    if [[ "$(complete -p "$orig_cmd" 2> /dev/null)" != "$orig_complete" ]]; then257      __fzf_orig_completion < <(complete -p "$orig_cmd" 2> /dev/null)258259      # Update orig_complete by _fzf_orig_completion entry260      [[ $orig_complete =~ ' -F '(_fzf_[^ ]+)' ' ]] &&261        __fzf_orig_completion_instantiate "$cmd" "${BASH_REMATCH[1]}" &&262        orig_complete=$REPLY263264      if [[ "${__fzf_nospace_commands-}" = *" $orig_cmd "* ]]; then265        eval "${orig_complete/ -F / -o nospace -F }"266      else267        eval "$orig_complete"268      fi269    fi270    [[ $ret -eq 0 ]] && return 124271    return $ret272  fi273}274275__fzf_generic_path_completion() {276  local cur base dir leftover matches trigger cmd277  cmd="${COMP_WORDS[0]}"278  if [[ $cmd == \\* ]]; then279    cmd="${cmd:1}"280  fi281  COMPREPLY=()282  trigger=${FZF_COMPLETION_TRIGGER-'**'}283  cur="${COMP_WORDS[COMP_CWORD]}"284  if [[ "$cur" == *"$trigger" ]] && [[ $cur != *'$('* ]] && [[ $cur != *':='* ]] && [[ $cur != *'`'* ]]; then285    base=${cur:0:${#cur}-${#trigger}}286    eval "base=$base" 2> /dev/null || return287288    dir=289    [[ $base = *"/"* ]] && dir="$base"290    while true; do291      if [[ -z "$dir" ]] || [[ -d "$dir" ]]; then292        leftover=${base/#"$dir"}293        leftover=${leftover/#\/}294        [[ -z "$dir" ]] && dir='.'295        [[ "$dir" != "/" ]] && dir="${dir/%\//}"296        matches=$(297          export FZF_DEFAULT_OPTS=$(__fzf_defaults "--reverse --scheme=path" "${FZF_COMPLETION_OPTS-} $2")298          unset FZF_DEFAULT_COMMAND FZF_DEFAULT_OPTS_FILE299          if declare -F "$1" > /dev/null; then300            eval "$1 $(printf %q "$dir")" | __fzf_comprun "$4" -q "$leftover"301          else302            if [[ $1 =~ dir ]]; then303              walker=dir,follow304              rest=${FZF_COMPLETION_DIR_OPTS-}305            else306              walker=file,dir,follow,hidden307              rest=${FZF_COMPLETION_PATH_OPTS-}308            fi309            __fzf_comprun "$4" -q "$leftover" --walker "$walker" --walker-root="$dir" $rest310          fi | while read -r item; do311            printf "%q " "${item%$3}$3"312          done313        )314        matches=${matches% }315        [[ -z "$3" ]] && [[ "${__fzf_nospace_commands-}" = *" ${COMP_WORDS[0]} "* ]] && matches="$matches "316        if [[ -n "$matches" ]]; then317          COMPREPLY=( "$matches" )318        else319          COMPREPLY=( "$cur" )320        fi321        printf '\e[5n'322        return 0323      fi324      dir=$(command dirname "$dir")325      [[ "$dir" =~ /$ ]] || dir="$dir"/326    done327  else328    shift329    shift330    shift331    _fzf_handle_dynamic_completion "$cmd" "$@"332  fi333}334335_fzf_complete() {336  # Split arguments around --337  local args rest str_arg i sep338  args=("$@")339  sep=340  for i in "${!args[@]}"; do341    if [[ "${args[$i]}" = -- ]]; then342      sep=$i343      break344    fi345  done346  if [[ -n "$sep" ]]; then347    str_arg=348    rest=("${args[@]:$((sep + 1)):${#args[@]}}")349    args=("${args[@]:0:$sep}")350  else351    str_arg=$1352    args=()353    shift354    rest=("$@")355  fi356357  local cur selected trigger cmd post358  post="$(caller 0 | command awk '{print $2}')_post"359  type -t "$post" > /dev/null 2>&1 || post='command cat'360361  trigger=${FZF_COMPLETION_TRIGGER-'**'}362  cmd="${COMP_WORDS[0]}"363  cur="${COMP_WORDS[COMP_CWORD]}"364  if [[ "$cur" == *"$trigger" ]] && [[ $cur != *'$('* ]] && [[ $cur != *':='* ]] && [[ $cur != *'`'* ]]; then365    cur=${cur:0:${#cur}-${#trigger}}366367    selected=$(368      FZF_DEFAULT_OPTS=$(__fzf_defaults "--reverse" "${FZF_COMPLETION_OPTS-} $str_arg") \369      FZF_DEFAULT_OPTS_FILE='' \370        __fzf_comprun "${rest[0]}" "${args[@]}" -q "$cur" | $post | command tr '\n' ' ')371    selected=${selected% } # Strip trailing space not to repeat "-o nospace"372    if [[ -n "$selected" ]]; then373      COMPREPLY=("$selected")374    else375      COMPREPLY=("$cur")376    fi377    printf '\e[5n'378    return 0379  else380    _fzf_handle_dynamic_completion "$cmd" "${rest[@]}"381  fi382}383384_fzf_path_completion() {385  __fzf_generic_path_completion _fzf_compgen_path "-m" "" "$@"386}387388# Deprecated. No file only completion.389_fzf_file_completion() {390  _fzf_path_completion "$@"391}392393_fzf_dir_completion() {394  __fzf_generic_path_completion _fzf_compgen_dir "" "/" "$@"395}396397_fzf_complete_kill() {398  _fzf_proc_completion "$@"399}400401_fzf_proc_completion() {402  _fzf_complete -m --header-lines=1 --preview 'echo {}' --preview-window down:3:wrap --min-height 15 -- "$@" < <(403    command ps -eo user,pid,ppid,start,time,command 2> /dev/null ||404      command ps -eo user,pid,ppid,time,args # For BusyBox405  )406}407408_fzf_proc_completion_post() {409  command awk '{print $2}'410}411412# To use custom hostname lists, override __fzf_list_hosts.413# The function is expected to print hostnames, one per line as well as in the414# desired sorting and with any duplicates removed, to standard output.415#416# e.g.417#   # Use bash-completions’s _known_hosts_real() for getting the list of hosts418#   __fzf_list_hosts() {419#     # Set the local attribute for any non-local variable that is set by _known_hosts_real()420#     local COMPREPLY=()421#     _known_hosts_real ''422#     printf '%s\n' "${COMPREPLY[@]}" | command sort -u --version-sort423#   }424if ! declare -F __fzf_list_hosts > /dev/null; then425  __fzf_list_hosts() {426    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 '[*?%]') \427      <(command grep -oE '^[[a-z0-9.,:-]+' ~/.ssh/known_hosts 2> /dev/null | command tr ',' '\n' | command tr -d '[' | command awk '{ print $1 " " $1 }') \428      <(command grep -v '^\s*\(#\|$\)' /etc/hosts 2> /dev/null | command grep -Fv '0.0.0.0' | command sed 's/#.*//') |429      command awk '{for (i = 2; i <= NF; i++) print $i}' | command sort -u430  }431fi432433_fzf_host_completion() {434  _fzf_complete +m -- "$@" < <(__fzf_list_hosts)435}436437# Values for $1 $2 $3 are described here438# https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion.html439# > the first argument ($1) is the name of the command whose arguments are being completed,440# > the second argument ($2) is the word being completed,441# > and the third argument ($3) is the word preceding the word being completed on the current command line.442_fzf_complete_ssh() {443  case $3 in444    -i|-F|-E)445      _fzf_path_completion "$@"446      ;;447    *)448      local user=449      [[ "$2" =~ '@' ]] && user="${2%%@*}@"450      _fzf_complete +m -- "$@" < <(__fzf_list_hosts | command awk -v user="$user" '{print user $0}')451      ;;452  esac453}454455_fzf_var_completion() {456  _fzf_complete -m -- "$@" < <(457    declare -xp | command sed -En 's|^declare [^ ]+ ([^=]+).*|\1|p'458  )459}460461_fzf_alias_completion() {462  _fzf_complete -m -- "$@" < <(463    alias | command sed -En 's|^alias ([^=]+).*|\1|p'464  )465}466467# fzf options468complete -o default -F _fzf_opts_completion fzf469# fzf-tmux is a thin fzf wrapper that has only a few more options than fzf470# itself. As a quick improvement we take fzf's completion. Adding the few extra471# fzf-tmux specific options (like `-w WIDTH`) are left as a future patch.472complete -o default -F _fzf_opts_completion fzf-tmux473474d_cmds="${FZF_COMPLETION_DIR_COMMANDS-cd pushd rmdir}"475476# NOTE: $FZF_COMPLETION_PATH_COMMANDS and $FZF_COMPLETION_VAR_COMMANDS are477# undocumented and subject to change in the future.478a_cmds="${FZF_COMPLETION_PATH_COMMANDS-"479  awk bat cat diff diff3480  emacs emacsclient ex file ftp g++ gcc gvim head hg hx java481  javac ld less more mvim nvim patch perl python ruby482  sed sftp sort source tail tee uniq vi view vim wc xdg-open483  basename bunzip2 bzip2 chmod chown curl cp dirname du484  find git grep gunzip gzip hg jar485  ln ls mv open rm rsync scp486  svn tar unzip zip"}"487v_cmds="${FZF_COMPLETION_VAR_COMMANDS-export unset printenv}"488489# Preserve existing completion490__fzf_orig_completion < <(complete -p $d_cmds $a_cmds $v_cmds unalias kill ssh 2> /dev/null)491492if type _comp_load > /dev/null 2>&1; then493  # _comp_load was added in bash-completion 2.12 to replace _completion_loader.494  # We use it without -D option so that it does not use _comp_complete_minimal as the fallback.495  _fzf_completion_loader=_comp_load496elif type __load_completion > /dev/null 2>&1; then497  # In bash-completion 2.11, _completion_loader internally calls __load_completion498  # and if it returns a non-zero status, it sets the default 'minimal' completion.499  _fzf_completion_loader=__load_completion500elif type _completion_loader > /dev/null 2>&1; then501  _fzf_completion_loader=_completion_loader502fi503504__fzf_defc() {505  local cmd func opts REPLY506  cmd="$1"507  func="$2"508  opts="$3"509  if __fzf_orig_completion_instantiate "$cmd" "$func"; then510    eval "$REPLY"511  else512    complete -F "$func" $opts "$cmd"513  fi514}515516# Anything517for cmd in $a_cmds; do518  __fzf_defc "$cmd" _fzf_path_completion "-o default -o bashdefault"519done520521# Directory522for cmd in $d_cmds; do523  __fzf_defc "$cmd" _fzf_dir_completion "-o bashdefault -o nospace -o dirnames"524done525526# Variables527for cmd in $v_cmds; do528  __fzf_defc "$cmd" _fzf_var_completion "-o default -o nospace -v"529done530531# Aliases532__fzf_defc unalias _fzf_alias_completion "-a"533534# Processes535__fzf_defc kill _fzf_proc_completion "-o default -o bashdefault"536537# ssh538__fzf_defc ssh _fzf_complete_ssh "-o default -o bashdefault"539540unset cmd d_cmds a_cmds v_cmds541542_fzf_setup_completion() {543  local kind fn cmd544  kind=$1545  fn=_fzf_${1}_completion546  if [[ $# -lt 2 ]] || ! type -t "$fn" > /dev/null; then547    echo "usage: ${FUNCNAME[0]} path|dir|var|alias|host|proc COMMANDS..."548    return 1549  fi550  shift551  __fzf_orig_completion < <(complete -p "$@" 2> /dev/null)552  for cmd in "$@"; do553    case "$kind" in554      dir)   __fzf_defc "$cmd" "$fn" "-o nospace -o dirnames" ;;555      var)   __fzf_defc "$cmd" "$fn" "-o default -o nospace -v" ;;556      alias) __fzf_defc "$cmd" "$fn" "-a" ;;557      *)     __fzf_defc "$cmd" "$fn" "-o default -o bashdefault" ;;558    esac559  done560}561562fi