Emacs: Copy/Cut Current Line If No Selection

By Xah Lee. Date: . Last updated: .

This page shows you emacs copy/cut commands that will copy/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))))))
(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 2015-12-30"
  (let (ξp1 ξp2)
    (if current-prefix-arg
        (setq ξp1 (point-min) ξp2 (point-max))
      (if (use-region-p)
          (setq ξp1 (region-beginning) ξp2 (region-end))
        (setq ξp1 (line-beginning-position) ξp2 (line-end-position))))
    (if (eq last-command this-command)
          ;; (push-mark (point) "NOMSG" "ACTIVATE")
          (kill-append "\n" nil)
          (forward-line 1)
          (kill-append (buffer-substring-no-properties (line-beginning-position) (line-end-position)) nil)
          (message "Line copy appended"))
        (kill-ring-save ξp1 ξp2)
        (if current-prefix-arg
            (message "Buffer text copied")
          (message "Text copied"))))))

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.

You need to give them a key. 〔➤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 is inspired from http://www.emacswiki.org/emacs/SlickCopy. Thanks to Joseph O'Donnell for mentioning this. Apparently, this behavior is default in VisualStudio, TextMate, Sublime Text, SlickEdit.

Copy/Cut All or Selection

See also: Emacs: Copy/Cut All or Selection.

Like it? Buy Xah Emacs Tutorial. Thanks.