Emacs: Copy/Cut Current Line If No Selection

By Xah Lee. Date: . Last updated: .

Here's a command to cut current line if there's no text selection.

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

URL `http://ergoemacs.org/emacs/emacs_copy_cut_current_line.html'
Version 2015-06-10"
  (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 (use-region-p)
               (kill-region (region-beginning) (region-end) t)
             (kill-region (line-beginning-position) (line-beginning-position 2))))))

Copy Line or Append Copy Line or Region

This command copy current line if there's no text selection. If called again, it'll append-copy next line. So you can press a key repeatedly to keep copying lines.

(defun xah-copy-line-or-region ()
  "Copy current line, or text selection.
When called repeatedly, append copy subsequent lines.
When `universal-argument' is called first, copy whole buffer (respects `narrow-to-region').

URL `http://ergoemacs.org/emacs/emacs_copy_cut_current_line.html'
Version 2018-09-10"
  (if current-prefix-arg
        (copy-region-as-kill (point-min) (point-max)))
    (if (use-region-p)
          (copy-region-as-kill (region-beginning) (region-end)))
      (if (eq last-command this-command)
          (if (eobp)
              (progn )
              (kill-append "\n" nil)
               (buffer-substring-no-properties (line-beginning-position) (line-end-position))
        (if (eobp)
            (if (eq (char-before) 10 )
                (progn )
                (copy-region-as-kill (line-beginning-position) (line-end-position))
            (copy-region-as-kill (line-beginning-position) (line-end-position))

Put the code in your emacs init file.

You need to give them keys. [see Emacs: How to Define Keys] 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 xah fly keys.

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.

If you have a question, put $5 at patreon and message me.
Or Buy Xah Emacs Tutorial
Or buy JavaScript in Depth

Emacs Tutorial

Emacs Init

Emacs Keys


ELisp Examples

ELisp Write Major Mode

Emacs Tutorial

Quick Start

Manage Windows




On Current File

Find Replace




Rectangle Edit

Line Wrap


View Things

Working with Brackets

Power Editing

Org Mode


Emacs Efficiency