Vim is one of the most powerful text editors, loved by developers, sysadmins, and Linux enthusiasts. But when you’re new, even simple tasks like duplicating a line can feel confusing.
The good news: there are several quick ways to copy and paste lines in Vim. This article will walk you through basic, advanced, and time-saving methods to duplicate lines efficiently.
Method 1: Yank and Paste (Most Common)
The simplest way is to yank (copy) the line and paste it.
- Press
Escto enter Normal mode - Move your cursor to the line you want to duplicate
- Type:
yyThis yanks (copies) the whole line. - Then press:
pThis pastes the line below the current one.
If you want to paste above, use P instead of p.
Method 2: Use the :t. Command
Another neat trick is using Vim’s built-in :t command.
- Place your cursor on the line to duplicate
- Type:
:t.and press Enter.
This copies the current line (t) and places it below the same line (.).
Example: If your cursor is on line 5, :t. will duplicate line 5 directly below it.
You can also use numbers:
:t6→ copies current line and pastes it after line 6:.,.+2t.→ duplicates the current line and the next 2 lines
Method 3: Visual Mode (Great for Multiple Lines)
If you want to duplicate more than one line:
- Press
Escto go to Normal mode - Press
V(capital V) to start Visual Line mode - Move up or down to select multiple lines
- Press
yto yank (copy) - Press
pto paste below
This is great for duplicating code blocks.
Method 4: Create a Custom Mapping
If duplicating lines is something you do often, you can save time with a custom mapping in your .vimrc:
nnoremap <Leader>d yyP
Now pressing <Leader>d (usually \d) will duplicate the current line above it instantly.
You can customize it to paste below instead by changing it to yyP.
Advanced Tips
- Use registers:
"ayystores the line in registera, then"appastes it. This way you won’t overwrite your default yank register. - Repeat counts:
2yyyanks two lines, thenppastes both. - Undo mistakes: press
uif you accidentally duplicated too much. - Indentation issues: check your
autoindentorsmartindentsettings if pasted lines shift incorrectly.
FAQ: Duplicating Lines in Vim
Q: Can I duplicate without moving the cursor?
Yes. Using :t. keeps your cursor on the same line after duplication.
Q: Does this work in Neovim too?
Yes. Neovim inherits the same commands from Vim.
Q: Can I duplicate a line multiple times quickly?
Yes. For example, type yy and then 3p to paste the line three times below.
Conclusion
Duplicating lines in Vim is simple once you know the commands. You can use:
yy+p→ fast and easy:t.→ great for precision- Visual Mode → perfect for multiple lines
- Mappings → automate and speed up your workflow
Mastering these techniques will save you time and make editing in Vim much more efficient.
