Tell me the best way to choose a text and comment it?

Currently I go to the first line, go to insert mode then type # left-arrow down-arrow and then I repeat that sequence, perhaps saving a few keystrokes by using the . repeat feature to do each line.

Is there anyway I could (for instance) select either multiple lines in visual mode or by using a range of lines and an ex ('colon') command and for that range comment out all the lines with a # to make them a "block comment".

The ability to quickly 'de-comment' (remove the # 's) for a block comment would also be nice.

Best Answer

Visual Block Mode

Move the cursor to the first char of the first line of block code you want to comment and then type

Ctrl + v

then vim will go into VISUAL BLOCK mode. Use j to move the cursor down until you reach the last line of your code block. Then type.

Shift + i

now vim goes to INSERT mode and the cursor is at the first char of the first line. Finally, type # then ESC and the code block is now commented.

To decomment, do the same things but instead of type Shift + I , you just type x to remove all # after highlight them in VISUAL BLOCK mode.