I'd like to use my current zsh autocompletion setup but filter out some of the results. I've set up an autocompletion file and put it in my fpath so that it gets autoloaded. But there's one critical step that I haven't figured out how to do. In my code below, I'm using a glob to get the files, but I'd like to use the default zsh behavior to get the list of candidate filenames instead. For example, if I make a typo, my code below will not fix it, but zsh would do so by default.
#compdef cmd
# Filter out files from autocompletion for `cmd` if `the-filter` returns a nonzero exit code.
_cmd() {
local file
local -a candidates results
# This is the part I want to fix! It should get the list of files that `zsh` would have
# provided by default.
local prefix="${words[CURRENT]}"
candidates=( ${prefix}*(N) )
for file in $candidates; do
if ! the-filter "$file"; then
results+=( "$file" )
fi
done
# Add the filtered files to the completion list.
compadd -f "$@" "${results[@]}"
}
There is a similar question here, but it is 14 years old and never received a full working answer to the OP's question. (I'm also trying to filter results for vim right now, but I'd like to know how to do this in general.)
I have seen some examples where the _files, _path_files, or _arguments functions are used, but I haven't been able to figure out how to use them properly. It seems like they can be called within a complex ecosystem of autocompletion functions, but that I can't just call them directly to get a simple output list. The Google search AI assistant suggested that calling _files should populate the reply array used by the autocompletion system, but this also does not appear to be true.
Note that testing these things is somewhat difficult because you can only call these functions from within a completion function. I've been using set -xv and searching through the output to figure out what's actually happening, but if you know a better way, please let me know.