How to comment multiple lines at once?

Visual Block Mode

First, move the cursor to the first char of the first line in block code you want to comment, 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.


Ranges:

You can do it with the following commands:

for commenting:

:66,70s/^/#

for uncommenting:

:66,70s/^#/

Obviously, here we're commenting lines from 66 to 70 (inclusive).


Substitute

For the sake of completeness here's another way:

  1. Enter visual mode by pressing v
  2. select the lines you like to comment (up/down arrow or j/k)
  3. enter :s/^/# / which translates to: in selection (:) replace beginning of line (^) with `# '