I’d like to copy the region to another (temporary) buffer in Emacs, but if there’s no (acive) region, I’d like to copy the whole current buffer. What I did is as follows:
(defun do-something-with-region-or-buffer ()
(interactive)
(save-excursion
(let ((begin (point-min)) (end (point-max)))
(when (region-active-p)
(setq begin (region-beginning))
(setq end (region-end)))
(copy-region-as-kill begin end)
(with-temp-buffer
(switch-to-buffer (current-buffer))
(rename-buffer "*My Temp Buffer*")
(delete-other-windows)
(yank)
(do-something-with-current-buffer)))))
However, I have a strong feeling that this is suboptimal, since I’m messing around with the kill ring. How to do it without affecting it? (Bonus question: is my way of doing things with the region or the whole buffer if there’s no active region a good one?)
That’s how I would do it:
It’s up to you to decide if you want
insert-buffer-substringorinsert-buffer-substring-no-properties, but there is no need to usekill rings.
Also it’s rather strange to do something interactively within
with-temp-buffer: are you going to run a kind of modal loop there,or is it just displaying some progress?
As of doing things with the region or the whole buffer (NB: modulo
narrowing), it’s not quite unusual (see
replace-stringandfriends).