# Duplicate line in emacs

Quite often I find myself wanting to duplicate the line I'm standing on in my Emacs buffer. Maybe I need all or part of the text repeated below, or just the general structure to modify in place. Sometimes I create a simple template for something that I need to fill out over and over.

But duplicating a line in Emacs is not a trivial task. Here's a basic workflow for doing so:

1. Jump to the beginning of the line (C-a)
2. Kill the current line (C-k)
3. Put it back where it was (C-y)
4. Open a new line and move to it <ret>
5. Yank it again to duplicate it (C-y)

Those are 5 steps and 5 keystrokes we need for a very simple task. If, like me, you do it often enough, it gets old very quickly.

# The solution

In order to address this issue, I've created a small elisp command that does just that:

  ;;;###autoload
(defun fdx/duplicate-line()
(interactive)
(move-beginning-of-line 1)
(kill-line)
(yank)
(open-line 1)
(next-line 1)
(yank))

As I said, it does exactly what I explained earlier. In fact the only "difference" is that step 4 (which implies 2 actions with a single keystroke) is separated into opening the line and then moving, but this is just a nuance; otherwise, the process is the same.

# One keybinding and only one

Of course, the main idea for this is to have it bound to be performed by just one keystroke. I have it bound to H-d (for duplicate)

  (global-set-key (kbd "H-d") 'fdx/duplicate-line)

See you on the next one.

Saluti.