Kind reader William Annis noticed how clumsily i copied a line in the kill ring in my last screencast. I went to the beginning of the line (
C-a), killed it (
C-k) so i got it in my kill-ring, and yanked it back (
C-y). Admittedly, a bit cumbersome, my only excuse being that i have this keystroke sequence hardwired in my nervous system from the dawn of my emacs times; approximately the same epoch when i put in my .emacs this setting to make
kill-line eat also the final carry return:
(setq kill-whole-line t)
But, as William notices, there’re better ways of copying the current line. A quick one would be:
(defun jao-copy-line () "Copy current line in the kill ring" (interactive) (kill-ring-save (line-beginning-position) (line-beginning-position 2)) (message "Line copied"))
which can be easily extended to take as a prefix argument the number of lines to copy (with 1 as the default)
(defun jao-copy-line (arg) "Copy lines (as many as prefix argument) in the kill ring" (interactive "p") (kill-ring-save (line-beginning-position) (line-beginning-position (+ 1 arg))) (message "%d line%s copied" arg (if (= 1 arg) "" "s")))
Assign the new function to a handy shortcut, and you’re done. These functions have the additional benefit of leaving the point untouched.
Next thing you’ll do after using your new shiny shortcut will most probably be yanking those lines somewhere. And it may well happen that they’ll be mis-indented in their new location. A relatively quick way of realigning them is to take advantage of the fact that after a yank the region is set to the yanked text and use
indent-region, which is bound to
C-M-\. But i prefer to let Emacs do that for me, using this piece of advice in my .emacs:
(defadvice yank (after indent-region activate) (if (member major-mode '(emacs-lisp-mode scheme-mode lisp-mode c-mode c++-mode objc-mode LaTeX-mode TeX-mode)) (indent-region (region-beginning) (region-end) nil)))
where, as you can see, i’m limiting the advice to some modes: just delete the major-mode check if you want it to work everywhere.