Home > Software design >  How can I save a buffer in Emacs without visiting it?
How can I save a buffer in Emacs without visiting it?

Time:03-13

The built-in command list-buffers creates a buffer called *Buffer List* which can be saved to a file using C-x C-s. Is there some way to automate this so that I can enter something like list-buffers-to-file and have the output file created automatically, without having to leave the buffer I'm working in?

When I execute list-buffers, the window I'm working in is split and a buffer named *Buffer List* appears in the lower pane. I then have to C-x o to move to the *Buffer List* buffer and save it, then C-x o back to the buffer I was working in and type C-x 1 to remove the other pane. I would like to avoid the splitting of the window, and actually do not need to see the *Buffer List* buffer at all, but I cannot figure out how to do this. All of the buffer-saving elisp commands seem to work on the current buffer only, which means having to leave the buffer I'm working in. There doesn't seem to be a command like save-other-buffer buffer-name file-to-save-in. Is there some way to do this?

CodePudding user response:

This should do what you want.

(defun save-buf-list (&optional arg)
  "Write `list-buffers' output to file `~/somewhere/my-buflist.txt'.
A prefix arg is handled as in `list-buffers'."
  (interactive "P")
  (with-current-buffer (list-buffers-noselect arg)
    (write-file "~/somewhere/my-buflist.txt")))

If you want to be able to write the buffers to different files, you can add an arg for the FILE and prompt for that first.

To find this for yourself, check the code defining list-buffers (C-h f list-buffers, then click the file name). That command is defined with just this code:

(display-buffer (list-buffers-noselect arg))

So you know that list-buffers-noselect must return a buffer (which is what display-buffer needs). And C-h f list-buffers-noselect` confirms this.

Then all you need to know is how to write a given buffer to a given file. write-file writes the current buffer to a file. And macro with-current-buffer does stuff with a given buffer current.

  • Related