foxshell/fn/-z4h-comp-words
2025-07-04 11:48:40 -05:00

125 lines
3.3 KiB
Bash

#!/usr/bin/env zsh
() {
eval "$_z4h_opt"
local -i list_types
[[ $1 == on ]] && list_types=1
typeset -ga _z4h_naturals
if (( $#_z4h_naturals < $#_z4h_words )); then
_z4h_naturals+=({$(($#_z4h_naturals+1))..$#_z4h_words})
fi
local -A seen
local -a indices
local word idx
for word idx in "${(@)_z4h_words:^_z4h_naturals}"; do
if (( ! ${+seen[$word]} )); then
seen[$word]=1
indices+=($idx)
fi
done
-z4h-set-list-colors "$_z4h_curcontext" "$list_types"
local -i list_colors=$((!$?))
zstyle -t :completion:${_z4h_curcontext}:default sort
local -i sort=$((!$?))
autoload +X -Uz -- -z4h-cursor-show -z4h-fzf
local -i pct=60
(( _z4h_can_save_restore_screen )) && pct=100
local -i height=$(( 100 * ($#indices + 4) < pct * LINES ? $#indices + 4 : pct * LINES / 100 ))
(( height >= 6 )) || (( height = 6 ))
(( height <= LINES - 1 )) || (( height = LINES - 1 ))
local opts=(
--query=${_z4h_word_prefix:+"^$_z4h_word_prefix"}
--color=hl:201,hl+:201
--with-nth=2
--delimiter='\000'
--ansi
--exact
--no-mouse
--tiebreak=length,begin,index
--multi
--cycle
--border=horizontal
)
local cursor_y cursor_x
-z4h-get-cursor-pos || return
if (( _z4h_can_save_restore_screen )); then
opts+=(--no-clear)
if { (( height <= cursor_y - 1 )) && zstyle -T :z4h: prompt-at-bottom } ||
(( cursor_y - 1 > LINES - cursor_y && cursor_y - 1 > 6 )) &&
{ (( height > LINES - cursor_y )) || zstyle -T :z4h: prompt-at-bottom }; then
(( height <= cursor_y - 1 )) || (( height = cursor_y - 1 ))
local move=$'\e[0m\e['$((cursor_y-height))';1H'
opts+=(--layout=default)
elif (( LINES - cursor_y > 6 )); then
(( height <= LINES - cursor_y )) || (( height = LINES - cursor_y ))
local move=$'\e[0m\n\r'
opts+=(--layout=reverse)
else
local -i extra=$((height - LINES + cursor_y))
print -rnu $_z4h_tty_fd -- ${(pl:$height::\n:)} || return
(( cursor_y += LINES - cursor_y - height ))
local move=$'\e[0m\e['$((cursor_y+1))';1H'
opts+=(--layout=reverse)
fi
local _z4h_saved_screen
-z4h-save-screen || return
else
print >&$_z4h_tty_fd || return
local move=
opts+=(--layout=reverse)
fi
opts+=(--height=$height)
{
local choice
choice="$(
unsetopt pipe_fail
exec 2>/dev/null
{
# TODO: colorize files.
if (( sort )); then
local rows=()
for idx in $indices; do
rows+=($_z4h_descrs[idx]$'\0'$idx)
done
printf '%2$s\0%1$s\n' "${(@0)${(@o)rows}}"
else
for idx in $indices; do
printf '%s\0%s\n' $idx "$_z4h_descrs[idx]"
done
fi
} | {
print -rnu $_z4h_tty_fd -- $move
-z4h-cursor-show
2>&$_z4h_tty_fd -z4h-fzf $opts
}
)"
} always {
-z4h-cursor-hide
if (( _z4h_can_save_restore_screen )); then
-z4h-restore-screen
print -rn -- $'\e[0m\e['$cursor_y';'$cursor_x'H'
else
builtin echoti cuu 1
(( cursor_x > 1 )) && builtin echoti cuf $((cursor_x-1))
fi
}
[[ -n $choice ]] || return
choice=("${(@f)choice}")
typeset -g _z4h_reply=(0 ${${choice:1}%$'\0'*})
[[ -z $choice[1] ]] || _z4h_reply[1]=1
} "${options[list_types]}"