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:
- Jump to the beginning of the line (
- Kill the current line (
- Put it back where it was (
- Open a new line and move to it
- Yank it again to duplicate it (
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.
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.