Friday, May 7, 2010

Vim Commenting

Recently there has been some renewed interest in my series of posts on using Vim for C# development, so I thought I should add a few more posts to the series to bring it up to date.

You can find the introduction to this series here.

Visual Studio has a feature which allows you to select a bunch of lines of code and have them all commented out, or uncommented.  In my setup it is bound to Ctrl+k+c to comment and Ctrl+k+u to uncomment.

I use this particular feature pretty regularly, so I definitely wanted it in Vim, and wouldn't you know it, there's a plugin for that!  NERD Commenter.

With NERD Commenter installed you can select a bunch of lines of code (I typically do something like Vjjjj) and then type either
The first is the comment command, the second is the toggle command.  If you use the comment command you'll need to use
to uncomment.  If you use the toggle command you don't need to remember two commands!

That's all there is to it!

Now, the first step is to visually select the lines you want to comment or uncomment.  You can just hit j,k a bunch of times but there are usually better ways.  For example, if you want to comment out an entire method:
public void IAmAMethod()
  ... lots of lines here...
If there are lots of lines in  the method, you don't want to be hitting j all day.  Instead, with your cursor on the method declaration line, do:
The % is the "match" motion.  So when your cursor is on the { it will find the matching }.

Alternatively, if you just want to comment out a group of text that is arranged in a paragraph:
public void IAmAMethod()
  ...paragraph of code...

  // I want to comment out this block of code
  ...more code...
  ...goes here...
For this you can use the "paragraph" motion.  With your cursor on the first line of the block, do:
That will select the whole block.

Once again, we have approximated a feature found in Visual Studio, but made it even better with the power Vim!


  1. Can't manage to run it. I select the lines in visual mode but as soon as I press c all the selected lines are deleted. Any ideas?

  2. Comma is my leader key, but the default leader key is backslash. Try \cc instead of ,cc. Or type :set leader to see what your leader key is set to.


Note: Only a member of this blog may post a comment.