zsh suffix aliases - exceptions

805 views Asked by At

I'd like to use suffix aliases for automatically opening .py files in vim. For that, I've got alias -s py=vimin my zshrc.

However, I do have some python files that are executables in my path, for which I'd like to disable suffix completion. I could simply call the file directly with python /path/to/executable.py, but entering the path every single time is cumbersome (and counter the notion of PATH anyway).

Is there a way to exempt certain files, preferably simply those that do not reside in the current working directory from suffix aliasing? If not, does someone have pointers how to go about implementing such a functionality?

1

There are 1 answers

1
Adaephon On BEST ANSWER

There is no way to selectively disable suffix aliases for specific files before evaluating the alias.

But you could use a function to check if a file name is in your path as target for your alias. Depending on the result this function then would start the program or load the file in vim.

For example, you could add this to your .zshrc

vim_or_exec ()
{
    interps=($(whence -a "$1"))
    if [[ -z $interps[2] ]]; then
        vim "$1"
    else
        "$interps[2]" "${@:2}"
    fi
}

alias -s py=vim_or_exec

whence -a shows a list all interpretations of the given file name, ordered by precedence. With the alias set the first interpretation will be the value of the alias, that is vim_or_exec. If the file is not in $PATH (or an alias, shell function, etc.) there will be no further interpretations and the file will be loaded in vim (vim "$1"). If the there are further interpretations, the second one ("$interps[2]") will be called with any further command line parameters (${@:2}).