我在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

其他回答

要注释vim中的块:

按Esc键(退出编辑或其他模式)点击ctrl+v(视觉块模式)使用↑/↓ 箭头键选择所需的线条(它不会突出显示所有内容-这很好!)Shift+i(大写i)插入所需的文本,例如%按Esc键


要取消注释vim中的块:

按Esc键(退出编辑或其他模式)点击ctrl+v(视觉块模式)使用↑/↓ 箭头键选择要取消注释的行。如果要选择多个字符,请使用一种或组合以下方法:使用左/右箭头键选择更多文本要选择文本块,请使用shift+←/→ 箭头键您可以重复按下下面的删除键,就像常规的删除按钮按d或x删除字符,必要时重复

我是这样做的:

转到要注释掉的第一行的第一个字符。在GVIM中按Ctrl+q或在VIM中按Ctrl+v,然后向下选择要注释的行上的第一个字符。然后按c,并添加注释字符。

解压缩的方式相同,只需键入空格而不是注释字符。

此解决方案映射到注释和?取消注释(使用单个映射切换注释太复杂,无法正确实现)。它从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>"
:g/.spare[1-9].*/,+2s/^/\/\//

上面的代码将注释掉所有包含“备用”的行以及其后的一个数字,再加上它将从找到的行中注释两行。有关更多此类用途,请访问:http://vim.wikia.com/wiki/Search_and_replace#Details

下面是my.vimrc的一部分:

"insert and remove comments in visual and normal mode
vmap ,ic :s/^/#/g<CR>:let @/ = ""<CR>
map  ,ic :s/^/#/g<CR>:let @/ = ""<CR>
vmap ,rc :s/^#//g<CR>:let @/ = ""<CR>
map  ,rc :s/^#//g<CR>:let @/ = ""<CR>

在正常和视觉模式下,我可以按,ic插入注释,按,rc删除注释。