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

其他回答

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

很好的问题,但没有那么多好的答案。首先,我想说,在这里使用块插入模式不是一个简单的解决方案,只是击键太多,所以显然它必须在选定的行上工作,以提高代码编辑的性能。另一个没人提到的问题是:注释符号应该放在哪里-在行首或实际文本之前?这可能是一个品味问题,但我认为,应该将它放在文本之前,以保持代码可读:当注释符号放在最开始的一行时,它会破坏缩进代码的视觉一致性,因此看起来像一个项目符号列表。考虑到这一点,我最终得到了以下解决方案(我以#comment为例)。在我的vimrc中:

vnoremap 1 :s:^\(\s*\)\([^#\t ]\):\1#\2:e<CR>
vnoremap 2 :s:^\(\s*\)#\(\s*\):\1\2:e<CR>

键1在每个选定行的文本前(空格后)插入#。它检查是否已经有#,而不是两次插入#。并且还忽略空行。键2删除一个#。它还可以确保行右侧的注释安全。


更新:这里是一个示例,说明如何生成依赖于文件类型的切换注释命令。要了解更多信息,请阅读:http://learnvimscriptthehardway.stevelosh.com/chapters/14.html

为了使其正常工作,在.vimrc文件中放入以下行。

" build the whole regex search/replace command
function! Build()
    let b:Comment_ON='''<,''>s:^\(\s*\)\([^\t ]\):\1' . b:cs . '\2:e'
    let b:Comment_OFF='''<,''>s:^\(\s*\)' . b:cs . '\(\s*\):\1\2:e'
endfunction

" run this group on Filetype event
augroup SetCS
    autocmd!
    "default comment sign
    autocmd FileType * let b:cs='--'
    "detect file type and assign comment sign
    autocmd FileType python,ruby let b:cs='#'
    autocmd FileType c,cpp,java,javascript,php let b:cs = '\/\/'
    autocmd FileType vim let b:cs='"'
    autocmd FileType * call Build()
augroup END

vnoremap 1 :<C-u>execute b:Comment_ON<CR>
vnoremap 2 :<C-u>execute b:Comment_OFF<CR>

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

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

指定要在vim中注释的行:

显示行号:

:set number

然后

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

或者:

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

所有这些方法中最快、最直观的方法是重新映射()行的逐步注释,然后()逐步取消注释。尝试一下,你就不会再回去了。

在Ruby或Bash中,使用2空间缩进:

map ) I# <Esc>j
map ( k^2x

在C/C++或PHP中,使用4空间缩进:

map ) I//  <Esc>j
map ( k^4x

缺点是你在句子移动时会丢失(和)(但das可以在其中填充),而且你偶尔会在处理长段时使用select and replace或CtrlV。但这很罕见。

对于C样式,长注释最好用以下方式处理:

set cindent
set formatoptions=tcqr

…这与使用V[move]gq重新进行单词换行结合得很好。