Atomic write with Vim

Viewed 706

Can I configure Vim so it does an atomic write?

The default Vim behavior is:

  • move file.txt to file.txt~
  • write buffer contents to file.txt

But this causes some problem with compass watch for example

I would like behavior like:

  • write buffer contents to file.txt~
  • move file.txt~ to file.txt

I've looked at the backup, backupcopy and writebackup options but I can't get Vim configured as I want.

2 Answers

I'm not 100% sure how atomic writes are typically handled in arbitrary software. I could be wrong, but something like this is probably handled or configurable at the kernel level (and that would seem like the optimal place to handle such a notion as atomic writes for multiple reasons such as: efficiency, direct access to hardware, the DRY principle, application agnosticism, etc.). A more manual and user-space way that I can think of accomplishing this however would be to first write to some new/unique/random file inside of /tmp, then mv that file that you just wrote under /tmp into place. You can use Vim's tempname() function to help you accomplish this in a platform-agnostic manner (see :help tempname()).

Related