Emacs: How to Copy/Cut Current Line

Advertise Here

, 2010-05-21, …, 2012-02-02

This page shows you how to customize emacs so that the Copy command (kill-ring-saveAlt+w】) will copy the current line when there's no text selection. Same for Cut (kill-regionCtrl+w】).

Last month, i wrote Emacs: Shortcut to Delete Whole Line, because i find that deleting whole line is much frequently needed. But also, i didn't mention that i often find the need to copy the current line too. Usually, this meas moving the cursor to beginning of line, mark, move to end of line, then copy. This is 4 operations. The following code will make it just a single operation:

(defadvice kill-ring-save (before slick-copy activate compile)
  "When called interactively with no active region, copy the current line."
  (interactive
   (if mark-active
       (list (region-beginning) (region-end))
     (progn
       (message "Current line is copied.")
       (list (line-beginning-position) (line-beginning-position 2)) ) ) ))

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

Put the code in your emacs init file. Then, select the text and call eval-region. Now, when you do not have a text selection, copy will just copy the current line. Similar for cut. Super!

This is now part of ErgoEmacs Keybinding.

A great time saver is to bind them to single keys. Like this:

(global-set-key (kbd "<f1>") 'kill-region) ; cut.
(global-set-key (kbd "<f2>") 'kill-ring-save) ; copy.
(global-set-key (kbd "<f3>") 'yank) ; paste.

I've been using this for a few years. For deletting or cutting a few lines, this is more convenient than having to set mark first.

Thanks to Joseph O'Donnell (site instantcallout.com) for mentioning this. The code is originally from emacswiki.org SlickCopy. Apparently, this behavior is default in VisualStudio, TextMate, SlickEdit.

blog comments powered by Disqus