我在vi中打开了一个Ruby代码文件,其中有行注释为#:

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

假设我想取消注释第一个定义中的所有行。。。端部。在Vim中有什么有效的方法可以做到这一点?

总的来说,我正在寻找一种简单、流畅的方式来注释和取消注释行。这里我处理的是Ruby代码,但可能是JavaScript(//)或Haml(-#)。


当前回答

指定要在vim中注释的行:

显示行号:

:set number

然后

:5,17s/^/#/     this will comment out line 5-17

或者:

:%s/^/#/        will comment out all lines in file

其他回答

使用Control-V选择文本矩形:转到第一个#字符,键入Ctrl+V,向右移动一次,然后向下移动,直到注释结束。现在键入x:删除所有#字符,后跟一个空格。

我喜欢使用tcomment插件:http://www.vim.org/scripts/script.php?script_id=1173

我已经将gc和gcc映射为注释一行或高亮显示的代码块。它可以检测文件类型,工作非常好。

要取消注释整个文件,请执行以下操作:

Esc退出插入模式转到第一行的第一个字符ctrl+V或ctrl+shift+V选择当前字符G或shift+G转到最后一行x删除所选内容

:%s/^/\/\//g

删除角色和使用此命令注释.C或CPP文件

你可以使用tpope的vim评论(https://github.com/tpope/vim-commentary)您可以按如下方式使用它:

按进入视觉模式

'v'

然后按

'j' repeatedly or e.g 4j to select 4 row

现在,您所要做的选择就是输入键:

'gc'

这将注释掉所有选择,以取消注释repead键:

'gc'