Objective
I want vi file
to act like :find file
if file
doesn't exist.
That is, I want to be able to edit a file by name, without giving a path to the file, from the command line:
mkdir -p a/b/c
touch a/b/c/foo.py
vi foo.py
When there is no file at all, I don't expect this to work. But when a file does exist, I'd like to be able to get there, just as I could with :find foo.py
.
Implementation
I have set up my path in a local vimrc file:
let proj_dir = expand('<sfile>:p:h')
setlocal path=.
let &path .= ','.proj_dir.'/**'
Then I added a function in $MYVIMRC:
function! Find_if_not_exist(path)
if ! filereadable(a:path)
try
execute ":find! ".a:path
catch
endtry
endif
endfunction
And hooked that in with an autocmd in the same file:
autocmd VimEnter * call Find_if_not_exist(expand('<afile>'))
This almost works. The file gets loaded if it exists. But when Vim opens, the filetype is unset, there is no syntax hilighting, etc.
If I just type :e!
again, the reload does get the correct filetype, syntax, etc.
If I type :find! file
directly from my keyboard, it works.
So why does the :find!
executed from inside my autocmd not get the correct behavior, and how can I fix it?
Edit:
As a temporary fix, I've added | do BufRead
to the end of my function, which gets at least some of the problem resolved. But I'd still like to know what's going on, and if there's a smoother way to get the file loaded.
try-nested
, which doesn't seem to apply:h autocmd-nested