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

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.


    I think you described the most popular ways to comment code, but if you are open to use Vim Scripts, give a look to those:

  • The NERD Commenter
  • EnhCommentify.vim
  • tComment

  • 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.

    链接地址: http://www.djcxy.com/p/8694.html

    上一篇: 你在Vim中使用过的最喜欢/最有成效的宏是什么?

    下一篇: 您最喜欢在Vim中评论多行的方式是什么?