I frequently use vim to edit multiple files. On the command line, I'll type vim * or the like, and use :wn to move through the files until I get to the end.

Invariably, I get to the last file, and type :wn and get the maddening message E165: Cannot go beyond last file, when really what I want vim to do is quit at that point (:wq). Is there a configuration that controls this behavior?

  • 3
    Vim has a simple mind: you ask it to do :wn and it does :wn. If you want it to do :wq, don't tell it to do :wn, tell it to do :wq.
    – romainl
    Jul 30, 2016 at 20:08

3 Answers 3


I don't think there is a configuration option to change that behaviour. However you can create a custom command, that catches error E165 and quits in that case. Something like this should work (untested):

com! -count -bang Wnext try | <count>wn<bang> | catch /^Vim\%((\a\+)\)\=:E165/ | q | endtry
  • Hm...I tried this and it didn't work (nothing happened). I'm not familiar with custom commands in vim, and I didn't see the com command looking through the documentation...so I haven't been able to grok/debug this...I'd be happy if you pointed me at documentation.... Aug 8, 2016 at 22:10

You can define a function like this:

function! NextFileOrQuit()
  execute 'try | n | catch | try | wq! | catch | | endtry | endtry'

And then setup a normal mode mapping like so:

noremap <Tab> :call NextFileOrQuit()<CR>

With this setup, pressing <Tab> will move through the files and then "quit" once it reached the last one.


This is the normal behaviour of vi. You can do a :rew to start with the first file again. In vim you can also use :bn and :bp to go to the next or previous file. But :rew works with any vi variant.

  • I'm aware that this is the normal behavior of vim...my question was specifically how to change that normal behavior. Aug 8, 2016 at 22:05

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.