I have found myself falling into a workflow where I'm often starting vim by running $ vim and then opening up the most recent file once inside.

I was wondering how to detect:

  • when vim is launched
  • which files it was launched with

so that in the case when no files are specified, I can run a custom command (such as opening the most recent file).

1 Answer 1


You could start with something like this:

function MyVimEnter()
    if argc() != 0

    if exists("v:oldfiles[0]") && filereadable(expand(v:oldfiles[0]))
        execute "e " . v:oldfiles[0]

" The 'nested' before call allows nested autocmds, important for
" syntax detection etc.
autocmd VimEnter * nested call MyVimEnter()

Whenever Vim is started and finished setup, the function MyVimEnter is called. This checks if files where given on the command line. If yes, it returns immediately. If no, it loads the last file you edited.

  • Thanks. I actually had figured it out independently. One thing that might be useful for other users is that for some reason, calling edit (e here) from the VimEnter handler doesn't trigger all the other handlers you would want. (Syntax highlighting, for instance, doesn't work). My work-around was to use a 0-second timeout: call timer_start(0, {tid -> DoRestore()}), where DoRestore is the function to conditionally edit the most recent file.
    – Tac-Tics
    Commented Jan 21, 2019 at 3:20
  • @Tac-Tics Updated. Added nested to allow nested autocmd.
    – Ralf
    Commented Jan 21, 2019 at 5:10

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.