I run Vim inside a screen session. When that session terminates, it kills processes running inside it, causing Vim to leave behind .swp files. This is a good thing if the .swp files contain information that allows me to recover unsaved edits, but in most cases I exit screen with everything in a clean saved state (:wa). This makes the .swp files an annoyance, as they don't contain any useful information, but still cause a recovery prompt when reopening.

Can I get Vim to only maintain a .swp file when there are unsaved changes pending?


Swap files

The short answer is no. With Vim, the swap files are constantly kept open while the buffer is being edited. It could slow editing too much to open the swap file and close it every time a change is made to it (the swap file is updated after typing 200 characters or when you have not typed anything for four seconds).

If you don’t want a swap file to be used for a certain buffer or buffers, you can temporarily unset the swapfile option:

set noswapfile

To open a new buffer without using a swap file, you can use the :noswapfile modifier, e.g.,

:noswapfile edit ~/.bashrc


From your use case, it sounds like you could benefit from Vim sessions. When you’re finished editing, run mksession to save your session in a Vim script file called Session.vim in the current directory. Then type xa to write and quit all files. The next time you’re running Vim, start it in the same working directory by using

vim -S Session.vim

Alternatively, if you’ve already started Vim, you can source the session script with

:source Session.vim

See help Session for more information on this useful feature.

BTW, with regard to screen, I presume you’re only closing the screen session (rather than detaching it) because the computer is being shut down or restarted.

  • Thank you. I am using Vim sessions and my end-session workflow is (1) switch to the screen tab that has Vim running in it, (2) :xa, (3) close the terminal window that has screen in it (yes, this is on a desktop development machine and I close screen on shutdown). I was hoping for an answer that allowed me to skip (1) and (2). – jl6 Feb 21 '16 at 20:13
  • @jl6 My workflow is similar to yours aside from the fact that I'm often running GVim for editing local files rather than Vim in a terminal. I don't find it too onerous to save the Vim session before explicitly closing it. – Anthony Geoghegan Feb 21 '16 at 23:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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