Vim: How to Comment Multiple Lines

illustration of people working on a computer

There are multiple different ways you can write a multiline comment in the vim/vi editor. Here are some of the most commonly used ones.

Method 1: Comment multiple lines with visual block mode

Here's how you can comment on multiple lines in visual block mode:

  1. Navigate to the beginning of the first line of the group of lines you want to comment out.
  2. Here, press Ctrl or Cmd + V. Your editor will go into VISUAL BLOCK mode.
  3. Then, using the arrow keys move forward and select until the last character of the last line that you want to comment out.
  4. Once here, press Shift + I - this will take your editor into Insert mode
  5. In insert mode, press the # key. This will add a hash to the first line.
  6. After this, press the Esc key. The # symbol will be inserted on all the other lines you have selected and the block will be commented out.

Method 2: Making multiline comments using ranges

If you're looking for a single command to comment out a bunch of lines, you can use the following command in command mode for commenting:

:55,80s/^/#

And for uncommenting:

:55,80/^#/

This command would comment out the lines from 55 to 80 (inclusive).


And that's all folks, those are two easy ways you can make a multiline comment in the vi/vim editor!