copying lines without selecting them






When I'm programming, I often need to copy a line. Normally, this requires me
to first select ('mark') the line I want to copy. That does not seem like a
big deal, but when I'm in the 'flow' I want to avoid any little obstacle that
can slow me down.



So, how can I copy the current line without selection? I found a nice trick by
MacChan on EmacsWiki to accomplish this. It also adds ta function to kill
(cut) the current line (similar to kill-line (C-k), but kills the whole
line, not just from point (cursor) to the end.



The code below simply embellishes the normal functions with the functionality
'if nothing is selected, assume we mean the current line'. The key bindings
stay the same (M-w, C-w).



To enable this, put the following in your .emacs:





(defadvice kill-ring-save (before slick-copy activate compile) "When called
interactively with no active region, copy a single line instead."

(interactive (if mark-active (list (region-beginning) (region-end)) (message
"Copied line") (list (line-beginning-position) (line-beginning-position
2)))))

(defadvice kill-region (before slick-cut activate compile)
"When called interactively with no active region, kill a single line instead."
(interactive
(if mark-active (list (region-beginning) (region-end))
(list (line-beginning-position)
(line-beginning-position 2)))))






It also shows the power of Emacs-Lisp with the defadvice-macro – see the
fine documentation. Using defadvice, you can 'decorate' any function with
your own modifications. This great power should be used with caution, of
course, as to not break other usage that assumes the undecorated versions. In
this case, that seem unlikely. And note that the 'advise' only applies when
the functions are called interactively.


No comments:

Post a Comment

Followers

Popular Posts