What is your favorite way to comment several lines in Vim?

Viewed 15564

It happens more often than not that I have to comment several lines at once in Vim. Methods that I know are not as fast as say TextMate way to comment lines out.

What is your favorite way to do it?

I currently use:

Method 1:

  • go to first char of a line and use blockwise visual mode (ctrl-v)
  • go down/up until the first characters of every lines you want to comment out are selected
  • use shift-i and then type your comment character (# for Ruby)
  • use esc to insert the comment character to every line

Method 2:

  • select lines you need to comment out using linewise visual mode (shift-v)
  • type : which gives you a :'<,'> prompt which you can extend to :'<,'>s/^/#/

Method 3:

  • go to the first line to be commented out
  • make a bookmark for example typing mm
  • go to the last line to be commented out
  • type :'m,.s/^/#/

I like method 1 the most but I still hope there is a better way.

6 Answers

I use a keymap for the regex part, but I do the same visual selection first. Usually using:

vip

to get the visual block (paragraph visual selection)

then using

\cc
\co

for comment add/remove (cc,co chosen for muscle memory reasons)

with the mappings defined in .vimrc as:

vmap <leader>cc :s/^/#/<cr>
vmap <leader>co :s/^#//<cr>

Though this is rather old I just wanted to add my solution which is pretty similar to everyone elses but adds the unhighlighting function. In my .vimrc file I have the following maps:

:vmap `c :s/^/\/*/<cr>gv:s/$/*\//<cr>:noh<cr>i
:vmap `r :s/^\/\*//<cr>gv:s/\*\/$/<cr>:noh<cr>i

Note: I use /*line of code*/ style of commenting to be compatible with old c code. In vim I simply highlight the lines and push `c to comment and `r to remove comments.

I normally just save the step in a macro and then invoke the macro in whichever fashion I feel like.

Plugins are the way to go. They are extensible, they already support more filetypes that you would ever use, they are automagically able to toggle the commented state of a line (in other words: no need to consume two shortcuts where one is enough).

See the list given by CMS.

Related