Amazing Vim tip of the {time_interval}: Commenting blocks of text

If you have multiple lines of code that you want to comment out, here is an easy and fast way to do it in Vim:

From command mode, with the cursor placed on the first line of the block that you want to comment, type Ctrl-v to enter visual-block mode.

Move the cursor down to the last row of the block.

Enter insert mode: Shift-I (note it has to be capital I, not lowercase as one would normally enter insert mode from command mode).

Type the comment character (for example #) then press escape to exit insert mode. Automatically the entire block of lines will be commented.

Note that I tried to use this same procedure to uncomment a block and unfortunately it doesn’t work…

UPDATE: Here is another way to comment and uncomment blocks using Shift-v (visual-line mode) instead of Ctrl-v:

http://stackoverflow.com/questions/2561418: #26 You could add the following mapping to your .vimrc

UPDATE2: This is even cooler:
http://stackoverflow.com/questions/2561418: #1 Ctrl + k for comment (Visual Mode)

One you add the two lines to your .vimrc and you are editing a file, in command mode you just press “v” to go into visual mode, then move the cursor down to select a block, then press either Ctrl-k to comment the block or press Ctrl-u to uncomment the block. Very simple!

I think regular visual mode in this last example is easier than visual-block mode in the first one or than visual-line mode in the second one.

Credits & thanks:

devrefresh.wordpress.com: Vim: Comment a Block of Code