Commenting out multiple lines in Vim

Somtimes you want to comment out multiple lines in Vim. There’s an easy way to do this out of the box without any rc magic or plugin.

  1. Navigate with the cursor to either the first or last line you want to comment out.
  2. Pess Control and v to select a new visual block.
  3. Move your cursor down (or up respectively) to the last (or first) line you want to comment out. You just formed a visual block of your comment.
  4. Press I to insert text before all selected lines.
  5. Type your comment code (for example // or # or ;).
  6. Press Escape. Your comment code will be inserted before every line of the visual block.

To uncomment, do exactly the same, but instead of executing step 5 apply a regular expression. The regular expression should look something like this: :s/^#/. This will replace every # at the beginning of the line with nothing. If your comment code has only one character, you can also press d to delete the first character of every line.

Easy. Now tell me how to do this in Emacs. Christine graciously commented on how to do this in Emacs. Looks similar, except that Emacs seems to be a bit smarter about what comment code to use.

Tags: , , , ,

Shameless plug: If this post was useful to you, please consider buying yourself something from one of my Amazon stores: US store, UK store, FR store, DE store, CA store. If you're not into Amazon, why not donate something to GNOME, Mozilla or Wikipedia? Thank you!

2 Responses to “Commenting out multiple lines in Vim”

  1. Christine says:

    How to do this in Emacs:
    1. Navigate with the cursor to the beginning of either the first or last line you want to comment out.
    2. Press Control and Space to set a mark
    3. Move your cursor down (or up respectively) to the end of the last (or first) line you want to comment out.
    4. Press M-; That’s it. Most of the time at least. Otherwise Emacs will ask you for the right characters to insert by saying ‘No comment syntax is defined. Use: ‘

    To uncomment, do exactly the same.

    You can also use regular expressions for the same purpose. Instead of pressing M-; you can press C-M-% and
    a. if you want to comment: type ^. Press Return and type #, // or whatever you need, press Return and then ! to replace all occurences.
    or
    b. if you want to uncomment: type ^#, ^// or whatever you inserted before, press Return twice and then !.

  2. Patrick says:

    Great. Thanks!

Leave a Reply