Vim's 'path'
option allows you to specify directories which commands like gf
and :find
will search for a file.
If you only want this functionality to trigger for a specific set of files, then you could use an autocmd to automatically "redirect" your :edit
command to the file in one of the 'path'
directories.
set path+=~/
function! FindInPath(name)
let found = findfile(a:name)
if !empty(found)
exe 'silent keepalt file '. fnameescape(found)
edit
endif
endfunction
autocmd BufNewFile .vimrc,.zshrc nested call FindInPath(expand('<afile>'))
This uses the BufNewFile
autocmd as a trigger for file not found, so try to find it somewhere else
. When that situation is detected, use findfile()
to try to find the file in the 'path'
directories. If it is found, change the name of the current buffer to that file and re-edit the buffer, otherwise just continue using the new buffer.
The nested
qualifier is required here since autocmds don't normally nest. In this case, you do want the typical autocmds to trigger when the :edit
command opens your file.
Note that this will still create an extra buffer as compared to just editing the file manually. By the time BufNewFile
is run, the buffer for the originally specified file name is already created. Using :file
to change the name of a buffer creates a new, unloaded buffer with the original name.
If you always want to search in 'path'
, then the autocmd can simply be changed to use the *
file pattern rather than specifying certain files.
Here's an updated version which should match your requirements better. It uses :find
to directly open the file instead of setting the buffer name based on the result of findfile()
.
function! FindInPath(name)
let path=&path
" Add any extra directories to the normal search path
set path+=~,~/.vim,/etc
" If :find finds a file, then wipeout the buffer that was created for the "new" file
setlocal bufhidden=wipe
exe 'silent! keepalt find '. fnameescape(a:name)
" Restore 'path' and 'bufhidden' to their normal values
let &path=path
set bufhidden<
endfunction
autocmd BufNewFile * nested call FindInPath(expand('<afile>'))
This solves the problem in the previous function where Vim would complain when trying to save the :file
-named buffer.