Vim: comment blocks

I have become tired of using the arrow keys to navigate around my source code just to insert comments on each line of a block of code.  Wouldn’t it be nice if I could just select a few lines, hit a button or two, and have all of the lines commented out or un-commented?  (Like in Max-PlusII or QuartusII support in their VHDL editors…)

Well Vim has the ability to do so!  First of all, let me introduce the visual-block command.  In Vim, pressing v allows you to select text. Visual-block is enabled by pressing Cntl-v.  Notice the difference in the following two screen shots.

Regular Visual Mode in Vim
Visual-block mode in Vim

In visual mode, if you move downward, the entire line is selected, but in visual-block mode, only the text in the same column is selected.  In visual-block mode, if you move to the right, more columns are selected.

To insert comments, select the text rows that you want to block comment-out with visual-block, Cntl-v. Now press I, and then the commenting characters that you want to insert.  For C++ you would want //, for Ada or VHDL , or for scripting languages a # would do the trick. Finally, press the Esc key to end the visual-block command.  The block of code should now be commented out!

To remove comments from a block of test, usual the visual-block command (Cntl-v) and select the columns of comment text, and then press d, and that should take care of it.

Removing comments is easy enough, but wouldn’t it be nice to have an easier way to add comment blocks without all of those keys to press?  Well, why don’t we map the keystrokes to a single key?  Edit your .vimrc and add the following as needed:

map <F2> I–<Esc><Esc>
map <F3> I//<Esc><Esc>
map <F4> I#<Esc><Esc>

Now I can simply select the text block with visual-block, and press a function key to insert comments for Ada, C++ or shell scripts.  I’m just beginning to see the real power of Vim.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s