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

其他回答

指定要在vim中注释的行:

显示行号:

:set number

然后

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

或者:

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

下面是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删除注释。

是的,这个问题已经有33个(大部分是重复的)答案。

下面是另一种在Vim中注释行的方法:运动。基本思想是使用与键入yip删除段落或键入dj删除2行相同的方法注释或取消注释行。

这种方法可以让您执行以下操作:

ccj注释接下来的2行,cuk取消注释;cci{注释一个块,cui{取消注释;ccip注释整个段落,cuip取消注释。ccG将所有内容注释到最后一行,cugg将所有内容取消注释到第一行。

您只需要2个对运动进行操作的函数,以及每个函数的2个映射。首先,映射:

nnoremap <silent> cc  :set opfunc=CommentOut<cr>g@
vnoremap <silent> cc  :<c-u>call  CommentOut(visualmode(), 1)<cr>
nnoremap <silent> cu  :set opfunc=Uncomment<cr>g@
vnoremap <silent> cu  :<c-u>call  Uncomment(visualmode(), 1)<cr>

(请参阅有关g@运算符和operatorfunc变量的手册。)

现在功能如下:

function! CommentOut(type, ...)
  if a:0
    silent exe "normal!  :'<,'>s/^/#/\<cr>`<"
  else
    silent exe "normal!  :'[,']s/^/#/\<cr>'["
  endif
endfunction

function! Uncomment(type, ...)
  if a:0
    silent exe "normal!  :'<,'>s/^\\(\\s*\\)#/\\1/\<cr>`<"
  else
    silent exe "normal!  :'[,']s/^\\(\\s*\\)#/\\1/\<cr>`["
  endif
endfunction

修改上面的正则表达式以适合您的口味,即#应该在哪里:

我个人想评论一下Visual Studio。我在工作中已经习惯了它,以至于它占据了我的肌肉记忆(使用vsvim)。使用shift+v选择所需的行,然后按ctrl+k,ctrl+c进行注释,或按ctrl+k,ctrl+u取消注释。

:vnoremap <C-k><C-c> :norm i//<Cr>
:vnoremap <C-k><C-u> :s/\/\///g<Cr>:noh<Cr>

这个简单的片段来自my.vimrc:

function! CommentToggle()
    execute ':silent! s/\([^ ]\)/\/\/ \1/'
    execute ':silent! s/^\( *\)\/\/ \/\/ /\1/'
endfunction

map <F7> :call CommentToggle()<CR>

它适用于//-注释,但您可以很容易地将其改编为其他角色。您可以按照jqno的建议使用autocmd设置引线。

这是一种非常简单和有效的方式,自然地处理范围和视觉模式。