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.


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)
            execute ":find! ".a:path

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?


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.

  • 1
    could it be a missing nested? Commented May 9, 2017 at 7:50
  • What's a nested? :help nested finds try-nested, which doesn't seem to apply
    – aghast
    Commented May 9, 2017 at 16:14
  • 3
    See :h autocmd-nested Commented May 10, 2017 at 10:14
  • Super! That works, although it's about a second slower. Thanks very much!
    – aghast
    Commented May 10, 2017 at 18:02


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.