Skip to content
Myr

completion.bash

This file

Path

shell/completion.bash

544 lines · 14.2 KiB · Shell

Last changed by

[completion] Handle all hostaliases in /etc/hosts (#3495)akdevservicesbefore adoptiona62fe3d

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}16if ! declare -F _fzf_compgen_path > /dev/null; then17  _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  }23fi2425if ! declare -F _fzf_compgen_dir > /dev/null; then26  _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  }31fi3233###########################################################3435# To redraw line after fzf closes (printf '\e[5n')36bind '"\e[0n": redraw-current-line' 2> /dev/null3738__fzf_comprun() {39  if [[ "$(type -t _fzf_comprun 2>&1)" = function ]]; then40    _fzf_comprun "$@"41  elif [[ -n "${TMUX_PANE-}" ]] && { [[ "${FZF_TMUX:-0}" != 0 ]] || [[ -n "${FZF_TMUX_OPTS-}" ]]; }; then42    shift43    fzf-tmux ${FZF_TMUX_OPTS:--d${FZF_TMUX_HEIGHT:-40%}} -- "$@"44  else45    shift46    fzf "$@"47  fi48}4950__fzf_orig_completion() {51  local l comp f cmd52  while read -r l; do53    if [[ "$l" =~ ^(.*\ -F)\ *([^ ]*).*\ ([^ ]*)$ ]]; then54      comp="${BASH_REMATCH[1]}"55      f="${BASH_REMATCH[2]}"56      cmd="${BASH_REMATCH[3]}"57      [[ "$f" = _fzf_* ]] && continue58      printf -v "_fzf_orig_completion_${cmd//[^A-Za-z0-9_]/_}" "%s" "${comp} %s ${cmd} #${f}"59      if [[ "$l" = *" -o nospace "* ]] && [[ ! "${__fzf_nospace_commands-}" = *" $cmd "* ]]; then60        __fzf_nospace_commands="${__fzf_nospace_commands-} $cmd "61      fi62    fi63  done64}6566_fzf_opts_completion() {67  local cur prev opts68  COMPREPLY=()69  cur="${COMP_WORDS[COMP_CWORD]}"70  prev="${COMP_WORDS[COMP_CWORD-1]}"71  opts="72    -h --help73    -x --extended74    -e --exact75    --extended-exact76    +x --no-extended77    +e --no-exact78    -q --query79    -f --filter80    --literal81    --no-literal82    --algo83    --scheme84    --expect85    --no-expect86    --enabled --no-phony87    --disabled --phony88    --tiebreak89    --bind90    --color91    --toggle-sort92    -d --delimiter93    -n --nth94    --with-nth95    -s --sort96    +s --no-sort97    --track98    --no-track99    --tac100    --no-tac101    -i102    +i103    -m --multi104    +m --no-multi105    --ansi106    --no-ansi107    --no-mouse108    +c --no-color109    +2 --no-256110    --black111    --no-black112    --bold113    --no-bold114    --layout115    --reverse116    --no-reverse117    --cycle118    --no-cycle119    --keep-right120    --no-keep-right121    --hscroll122    --no-hscroll123    --hscroll-off124    --scroll-off125    --filepath-word126    --no-filepath-word127    --info128    --no-info129    --inline-info130    --no-inline-info131    --separator132    --no-separator133    --scrollbar134    --no-scrollbar135    --jump-labels136    -1 --select-1137    +1 --no-select-1138    -0 --exit-0139    +0 --no-exit-0140    --read0141    --no-read0142    --print0143    --no-print0144    --print-query145    --no-print-query146    --prompt147    --pointer148    --marker149    --sync150    --no-sync151    --async152    --no-history153    --history154    --history-size155    --no-header156    --no-header-lines157    --header158    --header-lines159    --header-first160    --no-header-first161    --ellipsis162    --preview163    --no-preview164    --preview-window165    --height166    --min-height167    --no-height168    --no-margin169    --no-padding170    --no-border171    --border172    --no-border-label173    --border-label174    --border-label-pos175    --no-preview-label176    --preview-label177    --preview-label-pos178    --no-unicode179    --unicode180    --margin181    --padding182    --tabstop183    --listen184    --no-listen185    --clear186    --no-clear187    --version188    --"189190  case "${prev}" in191  --algo)192    COMPREPLY=( $(compgen -W "v1 v2" -- "$cur") )193    return 0194    ;;195  --scheme)196    COMPREPLY=( $(compgen -W "default path history" -- "$cur") )197    return 0198    ;;199  --tiebreak)200    COMPREPLY=( $(compgen -W "length chunk begin end index" -- "$cur") )201    return 0202    ;;203  --color)204    COMPREPLY=( $(compgen -W "dark light 16 bw no" -- "$cur") )205    return 0206    ;;207  --layout)208    COMPREPLY=( $(compgen -W "default reverse reverse-list" -- "$cur") )209    return 0210    ;;211  --info)212    COMPREPLY=( $(compgen -W "default right hidden inline inline-right" -- "$cur") )213    return 0214    ;;215  --preview-window)216    COMPREPLY=( $(compgen -W "217      default218      hidden219      nohidden220      wrap221      nowrap222      cycle223      nocycle224      up top225      down bottom226      left227      right228      rounded border border-rounded229      sharp border-sharp230      border-bold231      border-block232      border-thinblock233      border-double234      noborder border-none235      border-horizontal236      border-vertical237      border-up border-top238      border-down border-bottom239      border-left240      border-right241      follow242      nofollow" -- "$cur") )243    return 0244    ;;245  --border)246    COMPREPLY=( $(compgen -W "rounded sharp bold block thinblock double horizontal vertical top bottom left right none" -- "$cur") )247    return 0248    ;;249  --border-label-pos|--preview-label-pos)250    COMPREPLY=( $(compgen -W "center bottom top" -- "$cur") )251    return 0252    ;;253  esac254255  if [[ "$cur" =~ ^-|\+ ]]; then256    COMPREPLY=( $(compgen -W "${opts}" -- "$cur") )257    return 0258  fi259260  return 0261}262263_fzf_handle_dynamic_completion() {264  local cmd orig_var orig ret orig_cmd orig_complete265  cmd="$1"266  shift267  orig_cmd="$1"268  orig_var="_fzf_orig_completion_$cmd"269  orig="${!orig_var-}"270  orig="${orig##*#}"271  if [[ -n "$orig" ]] && type "$orig" > /dev/null 2>&1; then272    $orig "$@"273  elif [[ -n "${_fzf_completion_loader-}" ]]; then274    orig_complete=$(complete -p "$orig_cmd" 2> /dev/null)275    _completion_loader "$@"276    ret=$?277    # _completion_loader may not have updated completion for the command278    if [[ "$(complete -p "$orig_cmd" 2> /dev/null)" != "$orig_complete" ]]; then279      __fzf_orig_completion < <(complete -p "$orig_cmd" 2> /dev/null)280      if [[ "${__fzf_nospace_commands-}" = *" $orig_cmd "* ]]; then281        eval "${orig_complete/ -F / -o nospace -F }"282      else283        eval "$orig_complete"284      fi285    fi286    return $ret287  fi288}289290__fzf_generic_path_completion() {291  local cur base dir leftover matches trigger cmd292  cmd="${COMP_WORDS[0]}"293  if [[ $cmd == \\* ]]; then294    cmd="${cmd:1}"295  fi296  cmd="${cmd//[^A-Za-z0-9_=]/_}"297  COMPREPLY=()298  trigger=${FZF_COMPLETION_TRIGGER-'**'}299  cur="${COMP_WORDS[COMP_CWORD]}"300  if [[ "$cur" == *"$trigger" ]] && [[ $cur != *'$('* ]] && [[ $cur != *':='* ]] && [[ $cur != *'`'* ]]; then301    base=${cur:0:${#cur}-${#trigger}}302    eval "base=$base" 2> /dev/null || return303304    dir=305    [[ $base = *"/"* ]] && dir="$base"306    while true; do307      if [[ -z "$dir" ]] || [[ -d "$dir" ]]; then308        leftover=${base/#"$dir"}309        leftover=${leftover/#\/}310        [[ -z "$dir" ]] && dir='.'311        [[ "$dir" != "/" ]] && dir="${dir/%\//}"312        matches=$(eval "$1 $(printf %q "$dir")" | FZF_DEFAULT_OPTS="--height ${FZF_TMUX_HEIGHT:-40%} --reverse --scheme=path --bind=ctrl-z:ignore ${FZF_DEFAULT_OPTS-} ${FZF_COMPLETION_OPTS-} $2" __fzf_comprun "$4" -q "$leftover" | while read -r item; do313          printf "%q " "${item%$3}$3"314        done)315        matches=${matches% }316        [[ -z "$3" ]] && [[ "${__fzf_nospace_commands-}" = *" ${COMP_WORDS[0]} "* ]] && matches="$matches "317        if [[ -n "$matches" ]]; then318          COMPREPLY=( "$matches" )319        else320          COMPREPLY=( "$cur" )321        fi322        printf '\e[5n'323        return 0324      fi325      dir=$(command dirname "$dir")326      [[ "$dir" =~ /$ ]] || dir="$dir"/327    done328  else329    shift330    shift331    shift332    _fzf_handle_dynamic_completion "$cmd" "$@"333  fi334}335336_fzf_complete() {337  # Split arguments around --338  local args rest str_arg i sep339  args=("$@")340  sep=341  for i in "${!args[@]}"; do342    if [[ "${args[$i]}" = -- ]]; then343      sep=$i344      break345    fi346  done347  if [[ -n "$sep" ]]; then348    str_arg=349    rest=("${args[@]:$((sep + 1)):${#args[@]}}")350    args=("${args[@]:0:$sep}")351  else352    str_arg=$1353    args=()354    shift355    rest=("$@")356  fi357358  local cur selected trigger cmd post359  post="$(caller 0 | command awk '{print $2}')_post"360  type -t "$post" > /dev/null 2>&1 || post='command cat'361362  cmd="${COMP_WORDS[0]//[^A-Za-z0-9_=]/_}"363  trigger=${FZF_COMPLETION_TRIGGER-'**'}364  cur="${COMP_WORDS[COMP_CWORD]}"365  if [[ "$cur" == *"$trigger" ]] && [[ $cur != *'$('* ]] && [[ $cur != *':='* ]] && [[ $cur != *'`'* ]]; then366    cur=${cur:0:${#cur}-${#trigger}}367368    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' ' ')369    selected=${selected% } # Strip trailing space not to repeat "-o nospace"370    if [[ -n "$selected" ]]; then371      COMPREPLY=("$selected")372    else373      COMPREPLY=("$cur")374    fi375    printf '\e[5n'376    return 0377  else378    _fzf_handle_dynamic_completion "$cmd" "${rest[@]}"379  fi380}381382_fzf_path_completion() {383  __fzf_generic_path_completion _fzf_compgen_path "-m" "" "$@"384}385386# Deprecated. No file only completion.387_fzf_file_completion() {388  _fzf_path_completion "$@"389}390391_fzf_dir_completion() {392  __fzf_generic_path_completion _fzf_compgen_dir "" "/" "$@"393}394395_fzf_complete_kill() {396  _fzf_proc_completion "$@"397}398399_fzf_proc_completion() {400  _fzf_complete -m --header-lines=1 --preview 'echo {}' --preview-window down:3:wrap --min-height 15 -- "$@" < <(401    command ps -eo user,pid,ppid,start,time,command 2> /dev/null ||402      command ps -eo user,pid,ppid,time,args # For BusyBox403  )404}405406_fzf_proc_completion_post() {407  command awk '{print $2}'408}409410# To use custom hostname lists, override __fzf_list_hosts.411# The function is expected to print hostnames, one per line as well as in the412# desired sorting and with any duplicates removed, to standard output.413#414# e.g.415#   # Use bash-completions’s _known_hosts_real() for getting the list of hosts416#   __fzf_list_hosts() {417#     # Set the local attribute for any non-local variable that is set by _known_hosts_real()418#     local COMPREPLY=()419#     _known_hosts_real ''420#     printf '%s\n' "${COMPREPLY[@]}" | command sort -u --version-sort421#   }422if ! declare -F __fzf_list_hosts > /dev/null; then423  __fzf_list_hosts() {424    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 '[*?%]') \425      <(command grep -oE '^[[a-z0-9.,:-]+' ~/.ssh/known_hosts 2> /dev/null | command tr ',' '\n' | command tr -d '[' | command awk '{ print $1 " " $1 }') \426      <(command grep -v '^\s*\(#\|$\)' /etc/hosts 2> /dev/null | command grep -Fv '0.0.0.0' | command sed 's/#.*//') |427      command awk '{for (i = 2; i <= NF; i++) print $i}' | command sort -u428  }429fi430431_fzf_host_completion() {432  _fzf_complete +m -- "$@" < <(__fzf_list_hosts)433}434435# Values for $1 $2 $3 are described here436# https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion.html437# > the first argument ($1) is the name of the command whose arguments are being completed,438# > the second argument ($2) is the word being completed,439# > and the third argument ($3) is the word preceding the word being completed on the current command line.440_fzf_complete_ssh() {441  case $3 in442    -i|-F|-E)443      _fzf_path_completion "$@"444      ;;445    *)446      local user=447      [[ "$2" =~ '@' ]] && user="${2%%@*}@"448      _fzf_complete +m -- "$@" < <(__fzf_list_hosts | command awk -v user="$user" '{print user $0}')449      ;;450  esac451}452453_fzf_var_completion() {454  _fzf_complete -m -- "$@" < <(455    declare -xp | command sed -En 's|^declare [^ ]+ ([^=]+).*|\1|p'456  )457}458459_fzf_alias_completion() {460  _fzf_complete -m -- "$@" < <(461    alias | command sed -En 's|^alias ([^=]+).*|\1|p'462  )463}464465# fzf options466complete -o default -F _fzf_opts_completion fzf467# fzf-tmux is a thin fzf wrapper that has only a few more options than fzf468# itself. As a quick improvement we take fzf's completion. Adding the few extra469# fzf-tmux specific options (like `-w WIDTH`) are left as a future patch.470complete -o default -F _fzf_opts_completion fzf-tmux471472d_cmds="${FZF_COMPLETION_DIR_COMMANDS:-cd pushd rmdir}"473a_cmds="474  awk bat cat diff diff3475  emacs emacsclient ex file ftp g++ gcc gvim head hg hx java476  javac ld less more mvim nvim patch perl python ruby477  sed sftp sort source tail tee uniq vi view vim wc xdg-open478  basename bunzip2 bzip2 chmod chown curl cp dirname du479  find git grep gunzip gzip hg jar480  ln ls mv open rm rsync scp481  svn tar unzip zip"482483# Preserve existing completion484__fzf_orig_completion < <(complete -p $d_cmds $a_cmds ssh 2> /dev/null)485486if type _completion_loader > /dev/null 2>&1; then487  _fzf_completion_loader=1488fi489490__fzf_defc() {491  local cmd func opts orig_var orig def492  cmd="$1"493  func="$2"494  opts="$3"495  orig_var="_fzf_orig_completion_${cmd//[^A-Za-z0-9_]/_}"496  orig="${!orig_var-}"497  if [[ -n "$orig" ]]; then498    printf -v def "$orig" "$func"499    eval "$def"500  else501    complete -F "$func" $opts "$cmd"502  fi503}504505# Anything506for cmd in $a_cmds; do507  __fzf_defc "$cmd" _fzf_path_completion "-o default -o bashdefault"508done509510# Directory511for cmd in $d_cmds; do512  __fzf_defc "$cmd" _fzf_dir_completion "-o nospace -o dirnames"513done514515# ssh516__fzf_defc ssh _fzf_complete_ssh "-o default -o bashdefault"517518unset cmd d_cmds a_cmds519520_fzf_setup_completion() {521  local kind fn cmd522  kind=$1523  fn=_fzf_${1}_completion524  if [[ $# -lt 2 ]] || ! type -t "$fn" > /dev/null; then525    echo "usage: ${FUNCNAME[0]} path|dir|var|alias|host|proc COMMANDS..."526    return 1527  fi528  shift529  __fzf_orig_completion < <(complete -p "$@" 2> /dev/null)530  for cmd in "$@"; do531    case "$kind" in532      dir)   __fzf_defc "$cmd" "$fn" "-o nospace -o dirnames" ;;533      var)   __fzf_defc "$cmd" "$fn" "-o default -o nospace -v" ;;534      alias) __fzf_defc "$cmd" "$fn" "-a" ;;535      *)     __fzf_defc "$cmd" "$fn" "-o default -o bashdefault" ;;536    esac537  done538}539540# Environment variables / Aliases / Hosts / Process541_fzf_setup_completion 'var'   export unset printenv542_fzf_setup_completion 'alias' unalias543_fzf_setup_completion 'host'  telnet544_fzf_setup_completion 'proc'  kill