ErgoEmacsEmacsLispBlogEmacsLispBuy Tutorial
Web Hosting by 1&1

Emacs: Copy/Cut Current Line If No Selection

Xah Lee, , …,

This page shows you how to customize emacs so that the Copy command will copy the current line when there's no text selection. Same for Cut.

By default, to copy/cut current line, you need to move 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.

(defun copy-line-or-region ()
  "Copy current line, or current text selection."
  (interactive)
  (if (region-active-p)
      (kill-ring-save (region-beginning) (region-end))
    (kill-ring-save (line-beginning-position) (line-beginning-position 2)) ) )

(defun cut-line-or-region ()
  "Cut the current line, or current text selection."
  (interactive)
  (if (region-active-p)
      (kill-region (region-beginning) (region-end))
    (kill-region (line-beginning-position) (line-beginning-position 2)) ) )

Put the code in your emacs init file. When you do not have a text selection, copy/cut will just copy/cut the current line. This is now part of ErgoEmacs Keybinding.

You need to give them a key. 〔☛ Emacs: How to Define Keys〕 A great hand saver is to bind them to single keys. Like this:

(global-set-key (kbd "<f2>") 'cut-line-or-region) ; cut.
(global-set-key (kbd "<f3>") 'copy-line-or-region) ; copy.
(global-set-key (kbd "<f4>") 'yank) ; paste.

The code is inspired from http://www.emacswiki.org/emacs/SlickCopy. Thanks to Joseph O'Donnell (site instantcallout.com) for mentioning this. Apparently, this behavior is default in VisualStudio, TextMate, Sublime Text, SlickEdit.

blog comments powered by Disqus