Debian Codegraph @

shell/completion.zsh

raw
1 # ____ ____
2 # / __/___ / __/
3 # / /_/_ / / /_
4 # / __/ / /_/ __/
5 # /_/ /___/_/ completion.zsh
6 #
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)
11
12
13 # Both branches of the following `if` do the same thing -- define
14 # __fzf_completion_options such that `eval $__fzf_completion_options` sets
15 # all options to the same values they currently have. We'll do just that at
16 # 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 quoted
19 # *must* be quoted in order to prevent alias expansion. In addition, code must
20 # be written in a way works with any set of zsh options. This is very tricky, so
21 # 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.
25 if 'zmodload' 'zsh/parameter' 2>'/dev/null' && (( ${+options} )); then
26 # 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 elements
30 # together separated by spaces. __fzf_completion_options ends up with a value
31 # like this: "options=(shwordsplit off aliases on ...)".
32 __fzf_completion_options="options=(${(j: :)${(kv)options[@]}})"
33 else
34 # This branch is much slower because it forks to get the names of all
35 # zsh options. It's possible to eliminate this fork but it's not worth the
36 # trouble because this branch gets taken only on very ancient or broken
37 # zsh installations.
38 () {
39 # That `()` above defines an anonymous function. This is essentially a scope
40 # 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 option
44 # 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 expansion
46 # removes spaces and everything that follow them on every line. __fzf_opt
47 # ends up iterating over option names: shwordsplit, aliases, etc.
48 for __fzf_opt in "${(@)${(@f)$(set -o)}%% *}"; do
49 if [[ -o "$__fzf_opt" ]]; then
50 # Option $__fzf_opt is currently on, so remember to set it back on.
51 __fzf_completion_options+=" -o $__fzf_opt"
52 else
53 # Option $__fzf_opt is currently off, so remember to set it back off.
54 __fzf_completion_options+=" +o $__fzf_opt"
55 fi
56 done
57 # The value of __fzf_completion_options here looks like this:
58 # "setopt +o shwordsplit -o aliases ..."
59 }
60 fi
61
62 # Enable the default zsh options (those marked with <Z> in `man zshoptions`)
63 # but without `aliases`. Aliases in functions are expanded when functions are
64 # defined, so if we disable aliases here, we'll be sure to have no pesky
65 # aliases in any of our functions. This way we won't need prefix every
66 # command with `command` or to quote every word to defend against global
67 # aliases. Note that `aliases` is not the only option that's important to
68 # control. There are several others that could wreck havoc if they are set
69 # to values we don't expect. With the following `emulate` command we
70 # sidestep this issue entirely.
71 'builtin' 'emulate' 'zsh' && 'builtin' 'setopt' 'no_aliases'
72
73 # This brace is the start of try-always block. The `always` part is like
74 # `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.
78 if [[ -o interactive ]]; then
79
80 # 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 # }
94
95 ###########################################################
96
97 #----BEGIN INCLUDE common.sh
98 # 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 apply
100 # the changes. See code comments in "common.sh" for the implementation details.
101
102 __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/null
105 builtin printf '%s\n' "${FZF_DEFAULT_OPTS-} $2"
106 }
107
108 __fzf_exec_awk() {
109 if [[ -z ${__fzf_awk-} ]]; then
110 __fzf_awk=awk
111 if [[ $OSTYPE == solaris* && -x /usr/xpg4/bin/awk ]]; then
112 __fzf_awk=/usr/xpg4/bin/awk
113 elif command -v mawk > /dev/null 2>&1; then
114 local n x y z d
115 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=mawk
120 fi
121 fi
122 LC_ALL=C exec "$__fzf_awk" "$@"
123 }
124 #----END INCLUDE
125
126 __fzf_comprun() {
127 if [[ "$(type _fzf_comprun 2>&1)" =~ function ]]; then
128 _fzf_comprun "$@"
129 elif [ -n "${TMUX_PANE-}" ] && { [ "${FZF_TMUX:-0}" != 0 ] || [ -n "${FZF_TMUX_OPTS-}" ]; }; then
130 shift
131 if [ -n "${FZF_TMUX_OPTS-}" ]; then
132 fzf-tmux ${(Q)${(Z+n+)FZF_TMUX_OPTS}} -- "$@"
133 else
134 fzf-tmux -d ${FZF_TMUX_HEIGHT:-40%} -- "$@"
135 fi
136 else
137 shift
138 fzf "$@"
139 fi
140 }
141
142 # 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 nothing
145 compstate[insert]=
146 compstate[list]=
147 cmd_word="${(Q)words[1]}"
148 }
149
150 __fzf_generic_path_completion() {
151 local base lbuf compgen fzf_opts suffix tail dir leftover matches
152 base=$1
153 lbuf=$2
154 compgen=$3
155 fzf_opts=$4
156 suffix=$5
157 tail=$6
158
159 setopt localoptions nonomatch
160 if [[ $base = *'$('* ]] || [[ $base = *'<('* ]] || [[ $base = *'>('* ]] || [[ $base = *':='* ]] || [[ $base = *'`'* ]]; then
161 return
162 fi
163 eval "base=$base" 2> /dev/null || return
164 [[ $base = *"/"* ]] && dir="$base"
165 while [ 1 ]; do
166 if [[ -z "$dir" || -d ${dir} ]]; then
167 leftover=${base/#"$dir"}
168 leftover=${leftover/#\/}
169 [ -z "$dir" ] && dir='.'
170 [ "$dir" != "/" ] && dir="${dir/%\//}"
171 matches=$(
172 export FZF_DEFAULT_OPTS
173 FZF_DEFAULT_OPTS=$(__fzf_defaults "--reverse --scheme=path" "${FZF_COMPLETION_OPTS-}")
174 unset FZF_DEFAULT_COMMAND FZF_DEFAULT_OPTS_FILE
175 if [[ $compgen =~ dir ]]; then
176 rest=${FZF_COMPLETION_DIR_OPTS-}
177 else
178 rest=${FZF_COMPLETION_PATH_OPTS-}
179 fi
180 if declare -f "$compgen" > /dev/null; then
181 eval "$compgen $(printf %q "$dir")" | __fzf_comprun "$cmd_word" ${(Q)${(Z+n+)fzf_opts}} -q "$leftover" ${(Q)${(Z+n+)rest}}
182 else
183 if [[ $compgen =~ dir ]]; then
184 walker=dir,follow
185 else
186 walker=file,dir,follow,hidden
187 fi
188 __fzf_comprun "$cmd_word" ${(Q)${(Z+n+)fzf_opts}} -q "$leftover" --walker "$walker" --walker-root="$dir" ${(Q)${(Z+n+)rest}} < /dev/tty
189 fi | while read -r item; do
190 item="${item%$suffix}$suffix"
191 echo -n -E "${(q)item} "
192 done
193 )
194 matches=${matches% }
195 if [ -n "$matches" ]; then
196 LBUFFER="$lbuf$matches$tail"
197 fi
198 zle reset-prompt
199 break
200 fi
201 dir=$(dirname "$dir")
202 dir=${dir%/}/
203 done
204 }
205
206 _fzf_path_completion() {
207 __fzf_generic_path_completion "$1" "$2" _fzf_compgen_path \
208 "-m" "" " "
209 }
210
211 _fzf_dir_completion() {
212 __fzf_generic_path_completion "$1" "$2" _fzf_compgen_dir \
213 "" "/" ""
214 }
215
216 _fzf_feed_fifo() {
217 command rm -f "$1"
218 mkfifo "$1"
219 cat <&0 > "$1" &|
220 }
221
222 _fzf_complete() {
223 setopt localoptions ksh_arrays
224 # Split arguments around --
225 local args rest str_arg i sep
226 args=("$@")
227 sep=
228 for i in {0..${#args[@]}}; do
229 if [[ "${args[$i]-}" = -- ]]; then
230 sep=$i
231 break
232 fi
233 done
234 if [[ -n "$sep" ]]; then
235 str_arg=
236 rest=("${args[@]:$((sep + 1)):${#args[@]}}")
237 args=("${args[@]:0:$sep}")
238 else
239 str_arg=$1
240 args=()
241 shift
242 rest=("$@")
243 fi
244
245 local fifo lbuf matches post
246 fifo="${TMPDIR:-/tmp}/fzf-complete-fifo-$$"
247 lbuf=${rest[0]}
248 post="${funcstack[1]}_post"
249 type $post > /dev/null 2>&1 || post=cat
250
251 _fzf_feed_fifo "$fifo"
252 matches=$(
253 FZF_DEFAULT_OPTS=$(__fzf_defaults "--reverse" "${FZF_COMPLETION_OPTS-} $str_arg") \
254 FZF_DEFAULT_OPTS_FILE='' \
255 __fzf_comprun "$cmd_word" "${args[@]}" -q "${(Q)prefix}" < "$fifo" | $post | tr '\n' ' ')
256 if [ -n "$matches" ]; then
257 LBUFFER="$lbuf$matches"
258 fi
259 command rm -f "$fifo"
260 }
261
262 # To use custom hostname lists, override __fzf_list_hosts.
263 # The function is expected to print hostnames, one per line as well as in the
264 # desired sorting and with any duplicates removed, to standard output.
265 if ! declare -f __fzf_list_hosts > /dev/null; then
266 __fzf_list_hosts() {
267 command sort -u \
268 <(
269 # Note: To make the pathname expansion of "~/.ssh/config.d/*" work
270 # properly, we need to adjust the related shell options. We need to
271 # unset "NO_GLOB" (or reset "GLOB"), which disable the pathname
272 # expansion totally. We need to unset "DOT_GLOB" and set "CASE_GLOB"
273 # to avoid matching unwanted files. We need to set "NULL_GLOB" to
274 # avoid attempting to read the literal filename '~/.ssh/config.d/*'
275 # when no matching is found.
276 setopt GLOB NO_DOT_GLOB CASE_GLOB NO_NOMATCH NULL_GLOB
277
278 __fzf_exec_awk '
279 # Note: mawk <= 1.3.3-20090705 does not support the POSIX brackets of
280 # the form [[:blank:]], and Ubuntu 18.04 LTS still uses this
281 # 16-year-old mawk unfortunately. We need to use [ \t] instead.
282 match(tolower($0), /^[ \t]*host(name)?[ \t]*[ \t=]/) {
283 $0 = substr($0, RLENGTH + 1) # Remove "Host(name)?=?"
284 sub(/#.*/, "")
285 for (i = 1; i <= NF; i++)
286 if ($i !~ /[*?%]/)
287 print $i
288 }
289 ' ~/.ssh/config ~/.ssh/config.d/* /etc/ssh/ssh_config 2> /dev/null
290 ) \
291 <(
292 __fzf_exec_awk -F ',' '
293 match($0, /^[][a-zA-Z0-9.,:-]+/) {
294 $0 = substr($0, 1, RLENGTH)
295 gsub(/[][]|:[^,]*/, "")
296 for (i = 1; i <= NF; i++)
297 print $i
298 }
299 ' ~/.ssh/known_hosts 2> /dev/null
300 ) \
301 <(
302 __fzf_exec_awk '
303 {
304 sub(/#.*/, "")
305 for (i = 2; i <= NF; i++)
306 if ($i != "0.0.0.0")
307 print $i
308 }
309 ' /etc/hosts 2> /dev/null
310 )
311 }
312 fi
313
314 _fzf_complete_telnet() {
315 _fzf_complete +m -- "$@" < <(__fzf_list_hosts)
316 }
317
318 # The first and the only argument is the LBUFFER without the current word that contains the trigger.
319 # The current word without the trigger is in the $prefix variable passed from the caller.
320 _fzf_complete_ssh() {
321 local -a tokens
322 tokens=(${(z)1})
323 case ${tokens[-1]} in
324 -i|-F|-E)
325 _fzf_path_completion "$prefix" "$1"
326 ;;
327 *)
328 local user
329 [[ $prefix =~ @ ]] && user="${prefix%%@*}@"
330 _fzf_complete +m -- "$@" < <(__fzf_list_hosts | __fzf_exec_awk -v user="$user" '{print user $0}')
331 ;;
332 esac
333 }
334
335 _fzf_complete_export() {
336 _fzf_complete -m -- "$@" < <(
337 declare -xp | sed 's/=.*//' | sed 's/.* //'
338 )
339 }
340
341 _fzf_complete_unset() {
342 _fzf_complete -m -- "$@" < <(
343 declare -xp | sed 's/=.*//' | sed 's/.* //'
344 )
345 }
346
347 _fzf_complete_unalias() {
348 _fzf_complete +m -- "$@" < <(
349 alias | sed 's/=.*//'
350 )
351 }
352
353 _fzf_complete_kill() {
354 local transformer
355 transformer='
356 if [[ $FZF_KEY =~ ctrl|alt|shift ]] && [[ -n $FZF_NTH ]]; then
357 nths=( ${FZF_NTH//,/ } )
358 new_nths=()
359 found=0
360 for nth in ${nths[@]}; do
361 if [[ $nth = $FZF_CLICK_HEADER_NTH ]]; then
362 found=1
363 else
364 new_nths+=($nth)
365 fi
366 done
367 [[ $found = 0 ]] && new_nths+=($FZF_CLICK_HEADER_NTH)
368 new_nths=${new_nths[*]}
369 new_nths=${new_nths// /,}
370 echo "change-nth($new_nths)+change-prompt($new_nths> )"
371 else
372 if [[ $FZF_NTH = $FZF_CLICK_HEADER_NTH ]]; then
373 echo "change-nth()+change-prompt(> )"
374 else
375 echo "change-nth($FZF_CLICK_HEADER_NTH)+change-prompt($FZF_CLICK_HEADER_WORD> )"
376 fi
377 fi
378 '
379 _fzf_complete -m --header-lines=1 --no-preview --wrap --color fg:dim,nth:regular \
380 --bind "click-header:transform:$transformer" -- "$@" < <(
381 command ps -eo user,pid,ppid,start,time,command 2> /dev/null ||
382 command ps -eo user,pid,ppid,time,args 2> /dev/null || # For BusyBox
383 command ps --everyone --full --windows # For cygwin
384 )
385 }
386
387 _fzf_complete_kill_post() {
388 __fzf_exec_awk '{print $2}'
389 }
390
391 fzf-completion() {
392 local tokens prefix trigger tail matches lbuf d_cmds cursor_pos cmd_word
393 setopt localoptions noshwordsplit noksh_arrays noposixbuiltins
394
395 # http://zsh.sourceforge.net/FAQ/zshfaq03.html
396 # http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion-Flags
397 tokens=(${(z)LBUFFER})
398 if [ ${#tokens} -lt 1 ]; then
399 zle ${fzf_default_completion:-expand-or-complete}
400 return
401 fi
402
403 # Explicitly allow for empty trigger.
404 trigger=${FZF_COMPLETION_TRIGGER-'**'}
405 [[ -z $trigger && ${LBUFFER[-1]} == ' ' ]] && tokens+=("")
406
407 # When the trigger starts with ';', it becomes a separate token
408 if [[ ${LBUFFER} = *"${tokens[-2]-}${tokens[-1]}" ]]; then
409 tokens[-2]="${tokens[-2]-}${tokens[-1]}"
410 tokens=(${tokens[0,-2]})
411 fi
412
413 lbuf=$LBUFFER
414 tail=${LBUFFER:$(( ${#LBUFFER} - ${#trigger} ))}
415
416 # Trigger sequence given
417 if [ ${#tokens} -gt 1 -a "$tail" = "$trigger" ]; then
418 d_cmds=(${=FZF_COMPLETION_DIR_COMMANDS-cd pushd rmdir})
419
420 {
421 cursor_pos=$CURSOR
422 # Move the cursor before the trigger to preserve word array elements when
423 # trigger chars like ';' or '`' would otherwise reset the 'words' array.
424 CURSOR=$((cursor_pos - ${#trigger} - 1))
425 # Check if at least one completion system (old or new) is active.
426 # If at least one user-defined completion widget is detected, nothing will
427 # be completed if neither the old nor the new completion system is enabled.
428 # In such cases, the 'zsh/compctl' module is loaded as a fallback.
429 if ! zmodload -F zsh/parameter p:functions 2>/dev/null || ! (( ${+functions[compdef]} )); then
430 zmodload -F zsh/compctl 2>/dev/null
431 fi
432 # Create a completion widget to access the 'words' array (man zshcompwid)
433 zle -C __fzf_extract_command .complete-word __fzf_extract_command
434 zle __fzf_extract_command
435 } always {
436 CURSOR=$cursor_pos
437 # Delete the completion widget
438 zle -D __fzf_extract_command 2>/dev/null
439 }
440
441 [ -z "$trigger" ] && prefix=${tokens[-1]} || prefix=${tokens[-1]:0:-${#trigger}}
442 if [[ $prefix = *'$('* ]] || [[ $prefix = *'<('* ]] || [[ $prefix = *'>('* ]] || [[ $prefix = *':='* ]] || [[ $prefix = *'`'* ]]; then
443 return
444 fi
445 [ -n "${tokens[-1]}" ] && lbuf=${lbuf:0:-${#tokens[-1]}}
446
447 if eval "noglob type _fzf_complete_${cmd_word} >/dev/null"; then
448 prefix="$prefix" eval _fzf_complete_${cmd_word} ${(q)lbuf}
449 zle reset-prompt
450 elif [ ${d_cmds[(i)$cmd_word]} -le ${#d_cmds} ]; then
451 _fzf_dir_completion "$prefix" "$lbuf"
452 else
453 _fzf_path_completion "$prefix" "$lbuf"
454 fi
455 # Fall back to default completion
456 else
457 zle ${fzf_default_completion:-expand-or-complete}
458 fi
459 }
460
461 [ -z "$fzf_default_completion" ] && {
462 binding=$(bindkey '^I')
463 [[ $binding =~ 'undefined-key' ]] || fzf_default_completion=$binding[(s: :w)2]
464 unset binding
465 }
466
467 # Normal widget
468 zle -N fzf-completion
469 bindkey '^I' fzf-completion
470 fi
471
472 } always {
473 # Restore the original options.
474 eval $__fzf_completion_options
475 'unset' '__fzf_completion_options'
476 }