When Emacs saves a file (save-buffer, write-file etc.), does it overwrite files directly or does it create a temporary file first?

More specifically, if I edit /path-to/file.txt, will Emacs directly open that file and overwrite the contents in-place, or will it write to a temporary file and replace the original file by it after successfully closing the file handle?

The latter convention is seen in a lot of other software. If Emacs has this behavior, or can be configured to use it, for my purposes it would be safe to disable backup files (M-x customize-variable make-backup-files).

1 Answer 1


As an answer I cite here mostly the comments of the normal execution path in basic-save-buffer-2 which is the working horse of save-buffer:

      ;; Write temp name, then rename it.
      ;; This requires write access to the containing dir,
      ;; which is why we don't try it if we don't have that access.
        ;; Create temp files with strict access rights.  It's easy to
        ;; loosen them later, whereas it's impossible to close the
        ;; time-window of loose permissions otherwise.
          ;; Call write-region in the appropriate way
          ;; for saving the buffer.
          (write-region nil nil tempname nil realname
          ;; If we failed, restore the buffer's modtime.
        ;; Since we have created an entirely new file,
        ;; make sure it gets the right permission bits set.
        ;; We succeeded in writing the temp file,
        ;; so rename it.
        (rename-file tempname buffer-file-name t)

So in the normal case you are right that Emacs writes to a temp file and changes its name later to the value of buffer-file-name which is the name of the original file.

But, note that there are bypasses that circumvent the normal execution. See, e.g., the doc strings of the variables write-file-functions and write-contents-functions.

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.