How to duplicate a whole line in Vim?

Viewed 842006

How do I duplicate a whole line in Vim in a similar way to Ctrl+D in IntelliJ IDEA/ Resharper or Ctrl+Alt+/ in Eclipse?

21 Answers

yy or Y to copy the line (mnemonic: yank)
or
dd to delete the line (Vim copies what you deleted into a clipboard-like "register", like a cut operation)

then

p to paste the copied or deleted text after the current line
or
P to paste the copied or deleted text before the current line

yy

will yank the current line without deleting it

dd

will delete the current line

p

will put a line grabbed by either of the previous methods

Do this:

First, yy to copy the current line, and then p to paste.

If you want another way:

"ayy: This will store the line in buffer a.

"ap: This will put the contents of buffer a at the cursor.

There are many variations on this.

"a5yy: This will store the 5 lines in buffer a.

See "Vim help files for more fun.

yyp - remember it with "yippee!"

Multiple lines with a number in between:

y7yp

I like: Shift+v (to select the whole line immediately and let you select other lines if you want), y, p

Another option would be to go with:

nmap <C-d> mzyyp`z

gives you the advantage of preserving the cursor position.

You can also try <C-x><C-l> which will repeat the last line from insert mode and brings you a completion window with all of the lines. It works almost like <C-p>

1 gotcha: when you use "p" to put the line, it puts it after the line your cursor is on, so if you want to add the line after the line you're yanking, don't move the cursor down a line before putting the new line.

I prefer to define a custom keymap Ctrl+D in .vimrc to duplicate the current line both in normal mode and insert mode:

" duplicate line in normal mode:
nnoremap <C-D> Yp
" duplicate line in insert mode:
inoremap <C-D> <Esc> Ypi

I use this mapping, which is similar to vscode. I hope it is useful!!!.

nnoremap <A-d> :t. <CR>==
inoremap <A-d> <Esc>:t. <CR>==gi
vnoremap <A-d> :t$ <CR>gv=gv
Related