Duplicate the current line in Emacs


/img/2022-05-23-emacs-duplicate-current-line.png
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."
  (interactive)
  (move-beginning-of-line 1)
  (kill-line)
  (yank)
  (open-line 1)
  (next-line 1)
  (yank))

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
                      (line-beginning-position)
                      (line-end-position))))
      (save-excursion
        (if comment-first
            (progn
              (comment-line 1)
              (move-beginning-of-line 1)
              (open-line 1))
          (move-end-of-line 1)
          (open-line 1)
          (forward-char))
        (insert line-text))
      (next-line)))

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

Emacs 

See also

comments powered by Disqus