Skip to content
Myr

completion.zsh

This file

Path

shell/completion.zsh

477 lines · 16.0 KiB · Shell

Last changed by

completion(zsh): use private mktemp dir for completion FIFOJunegunn Choibefore adoptioncbc11e4

History of this file

Take it

1#     ____      ____2#    / __/___  / __/3#   / /_/_  / / /_4#  / __/ / /_/ __/5# /_/   /___/_/ completion.zsh6#7# - $FZF_COMPLETION_TRIGGER   (default: '**')8# - $FZF_COMPLETION_OPTS      (default: empty)9# - $FZF_COMPLETION_PATH_OPTS (default: empty)10# - $FZF_COMPLETION_DIR_OPTS  (default: empty)111213# Both branches of the following `if` do the same thing -- define14# __fzf_completion_options such that `eval $__fzf_completion_options` sets15# all options to the same values they currently have. We'll do just that at16# the bottom of the file after changing options to what we prefer.17#18# IMPORTANT: Until we get to the `emulate` line, all words that *can* be quoted19# *must* be quoted in order to prevent alias expansion. In addition, code must20# be written in a way works with any set of zsh options. This is very tricky, so21# careful when you change it.22#23# Start by loading the builtin zsh/parameter module. It provides `options`24# associative array that stores current shell options.25if 'zmodload' 'zsh/parameter' 2>'/dev/null' && (( ${+options} )); then26  # This is the fast branch and it gets taken on virtually all Zsh installations.27  #28  # ${(kv)options[@]} expands to array of keys (option names) and values ("on"29  # or "off"). The subsequent expansion# with (j: :) flag joins all elements30  # together separated by spaces. __fzf_completion_options ends up with a value31  # like this: "options=(shwordsplit off aliases on ...)".32  __fzf_completion_options="options=(${(j: :)${(kv)options[@]}})"33else34  # This branch is much slower because it forks to get the names of all35  # zsh options. It's possible to eliminate this fork but it's not worth the36  # trouble because this branch gets taken only on very ancient or broken37  # zsh installations.38  () {39    # That `()` above defines an anonymous function. This is essentially a scope40    # for local parameters. We use it to avoid polluting global scope.41    'local' '__fzf_opt'42    __fzf_completion_options="setopt"43    # `set -o` prints one line for every zsh option. Each line contains option44    # name, some spaces, and then either "on" or "off". We just want option names.45    # Expansion with (@f) flag splits a string into lines. The outer expansion46    # removes spaces and everything that follow them on every line. __fzf_opt47    # ends up iterating over option names: shwordsplit, aliases, etc.48    for __fzf_opt in "${(@)${(@f)$(set -o)}%% *}"; do49      if [[ -o "$__fzf_opt" ]]; then50        # Option $__fzf_opt is currently on, so remember to set it back on.51        __fzf_completion_options+=" -o $__fzf_opt"52      else53        # Option $__fzf_opt is currently off, so remember to set it back off.54        __fzf_completion_options+=" +o $__fzf_opt"55      fi56    done57    # The value of __fzf_completion_options here looks like this:58    # "setopt +o shwordsplit -o aliases ..."59  }60fi6162# Enable the default zsh options (those marked with <Z> in `man zshoptions`)63# but without `aliases`. Aliases in functions are expanded when functions are64# defined, so if we disable aliases here, we'll be sure to have no pesky65# aliases in any of our functions. This way we won't need prefix every66# command with `command` or to quote every word to defend against global67# aliases. Note that `aliases` is not the only option that's important to68# control. There are several others that could wreck havoc if they are set69# to values we don't expect. With the following `emulate` command we70# sidestep this issue entirely.71'builtin' 'emulate' 'zsh' && 'builtin' 'setopt' 'no_aliases'7273# This brace is the start of try-always block. The `always` part is like74# `finally` in lesser languages. We use it to *always* restore user options.75{76# The 'emulate' command should not be placed inside the interactive if check;77# placing it there fails to disable alias expansion. See #3731.78if [[ -o interactive ]]; then7980# To use custom commands instead of find, override _fzf_compgen_{path,dir}81#82#   _fzf_compgen_path() {83#     echo "$1"84#     command find -L "$1" \85#       -name .git -prune -o -name .hg -prune -o -name .svn -prune -o \( -type d -o -type f -o -type l \) \86#       -a -not -path "$1" -print 2> /dev/null | sed 's@^\./@@'87#   }88#89#   _fzf_compgen_dir() {90#     command find -L "$1" \91#       -name .git -prune -o -name .hg -prune -o -name .svn -prune -o -type d \92#       -a -not -path "$1" -print 2> /dev/null | sed 's@^\./@@'93#   }9495###########################################################9697#----BEGIN INCLUDE common.sh98# NOTE: Do not directly edit this section, which is copied from "common.sh".99# To modify it, one can edit "common.sh" and run "./update.sh" to apply100# the changes. See code comments in "common.sh" for the implementation details.101102__fzf_defaults() {103  builtin printf '%s\n' "--height ${FZF_TMUX_HEIGHT:-40%} --min-height 20+ --bind=ctrl-z:ignore $1"104  command cat "${FZF_DEFAULT_OPTS_FILE-}" 2> /dev/null105  builtin printf '%s\n' "${FZF_DEFAULT_OPTS-} $2"106}107108__fzf_exec_awk() {109  if [[ -z ${__fzf_awk-} ]]; then110    __fzf_awk=awk111    if [[ $OSTYPE == solaris* && -x /usr/xpg4/bin/awk ]]; then112      __fzf_awk=/usr/xpg4/bin/awk113    elif command -v mawk > /dev/null 2>&1; then114      local n x y z d115      IFS=' .' read -r n x y z d <<< $(command mawk -W version 2> /dev/null)116      [[ $n == mawk ]] &&117        (((x * 1000 + y) * 1000 + z >= 1003004)) 2> /dev/null &&118        ((d >= 20230302)) 2> /dev/null &&119        __fzf_awk=mawk120    fi121  fi122  LC_ALL=C exec "$__fzf_awk" "$@"123}124#----END INCLUDE125126__fzf_comprun() {127  if [[ "$(type _fzf_comprun 2>&1)" =~ function ]]; then128    _fzf_comprun "$@"129  elif [ -n "${TMUX_PANE-}" ] && { [ "${FZF_TMUX:-0}" != 0 ] || [ -n "${FZF_TMUX_OPTS-}" ]; }; then130    shift131    if [ -n "${FZF_TMUX_OPTS-}" ]; then132      fzf-tmux ${(Q)${(Z+n+)FZF_TMUX_OPTS}} -- "$@"133    else134      fzf-tmux -d ${FZF_TMUX_HEIGHT:-40%} -- "$@"135    fi136  else137    shift138    fzf "$@"139  fi140}141142# Extract the name of the command. e.g. ls; foo=1 ssh **<tab>143__fzf_extract_command() {144  # Control completion with the "compstate" parameter, insert and list nothing145  compstate[insert]=146  compstate[list]=147  cmd_word="${(Q)words[1]}"148}149150__fzf_generic_path_completion() {151  local base lbuf compgen fzf_opts suffix tail dir leftover matches152  base=$1153  lbuf=$2154  compgen=$3155  fzf_opts=$4156  suffix=$5157  tail=$6158159  setopt localoptions nonomatch160  if [[ $base = *'$('* ]] || [[ $base = *'<('* ]] || [[ $base = *'>('* ]] || [[ $base = *':='* ]] || [[ $base = *'`'* ]]; then161    return162  fi163  eval "base=$base" 2> /dev/null || return164  [[ $base = *"/"* ]] && dir="$base"165  while [ 1 ]; do166    if [[ -z "$dir" || -d ${dir} ]]; then167      leftover=${base/#"$dir"}168      leftover=${leftover/#\/}169      [ -z "$dir" ] && dir='.'170      [ "$dir" != "/" ] && dir="${dir/%\//}"171      matches=$(172        export FZF_DEFAULT_OPTS173        FZF_DEFAULT_OPTS=$(__fzf_defaults "--reverse --scheme=path" "${FZF_COMPLETION_OPTS-}")174        unset FZF_DEFAULT_COMMAND FZF_DEFAULT_OPTS_FILE175        if [[ $compgen =~ dir ]]; then176          rest=${FZF_COMPLETION_DIR_OPTS-}177        else178          rest=${FZF_COMPLETION_PATH_OPTS-}179        fi180        if declare -f "$compgen" > /dev/null; then181          eval "$compgen $(printf %q "$dir")" | __fzf_comprun "$cmd_word" ${(Q)${(Z+n+)fzf_opts}} -q "$leftover" ${(Q)${(Z+n+)rest}}182        else183          if [[ $compgen =~ dir ]]; then184            walker=dir,follow185          else186            walker=file,dir,follow,hidden187          fi188          __fzf_comprun "$cmd_word" ${(Q)${(Z+n+)fzf_opts}} -q "$leftover" --walker "$walker" --walker-root="$dir" ${(Q)${(Z+n+)rest}} < /dev/tty189        fi | while read -r item; do190          item="${item%$suffix}$suffix"191          echo -n -E "${(q)item} "192        done193      )194      matches=${matches% }195      if [ -n "$matches" ]; then196        LBUFFER="$lbuf$matches$tail"197      fi198      zle reset-prompt199      break200    fi201    dir=$(dirname "$dir")202    dir=${dir%/}/203  done204}205206_fzf_path_completion() {207  __fzf_generic_path_completion "$1" "$2" _fzf_compgen_path \208    "-m" "" " "209}210211_fzf_dir_completion() {212  __fzf_generic_path_completion "$1" "$2" _fzf_compgen_dir \213    "" "/" ""214}215216_fzf_feed_fifo() {217  command rm -f "$1"218  command mkfifo "$1" || return219  cat <&0 > "$1" &|220}221222_fzf_complete() {223  setopt localoptions ksh_arrays224  # Split arguments around --225  local args rest str_arg i sep226  args=("$@")227  sep=228  for i in {0..${#args[@]}}; do229    if [[ "${args[$i]-}" = -- ]]; then230      sep=$i231      break232    fi233  done234  if [[ -n "$sep" ]]; then235    str_arg=236    rest=("${args[@]:$((sep + 1)):${#args[@]}}")237    args=("${args[@]:0:$sep}")238  else239    str_arg=$1240    args=()241    shift242    rest=("$@")243  fi244245  local fifo fifo_dir lbuf matches post246  fifo_dir=$(command mktemp -d "${TMPDIR:-/tmp}/fzf-completion-XXXXXX") || return247  fifo="$fifo_dir/fifo"248  lbuf=${rest[0]}249  post="${funcstack[1]}_post"250  type $post > /dev/null 2>&1 || post=cat251252  _fzf_feed_fifo "$fifo"253  matches=$(254    FZF_DEFAULT_OPTS=$(__fzf_defaults "--reverse" "${FZF_COMPLETION_OPTS-} $str_arg") \255    FZF_DEFAULT_OPTS_FILE='' \256      __fzf_comprun "$cmd_word" "${args[@]}" -q "${(Q)prefix}" < "$fifo" | $post | tr '\n' ' ')257  if [ -n "$matches" ]; then258    LBUFFER="$lbuf$matches"259  fi260  command rm -rf "$fifo_dir"261}262263# To use custom hostname lists, override __fzf_list_hosts.264# The function is expected to print hostnames, one per line as well as in the265# desired sorting and with any duplicates removed, to standard output.266if ! declare -f __fzf_list_hosts > /dev/null; then267  __fzf_list_hosts() {268    command sort -u \269      <(270        # Note: To make the pathname expansion of "~/.ssh/config.d/*" work271        # properly, we need to adjust the related shell options.  We need to272        # unset "NO_GLOB" (or reset "GLOB"), which disable the pathname273        # expansion totally.  We need to unset "DOT_GLOB" and set "CASE_GLOB"274        # to avoid matching unwanted files.  We need to set "NULL_GLOB" to275        # avoid attempting to read the literal filename '~/.ssh/config.d/*'276        # when no matching is found.277        setopt GLOB NO_DOT_GLOB CASE_GLOB NO_NOMATCH NULL_GLOB278279        __fzf_exec_awk '280          # Note: mawk <= 1.3.3-20090705 does not support the POSIX brackets of281          # the form [[:blank:]], and Ubuntu 18.04 LTS still uses this282          # 16-year-old mawk unfortunately.  We need to use [ \t] instead.283          match(tolower($0), /^[ \t]*host(name)?[ \t]*[ \t=]/) {284            $0 = substr($0, RLENGTH + 1) # Remove "Host(name)?=?"285            sub(/#.*/, "")286            for (i = 1; i <= NF; i++)287              if ($i !~ /[*?%]/)288                print $i289          }290        ' ~/.ssh/config ~/.ssh/config.d/* /etc/ssh/ssh_config 2> /dev/null291      ) \292      <(293        __fzf_exec_awk -F ',' '294          match($0, /^[][a-zA-Z0-9.,:-]+/) {295            $0 = substr($0, 1, RLENGTH)296            gsub(/[][]|:[^,]*/, "")297            for (i = 1; i <= NF; i++)298              print $i299          }300        ' ~/.ssh/known_hosts 2> /dev/null301      ) \302      <(303        __fzf_exec_awk '304          {305            sub(/#.*/, "")306            for (i = 2; i <= NF; i++)307              if ($i != "0.0.0.0")308                print $i309          }310        ' /etc/hosts 2> /dev/null311      )312  }313fi314315_fzf_complete_telnet() {316  _fzf_complete +m -- "$@" < <(__fzf_list_hosts)317}318319# The first and the only argument is the LBUFFER without the current word that contains the trigger.320# The current word without the trigger is in the $prefix variable passed from the caller.321_fzf_complete_ssh() {322  local -a tokens323  tokens=(${(z)1})324  case ${tokens[-1]} in325    -i|-F|-E)326      _fzf_path_completion "$prefix" "$1"327      ;;328    *)329      local user330      [[ $prefix =~ @ ]] && user="${prefix%%@*}@"331      _fzf_complete +m -- "$@" < <(__fzf_list_hosts | __fzf_exec_awk -v user="$user" '{print user $0}')332      ;;333  esac334}335336_fzf_complete_export() {337  _fzf_complete -m -- "$@" < <(338    declare -xp | sed 's/=.*//' | sed 's/.* //'339  )340}341342_fzf_complete_unset() {343  _fzf_complete -m -- "$@" < <(344    declare -xp | sed 's/=.*//' | sed 's/.* //'345  )346}347348_fzf_complete_unalias() {349  _fzf_complete +m -- "$@" < <(350    alias | sed 's/=.*//'351  )352}353354_fzf_complete_kill() {355  local transformer356  transformer='357    if [[ $FZF_KEY =~ ctrl|alt|shift ]] && [[ -n $FZF_NTH ]]; then358      nths=( ${FZF_NTH//,/ } )359      new_nths=()360      found=0361      for nth in ${nths[@]}; do362        if [[ $nth = $FZF_CLICK_HEADER_NTH ]]; then363          found=1364        else365          new_nths+=($nth)366        fi367      done368      [[ $found = 0 ]] && new_nths+=($FZF_CLICK_HEADER_NTH)369      new_nths=${new_nths[*]}370      new_nths=${new_nths// /,}371      echo "change-nth($new_nths)+change-prompt($new_nths> )"372    else373      if [[ $FZF_NTH = $FZF_CLICK_HEADER_NTH ]]; then374        echo "change-nth()+change-prompt(> )"375      else376        echo "change-nth($FZF_CLICK_HEADER_NTH)+change-prompt($FZF_CLICK_HEADER_WORD> )"377      fi378    fi379  '380  _fzf_complete -m --header-lines=1 --no-preview --wrap --color fg:dim,nth:regular \381    --bind "click-header:transform:$transformer" -- "$@" < <(382    command ps -eo user,pid,ppid,start,time,command 2> /dev/null ||383      command ps -eo user,pid,ppid,time,args 2> /dev/null || # For BusyBox384      command ps --everyone --full --windows # For cygwin385  )386}387388_fzf_complete_kill_post() {389  __fzf_exec_awk '{print $2}'390}391392fzf-completion() {393  local tokens prefix trigger tail matches lbuf d_cmds cursor_pos cmd_word394  setopt localoptions noshwordsplit noksh_arrays noposixbuiltins395396  # http://zsh.sourceforge.net/FAQ/zshfaq03.html397  # http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion-Flags398  tokens=(${(z)LBUFFER})399  if [ ${#tokens} -lt 1 ]; then400    zle ${fzf_default_completion:-expand-or-complete}401    return402  fi403404  # Explicitly allow for empty trigger.405  trigger=${FZF_COMPLETION_TRIGGER-'**'}406  [[ -z $trigger && ${LBUFFER[-1]} == ' ' ]] && tokens+=("")407408  # When the trigger starts with ';', it becomes a separate token409  if [[ ${LBUFFER} = *"${tokens[-2]-}${tokens[-1]}" ]]; then410    tokens[-2]="${tokens[-2]-}${tokens[-1]}"411    tokens=(${tokens[0,-2]})412  fi413414  lbuf=$LBUFFER415  tail=${LBUFFER:$(( ${#LBUFFER} - ${#trigger} ))}416417  # Trigger sequence given418  if [ ${#tokens} -gt 1 -a "$tail" = "$trigger" ]; then419    d_cmds=(${=FZF_COMPLETION_DIR_COMMANDS-cd pushd rmdir})420421    {422      cursor_pos=$CURSOR423      # Move the cursor before the trigger to preserve word array elements when424      # trigger chars like ';' or '`' would otherwise reset the 'words' array.425      CURSOR=$((cursor_pos - ${#trigger} - 1))426      # Check if at least one completion system (old or new) is active.427      # If at least one user-defined completion widget is detected, nothing will428      # be completed if neither the old nor the new completion system is enabled.429      # In such cases, the 'zsh/compctl' module is loaded as a fallback.430      if ! zmodload -F zsh/parameter p:functions 2>/dev/null || ! (( ${+functions[compdef]} )); then431        zmodload -F zsh/compctl 2>/dev/null432      fi433      # Create a completion widget to access the 'words' array (man zshcompwid)434      zle -C __fzf_extract_command .complete-word __fzf_extract_command435      zle __fzf_extract_command436    } always {437      CURSOR=$cursor_pos438      # Delete the completion widget439      zle -D __fzf_extract_command  2>/dev/null440    }441442    [ -z "$trigger"      ] && prefix=${tokens[-1]} || prefix=${tokens[-1]:0:-${#trigger}}443    if [[ $prefix = *'$('* ]] || [[ $prefix = *'<('* ]] || [[ $prefix = *'>('* ]] || [[ $prefix = *':='* ]] || [[ $prefix = *'`'* ]]; then444      return445    fi446    [ -n "${tokens[-1]}" ] && lbuf=${lbuf:0:-${#tokens[-1]}}447448    if eval "noglob type _fzf_complete_${cmd_word} >/dev/null"; then449      prefix="$prefix" eval _fzf_complete_${cmd_word} ${(q)lbuf}450      zle reset-prompt451    elif [ ${d_cmds[(i)$cmd_word]} -le ${#d_cmds} ]; then452      _fzf_dir_completion "$prefix" "$lbuf"453    else454      _fzf_path_completion "$prefix" "$lbuf"455    fi456  # Fall back to default completion457  else458    zle ${fzf_default_completion:-expand-or-complete}459  fi460}461462[ -z "$fzf_default_completion" ] && {463  binding=$(bindkey '^I')464  [[ $binding =~ 'undefined-key' ]] || fzf_default_completion=$binding[(s: :w)2]465  unset binding466}467468# Normal widget469zle     -N   fzf-completion470bindkey '^I' fzf-completion471fi472473} always {474  # Restore the original options.475  eval $__fzf_completion_options476  'unset' '__fzf_completion_options'477}