In Vim, how would I go about inserting characters at the beginning of each line in a selection?
For instance, let's say 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?
Yet another way:
/^/
is just a dummy pattern to match every line.norm
lets you run the normal-mode commands that follow.I//
says to enter insert-mode while jumping the cursor to the beginning of the line, then insert the following text (two slashes).:g
is often handy for doing something complex on multiple lines, where you may want to jump between multiple modes, delete or add lines, move the cursor around, run a bunch of macros, etc. And you can tell it to operate only on lines that match a pattern.This adds
#
at the beginning of every line:And people will stop complaining about your lack of properly commenting scripts.
Another way that might be easier for newcomers:
Place the cursor on the first line, e.g. by
: 1 Enter
and type the following to get into insert mode and add your text:
I / / Space
Press Esc to get back to command mode and use the digraph:
j . j .
j is a motion command to go down one line and . repeats the last editing command you made.
I can recommend the EnhCommentify plugin.
eg. put this to your vimrc:
you can then comment/uncomment the (selected) lines with ',c'
For further information and reading, check out this related article on the vim wiki.
Mark the area to be comment as a visual block (
<C-V
)and do
c#<ESC>p
c
hange it to "#"If you do it often, define a short cut (example
\q
) in your .vimrc