Tags Vim

After some looking-around I've found two interesting techniques to comment (or comment out) a block of code:

Substitution on a range of lines

Given a range of lines, a simple substitution command may add or remove comments. For example, for Python code s/^/#/ and s/^#// will add or remove a comment from the beginning of the line, respectively.

To make a range of lines for this operation you can use any Vim technique, like for example explicitly specifying the range:

:M,N s/^/#/

Will comment out lines in the inclusive range [M:N].

A simpler way is to use the visual selection mode, by pressing V (capital v for line selection), selecting the needed lines and then executing the substitution command.

Using block-mode visual selection

  1. Move to the first column in the first line you want to comment-out.
  2. Press Ctrl-V to start block-mode selection.
  3. Move down to select the first column of a block of lines.
  4. Press I and then the desired comment starter (i.e. #)
  5. Press ESC and the insertion will be applied to the whole block.

To uncomment with this techniques follow the directions but instead of I use x to delete the first char.


If you have other techniques to suggest, please let me know. Also if you're familiar with a good plugin that makes this really easy and also knows which types of source code require which comment chars, I'd like to hear about it.