Emacs includes some interesting functionality for dealing with rectangular regions of text. But I’ve long felt as though it were only half-complete — there are many useful things that you just can’t easily do with them, such as selecting a rectangle and adding it to the kill ring in such a way that you can later yank it as though it were regular text.
It’s possible, though, if you know how, and fortunately a kind person on freenode helped me to figure out how.
;; http://emacs.stackexchange.com/a/3174 via xtreak on freenode
(defun youngfrog/copy-rectangle-to-kill-ring (start end)
"Saves a rectangle to the normal kill ring. Not suitable for yank-rectangle."
(interactive "r")
(let ((lines (extract-rectangle start end)))
(with-temp-buffer
(while lines ;; insert-rectangle, but without the unneeded stuff
;; (most importantly no push-mark)
(insert-for-yank (car lines))
(insert "\n")
(setq lines (cdr lines)))
(kill-ring-save (point-min) (point-max)))))
(defun kill-rectangle-as-text (b e)
(interactive "r")
(progn (youngfrog/copy-rectangle-to-kill-ring b e)
(delete-rectangle b e)))
Then you can select a rectangle as usual and say M-x kill-rectangle-as-text
. Later you can C-y
as usual.
The elisp looks horrible here, but it looks much better in this gist.