我在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(-#)。


当前回答

切换注释

如果你只需要切换评论,我宁愿使用commenttary.vim by tpope。

安装

病菌:

cd ~/.vim/bundle
git clone git://github.com/tpope/vim-commentary.git

vim插头:

Plug 'tpope/vim-commentary'

Vundle公司:

Plugin 'tpope/vim-commentary'

进一步定制

将其添加到.virc文件:noremap<leader>/:Comments<cr>

现在,您可以通过按Leader+/来切换评论,就像Sublime和Atom一样。

其他回答

我使用Jasmeet Singh Anand的comments.vim(在vim.org上找到),

它适用于C、C++、Java、PHP[2345]、proc、CSS、HTML、htm、XML、XHTML、vim、vimrc、SQL、sh、ksh、csh、Perl、tex、fortran、ml、caml、ocaml、vhdl、haskel和普通文件

它在正常和可视模式下对不同源文件中的行进行注释和取消注释

用法:

CtrlC注释单行CtrlX取消注释单行ShiftV并选择多行,然后CtrlC对所选多行进行注释ShiftV并选择多行,然后CtrlX取消注释所选多行

如果您已经知道行号,那么n,ms/#//将起作用。

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

此解决方案映射到注释和?取消注释(使用单个映射切换注释太复杂,无法正确实现)。它从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命令不适用于我在Windows上的设置。Ctrl+v和Ctrl+q是其中的一些。后来我发现以下方法可以取消注释行。

鉴于

一些缩进的注释

   # Practice in Vim
   # Practice in Vim
   # Practice in Vim
   # Practice in Vim
   # Practice in Vim
   # Practice in Vim
   # Practice in Vim

以下方法删除#符号并保留缩进。

方法

将光标移动到第一条注释(箭头或h、j、k、l)。然后应用以下技术之一:

视觉块模式(更快)

Ctrl+Shift+v进入视觉块模式js来选择垂直线。l包括水平字符(可选)x删除块

搜索/替换+Regex

选择具有常规视觉模式的文本,即Shift+v类型:。您将得到提示“<,”>。键入regex,例如s/#//将哈希值替换为空。(可选:键入s/#//以包含空格)。进来

:norm命令

选择具有常规视觉模式的文本,即Shift+v类型:。您将得到提示“<,”>。发出命令。键入:norm ^x以删除第一个非空白字符和下一个字符。(可选:如果不缩进,请尝试:norm x,或:norm ^xx以包含空格)。进来

g模式

选择具有常规视觉模式的文本,即Shift+v类型:。您将得到提示“<,”>。发出命令。键入g/#/nom^x。(可选:键入g/#/nom!^xx以包含空格)。进来

后果

    Practice in Vim
    Practice in Vim
    Practice in Vim
    Practice in Vim
    Practice in Vim
    Practice in Vim
    Practice in Vim

另请参见

关于删除缩进的评论的帖子关于如何快速评论Vim的帖子Primagen的g命令教程。VimTrick的注释代码教程