Here is the official definition of copy-to-buffer
in Emacs 26.1 (the doc string part is omitted for brevity)
(defun copy-to-buffer (buffer start end)
(interactive "BCopy to buffer: \nr")
(let ((oldbuf (current-buffer)))
(with-current-buffer (get-buffer-create buffer)
(barf-if-buffer-read-only)
(erase-buffer)
(save-excursion
(insert-buffer-substring oldbuf start end)))))
I don't understand why it's necessary to use save-excursion
in conjoint with with-current-buffer
? As far as I'm concerned, the former is equivalent to a combination of save-excursion
and set-buffer
, so the current point would be saved and restored anyway.
In other words, I'm wondering why don't the Emacs implementers use the following piece of code, which after some experiments appears to be functionally identical to the current one.
(defun my-copy-to-buffer (buffer start end)
(interactive "BCopy to buffer: \nr")
(let ((oldbuf (current-buffer)))
(with-current-buffer (get-buffer-create buffer)
(barf-if-buffer-read-only)
(erase-buffer)
(insert-buffer-substring oldbuf start end))))
save-excursion
does not make much sense there. The content of BUFFER is replaced anyway. Maybe the reason forsave-excursion
is of historical nature. One would have to trace the log back in time. Even so I expected a slight difference between the two implementations.. I thought point should end up at the end of buffer with your impementation and stay at the beginning of buffer with the original implementation. But,insert-buffer-substring
does unexpectedly not move point to the end of the insertion?!M-: (insert-buffer-substring "*scratch*" 1 10)
point does go to the end. Maybe something in the command loop/post command hook is resetting things?current-buffer
but this movement is not shown in any window since the scope ofcurrent-buffer
is not associated with any window as long as one does not use functions likedisplay-buffer
. I did now(with-current-buffer "*work*" (insert-buffer-substring "*Help*" 1 10) (point))
which gave 10. Point did not move in any visible window.