Comment Multiple Lines in Vim

January 5, 2010 by Doug Leave a reply »

Oh Look - The Vim LogoEarlier today I was asked how to comment out multiple lines in Vim. Unfortunately I wasn’t too sure what the best way was and the only one I knew felt less than friendly. Anyway – after some research I’ve nailed a few different methods and thought I’d post them here for people to choose their favourite one.

1. Visual Insert

This is the simplest method by far. Quick fire steps are:

  1. Ctrl + V (enter block-visual selection mode)
  2. Select the first character of the lines you want to comment out using “hjkl” or cursor keys
  3. Shift + i
  4. Type your comment marker: “//”, “#”, etc.
  5. Escape
  6. The end – there is a tiny delay as the comments are now put into your other lines.

2. Visual Search/Replace

This is similar to the above but has a slightly more arcane method to adding the comments.

  1. Shift + V (enter line selection mode)
  2. Select the lines you want to comment out.
  3. Type:
:s/^/# [Return]

or

:s/^/\/\/ [Return]

The first will replace the the beginning of the line (^) with a hash (#) and the second will do the same with a double slash (//). Note the extra slashes to escape.

3 Line Number Range

Similar to above this is the only method I could think of and its hardly very friendly but it gets the job done.

Pick the line numbers of the first and last lines you want commented – this is rarely simple.

Type:

:2,10s/^/#

That will put hash comments at the start of lines 2 to 10.

4. Using Markers

I’m not fond of this method as I’m still not 100% on markers. In fact I’m around about…..0% on markers as I’d not heard of them until now!! Woo for learning!

Anyway – markers. Oh yes, I’ll do a nice list of steps again:

  1. On the first line while in command mode type “ma” (no colon required here)
  2. Go to the last line of your intended block.
  3. Type:
:'a,. s/^/# /

In English that means: Form marker “a” to here (.) perform this command: s/^/# /

5. Plugins

You could just skip all that and install a Vim plugin. The advantage being they have more features. The disadvantage being you’d have to make sure all the servers you use have this plugin otherwise you’re stumped.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Google Bookmarks
  • BlinkList
  • DZone
  • Live
  • Ma.gnolia
  • Reddit
  • Slashdot
  • SphereIt
  • StumbleUpon

Related

Advertisement

Leave a Reply