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
,ccor
,c<space>The first is the comment command, the second is the toggle command. If you use the comment command you'll need to use
,cuto 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:
Vj%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:
V}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!
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?
ReplyDeleteComma 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.
ReplyDelete