2

In zsh, how can one know which file a completion function is defined in or comes from?

which can print the source code of a completion but it does not give any information about where I can find the file that contains the completion script. For instance, which _git in a zsh shell gives the following output:

❯❯❯ which _git
_git () {
    local _ret=1 
    local cur cword prev
    #...  (omitted) ...
    let _ret && _default && _ret=0 
    return _ret
}

whereas which git (commands or executables) gives the exact path(s):

❯❯❯ which -a git 
/opt/homebrew/bin/git
/usr/bin/git

I know the completion functions must be somewhere in $fpath, so one could search $fpath to find a _completion file.

❯❯❯ for f in $fpath; do \ls $f/_git 2>/dev/null; done 
/opt/homebrew/share/zsh/site-functions/_git
/opt/homebrew/Cellar/zsh/5.9/share/zsh/functions/_git

But is there any easy way or built-in command for doing this?

1
  • type _git gives me: _git is a shell function from /usr/share/zsh/functions/Completion/Unix/_git Nov 30, 2022 at 17:52

1 Answer 1

0

The following function is similar to the where builtin, but looks for files in $fpath. It finds functions that are loadable from a file of the same name. If there are multiple matching files, it only reports the first one.

function whence-function {
    emulate -L zsh
    local name locations ret=0
    for name; do
        locations=($^fpath/$name(N))
        if (($#locations != 0)); then
            print -l -- $locations[1]
        else
            ret=1
        fi
    done
    return $ret
}

If a function is already loaded, I don't think zsh keeps track of which file it was loaded from. So for example, once _git is loaded, a lot of auxiliary functions _git_xxx are also loaded, but something like whence-function _git_commands won't tell you where to find _git_commands, you have to guess that it comes from the same file as _git.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .