How To Comment Out And UnComment Multiple Lines At Once In Vim Editor


How to comment out in VIM

If you use vim to code then you would be commenting and un-commenting many times.In this post, we would talk about multiple ways of commenting code.

Method 1.

Use the line numbers to comment the specific lines. For example, say we want to comment out lines from 2 to 4. Here is how you do it...

:2,4s/^/#



As we see in the above snapshot, lines 2 to 4 have comment sign '#' in front of each line.

Method 2.

Use the visual mode to select the lines which you want to comment.

  1. Go to the line which you want to start the comment from
  2. Press shift+V - this will select the whole line
  3. Now press j if you want to select lines down below from the current line other wise press k if you want to select current line + lines above
  4. Now press colon key ":" and type s/^/#/

Please checkout the snapshot below for details.




Method 3:

Use regex to find the lines, which you want to comment out. This technique is very powerful and also work if the lines to be commented are not continuous but caveat is that there should be common pattern.

Lets say we want to comment the lines 3 and 5 in our example above. There is common pattern in line 3 and 5 that is the common word character. Lets see how we can use that to comment out these two lines. The command is

:g/character/ s/^/#/



Well let me explain what is happening here. g/character/ is finding the pattern "character". Once we have the found all the lines, we are passing to vim substitution command s/^/#/ to insert # at the beginning of each line.


How to Uncomment in Vim

Uncommenting can also be done in multiple ways. Usually it is opposite of what we did when we commented out lines.

Method 1.

Lets say we want to uncomment lines starting with character '#'

:%s/^#/ 



Method 2.

Another way is visual way by selecting all the lines which we want to uncomment.

  1. Go to the line which you want to uncomment
  2. Press shift+V - this will select the whole line
  3. Now press j if you want to select lines down below from the current line other wise press k if you want to select current line + lines above
  4. Now press colon key ":" and type s/^#/



Method 3.

There is another visual way. Select only the character "#" visual and press delete key d. Here is how you do it.

  1. Go to the line which you want to uncomment. Put your cursor over the character '#'
  2. Press ctrl+v - this will select only the character '#'
  3. Press j if you want to uncomment the adjacent lines
  4. Press d to remove the character '#' from the front of the lines.

Checkout the snapshot below.



That's it for now. Hope you got the gist of how to comment and uncomment code in VIM.