Emacs: Copy Current Line 💠

By Xah Lee. Date: . Last updated: .

copy current line if no selection

put this in your Emacs Init File:

(defun xah-copy-line-or-region ()
  "Copy current line or selection.

Copy current line. When called repeatedly, append copy subsequent lines.
Except:

If `universal-argument' is called first, copy whole buffer (respects `narrow-to-region').
If `rectangle-mark-mode' is on, copy the rectangle.
If `region-active-p', copy the region.

URL `http://xahlee.info/emacs/emacs/emacs_copy_cut_current_line.html'
Created: 2010-05-21
Version: 2024-06-19"
  (interactive)
  (cond
   (current-prefix-arg (copy-region-as-kill (point-min) (point-max)))
   ((and (boundp 'rectangle-mark-mode) rectangle-mark-mode)
    (copy-region-as-kill (region-beginning) (region-end) t))
   ((region-active-p) (copy-region-as-kill (region-beginning) (region-end)))
   ((eq last-command this-command)
    (if (eobp)
        nil
      (progn
        (kill-append "\n" nil)
        (kill-append (buffer-substring (line-beginning-position) (line-end-position)) nil)
        (end-of-line)
        (forward-char))))
   ((eobp)
    (if (eq (char-before) 10)
        (progn)
      (progn
        (copy-region-as-kill (line-beginning-position) (line-end-position))
        (end-of-line))))
   (t
    (copy-region-as-kill (line-beginning-position) (line-end-position))
    (end-of-line)
    (forward-char))))

Cut Current Line If No Selection

put this in your Emacs Init File:

(defun xah-cut-line-or-region ()
  "Cut current line or selection.
When `universal-argument' is called first, cut whole buffer (respects `narrow-to-region').

URL `http://xahlee.info/emacs/emacs/emacs_copy_cut_current_line.html'
Version: 2010-05-21 2015-06-10"
  (interactive)
  (if current-prefix-arg
      (progn ; not using kill-region because we don't want to include previous kill
        (kill-new (buffer-string))
        (delete-region (point-min) (point-max)))
    (progn (if (region-active-p)
               (kill-region (region-beginning) (region-end) t)
             (kill-region (line-beginning-position) (line-beginning-position 2))))))

You need to give them keys. 〔see Emacs Keys: Define Key〕 A great hand saver is to bind them to single keys. Like this:

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

This is now part of ergoemacs-mode and Emacs: Xah Fly Keys 📦.

2010-05-21 The code was inspired from http://www.emacswiki.org/emacs/SlickCopy. Thanks to Joseph O'Donnell for mentioning it. Apparently, this behavior is default in VisualStudio, TextMate, Sublime Text, SlickEdit.

Emacs, copy paste