我在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的内置注释字符串选项中获取注释字符串,如果声明了filetype plugin on,则从/usr/share/VIM/VIM*/ftplugin/*.VIM等文件填充注释字符串。

filetype plugin on
autocmd FileType * let b:comment = split(&commentstring, '%s', 1)
autocmd FileType * execute "map <silent> <Leader>/ :normal 0i" . b:comment[0] . "<C-O>$" . b:comment[1] . "<C-O>0<CR>"
autocmd FileType * execute "map <silent> <Leader>? :normal $" . repeat('x', strlen(b:comment[1])) . "0" . strlen(b:comment[0]) . "x<CR>"

其他回答

通过mark命令标记文本区域,例如ma和mbtype命令::'a,'bg/(.*)/s////\1/

您可以在http://bknpk.ddns.net/my_web/VIM/vim_shell_cmd_on_block.html

我使用Tim Pope的vim评论插件。

按ctrl+v,然后使用↑ 或↓ 选择要注释的行数。然后按shift+I,按#,然后按ESC。这将注释掉您选择的行数。

与取消注释行相反。

注释行的一种方法是使用视觉块选择

将光标放在需要注释的行的第0个位置,然后按ctrl+v键进入视觉块。现在使用j(向下)或k(向上)导航到需要注释的行。然后使用c进行切割和插入测试。现在键入“#”以注释,然后键入esc以反映您在选定行上的插入

使用命令模式

选择带有V的行,然后使用j(downwards)k(向上)选择所有需要注释的行,并点击:进入命令模式,看起来像“:<,>”,然后在所选行的开头插入“#”

:'<,'>s/^/#

我标记第一行和最后一行(ma和mb),然后做:‘a,‘bs/^#//