In Vim, how do I insert characters at the beginning of each line in a selection?
For instance, I want to comment out a block of code by prepending //
at the beginning of each line assuming my language's comment system doesn't allow block commenting like /* */
. How would I do this?
vim Inserting text Insert text into multiple lines at once Press Ctrl + v to enter into visual block mode. Use ↑ / ↓ / j / k to select multiple lines. Press Shift + i and start typing what you want. After you press Esc , the text will be inserted into all the lines you selected.
Press ^ to move the cursor to the start of the current line. Press $ to move the cursor to the end of the current line.
Use sed 's insert ( i ) option which will insert the text in the preceding line.
In a visual block, you can insert text in each line before the selection with I , and you can append text in each line after the selection with A . If you use $ to convert the visual selection to select to the end of line, then A will append text to the end of each line in the visual block.
For further information and reading, check out "Inserting text in multiple lines" in the Vim Tips Wiki.
This replaces the beginning of each line with "//":
:%s!^!//!
This replaces the beginning of each selected line (use visual mode to select) with "//":
:'<,'>s!^!//!
Note that gv
(in normal mode) restores the last visual selection, this comes in handy from time to time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With