I would like to be able to save a copy (or a snapshot) of a buffer into a file. The behavior would be similar to write-file, except that it would not set the buffer to visit this file.

For a usecase, imagine that you have a shell session, and you want to quickly save it all into a log file. The buffer should not be renamed (so that functions relying on the buffer name still work), and it should not be visiting a file (so that the file is not accidentally overwritten, and there is no warning when exitting emacs).

I can imagine a few dirty ways of doing this, I will post one as a self-answer, but reading from the manual, the whole "visited file" system is more complicated than it looks, and I guess it is easy to draft a wrong solution. Is there a hidden, built-in, way of achieving this?

2 Answers 2


Just select the entire buffer (C-x h) and use write-region.

  • 4
    You don't need to select the buffer text, if you are using write-region from Lisp (e.g. in your own command). Just pass it (point-min) and (point-max), along with the file name.
    – Drew
    Dec 28, 2014 at 3:19
  • 2
    C-x h M-x write-region Jun 24, 2015 at 8:49
  • Thank you for the select buffer and the actual M-x write-region command. Dec 10, 2017 at 19:40

Dirty elisp doing what I want to do:

(defun tv/copy-buffer-to-file (filename)
  (interactive "sFile to write? ")
  (let ((bufname (buffer-name)))
    (set-visited-file-name filename)
    (set-visited-file-name nil)
    (rename-buffer bufname)))

This looks like a lot more hassle than should be needed, since we have to take care of both the visited file and the buffer name, and we cannot be sure that we did not forget anything else.

Other solutions involving copying the buffer text in a new buffer, then saving and killing that buffer would probably work better, but I'd then be worried over performance issues with large buffers.

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.