14

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?

T. Verron
  • 4,233
  • 1
  • 22
  • 55

2 Answers2

22

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

Sean
  • 929
  • 4
  • 13
0

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)
    (save-buffer)
    (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.

T. Verron
  • 4,233
  • 1
  • 22
  • 55