text – How do I duplicate a whole line in Emacs?

text – How do I duplicate a whole line in Emacs?

I use

C-a C-SPACE C-n M-w C-y

which breaks down to

  • C-a: move cursor to start of line
  • C-SPACE: begin a selection (set mark)
  • C-n: move cursor to next line
  • M-w: copy region
  • C-y: paste (yank)

The aforementioned

C-a C-k C-k C-y C-y

amounts to the same thing (TMTOWTDI)

  • C-a: move cursor to start of line
  • C-k: cut (kill) the line
  • C-k: cut the newline
  • C-y: paste (yank) (were back at square one)
  • C-y: paste again (now weve got two copies of the line)

These are both embarrassingly verbose compared to C-d in your editor, but in Emacs theres always a customization. C-d is bound to delete-char by default, so how about C-c C-d? Just add the following to your .emacs:

(global-set-key C-cC-d C-aC- C-nM-wC-y)

(@Nathans elisp version is probably preferable, because it wont break if any of the key bindings are changed.)

Beware: some Emacs modes may reclaim C-c C-d to do something else.

In addition to the previous answers you can also define your own function to duplicate a line. For example, putting the following in your .emacs file will make C-d duplicate the current line.

(defun duplicate-line()
  (interactive)
  (move-beginning-of-line 1)
  (kill-line)
  (yank)
  (open-line 1)
  (next-line 1)
  (yank)
)
(global-set-key (kbd C-d) duplicate-line)

text – How do I duplicate a whole line in Emacs?

Place cursor on line, if not at beginning do a CTRLA, then:

CTRLK

CTRLK

CTRLY

CTRLY

Leave a Reply

Your email address will not be published.