3

I have a list of files that I want to successively visit with find-file and then return to the first buffer. I thought that save-current-buffer would help me to achieve this. However, with the following code, the cursor ends up in one of the buffers opened by find-file, not in the buffer where save-current-buffer had been executed:

(save-current-buffer
    (dolist (file org-agenda-files)
        (find-file file)
        ;; do something with file
        ))

How can I return to the first buffer after find-file?

2 Answers 2

2

save-current-buffer, like set-buffer, controls which buffer is the current-buffer.

But it does not deal with which buffers might be displayed and which windows might be selected.

find-file not only visits file contents in a buffer - it also displays the buffer and selects its window.

You might want find-file-noselect instead of find-file.

5
  • 1
    But how can I then do something within the buffer created by find-file-noselect? I could use switch-to-buffer in order to jump to this buffer, but this amounts to using find-file.
    – Timm
    Jul 2, 2017 at 15:34
  • If you want to display a buffer, and you want to select it, then do so. If you want that then yes, find-file does that. Your question was about what save-current-buffer does. It does not take any care wrt whether a buffer is displayed or selected.
    – Drew
    Jul 2, 2017 at 22:10
  • with-current-buffer together with find-file-noselect might be what you're looking for.
    – YoungFrog
    Jul 3, 2017 at 18:36
  • @YoungFrog But with with-current-buffer I have to know the name of the buffer that is associated with each file? Could give an example?
    – Timm
    Jul 6, 2017 at 17:33
  • @Timm ffns returns the buffer. Basically you'd do (wcb (ffns ...) do things). (I'm on mobile so writing code is painful, sorry about the result)
    – YoungFrog
    Jul 6, 2017 at 23:18
0

There are two options:

1) one could enhance my code example by calling switch-to-buffer after save-current-buffer in order to jump back to the saved buffer.

(save-current-buffer
    (dolist (file org-agenda-files)
        (find-file file)
        ;; do something with file
        ))
(switch-to-buffer (current-buffer))

2) one could go for YoungFrog's proposal that uses with-current-buffer and find-file-noselect:

(dolist (file org-agenda-files)
    (with-current-buffer (find-file-noselect file)
        ;; do something with file
        ))

In my view, both options are pretty much equivalent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.