ZSH: adds ^n keybinding to expand current word's filename

This is useful if I want to edit a script but I'm not in my scripts
directory. It will look for a file with the name I have typed and
replace it.

for example:
    vim yt<^n>
will be replaced with
    vim /home/jonathan/.bin/yt

The script will first try `which <filename>`, searching the path. If
that fails, it will do `locate "*/filename"` which will search for the
file elsewhere
This commit is contained in:
Jonathan Hodgson 2021-08-31 10:46:58 +01:00
parent afb31a7589
commit fb3fb4365e

View file

@ -153,4 +153,26 @@ zle -N swap_command
bindkey '\ec' swap_command
find_current_file(){
tokens=(${(z)LBUFFER})
local lastWord="${tokens[-1]}" filepath
# First assume I'm trying to edit a script. If it's in my path, use it
filepath="$(which "$lastWord")"
if [ "$?" -eq 0 ]; then
tokens[-1]="$filepath"
LBUFFER="${tokens[@]}"
return 0
fi
# Next try locate with an exact filename match
filepath="$(locate "*/$lastWord")"
if [ "$?" -eq 0 ]; then
tokens[-1]="$filepath"
LBUFFER="${tokens[@]}"
return 0
fi
}
zle -N find_current_file
# ctrl + n
bindkey '^n' find_current_file