Thursday, June 12, 2008

Comment Out Line Range

This is one of my favorite ex hacks. It's pretty old school and should work all the way back to the original Vi. This assumes your comment character is # (octothorpe), but would work just as well with // comments or any other line-wise comment character. Go to column zero of the first line you want to start your comment block on. Hit ma to set a mark. Now scroll down to column zero of the last line you want to comment out. Issue the following ex command:

:'a, . s/^/# /

That's it. It runs a substitute on the range from the mark stored in register 'a to the current line. Take note that you can specify ranges for any ex command using the same technique.


Leslie P. Polzer said...

I use the following idiom to achieve this:

* Move to the beginning of the first line
* CTRL-V to enter visual char mode
* Move down to last line
* Press I for insert mode
* type // or # or whatever
* Press ESC

Anonymous said...

There are also plugins like EnhancedCommentify or NERD_Commenter, which take care of such things in flexible ways. They also recognise automatically, which comment to use based on the filetype.

Lucas Oman said...

Seems easier to do this in visual line mode. Select the code block, then a simple :s/^/#/ does it.

Nacho said...

IMHO Luca's way rocks.