Duplicate the current line in Emacs

Duplicate the current in Emacs

Duplicating the current line is frequent editing for me when I am coding. Initially, I copied a snippet as a command in Emacs from the Internet:

(defun w/duplicate-line()
  "Duplicate the current line."
  (move-beginning-of-line 1)
  (open-line 1)
  (next-line 1)

Most of the time, I was happy with it, but it has mainly two drawbacks:

  1. It cannot keep the column position when moving to the next line
  2. It messes up with the yank ring as it yanks the text under the hood

So today, I took some time to fix these two problems, and I also want it to be capable of commenting the current line out if I prefix the command.

Here is the improved version (it still doesn't handle the column position perfectly when the user commenting on the line first, but I am ok with it):

  (defun w/duplicate-line(comment-first)
    "Duplicate the current line."
    (interactive "P")
    (let ((line-text (buffer-substring-no-properties
        (if comment-first
              (comment-line 1)
              (move-beginning-of-line 1)
              (open-line 1))
          (move-end-of-line 1)
          (open-line 1)
        (insert line-text))

Update: Interestingly, Lars Ingebrigtsen also introduced a duplicate-line command to Emacs 29 recently, see discussions on this emacs-devel thread.


See also

comments powered by Disqus