What's a quick way to comment/uncomment lines in Vim?

I have a Ruby code file open in vi, there are lines commented out with # :

class Search < ActiveRecord::Migration
  def self.up
    # create_table :searches do |t|
    #   t.integer :user_id
    #   t.string :name
    #   t.string :all_of
    #   t.string :any_of
    #   t.string :none_of
    #   t.string :exact_phrase
    # 
    #   t.timestamps
    # end
  end

  def self.down
    # drop_table :searches
  end
end

Say I want to uncomment all the lines in the first def ... end section. What's an efficient way to do that in Vim?

In general, I'm looking for an easy and fluid way to comment and uncomment lines. Here I'm dealing with Ruby code, but it could be JavaScript ( // ) or Haml ( -# ).


I use the NERD Commenter script. It lets you easily comment, uncomment or toggle comments in your code.


For those tasks I use most of the time block selection.

Put your cursor on the first # character, press CtrlV (or CtrlQ for gVim), and go down until the last commented line and press x, that will delete all the # characters vertically.

For commenting a block of text is almost the same:

  • First, go to the first line you want to comment, press CtrlV. This will put the editor in the VISUAL BLOCK mode.
  • Then using the arrow key and select until the last line
  • Now press ShiftI, which will put the editor in INSERT mode and then press #. This will add a hash to the first line.
  • Then press Esc (give it a second), and it will insert a # character on all other selected lines.
  • For the stripped-down version of vim shipped with debian/ubuntu by default, type : s/^/# in the third step instead.


    To comment out blocks in vim:

  • press Esc (to leave editing or other mode)
  • hit ctrl+v (visual block mode)
  • use the up/down arrow keys to select lines you want (it won't highlight everything - it's OK!)
  • Shift+i (capital I)
  • insert the text you want, ie %
  • press EscEsc

  • To uncomment blocks in vim:

  • press Esc (to leave editing or other mode)
  • hit ctrl+v (visual block mode)
  • use the ↑/↓ arrow keys to select the lines to uncomment.

    If you want to select multiple characters, use one or combine these methods:

  • use the left/right arrow keys to select more text
  • to select chunks of text use shift + ←/→ arrow key
  • you can repeatedly push the delete keys below, like a regular delete button

  • press d or x to delete characters, repeatedly if necessary
  • 链接地址: http://www.djcxy.com/p/3864.html

    上一篇: 我如何让Git使用我选择的编辑器进行提交?

    下一篇: 在Vim中评论/取消注释的快捷方式是什么?