在Vim中,什么是快速评论/取消评论的方式?

时间:2022-11-04 23:17:26

I have a Ruby code file open in vi, there are lines commented out with #:

我有一个Ruby代码文件在vi中打开,有一些行注释掉了#:

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

Say I want to uncomment all the lines in the first def ... end section. What's an efficient way to do that in Vim?

比如说,我想取消第一个def中的所有行。结束部分。在Vim中有效的方法是什么?

In general, I'm looking for an easy and fluid way to comment and uncomment lines. Here I'm dealing with Ruby code, but it could be JavaScript (//) or Haml (-#).

总的来说,我正在寻找一种简单而流畅的方法来评论和取消评论。这里我要处理的是Ruby代码,但它可能是JavaScript(//)或Haml(-#)。

45 个解决方案

#1


154  

I use the NERD Commenter script. It lets you easily comment, uncomment or toggle comments in your code.

我用的是书呆子的评论脚本。它允许您轻松地评论、取消注释或在您的代码中切换注释。

#2


1637  

For those tasks I use most of the time block selection.

对于那些任务,我使用了大部分的时间块选择。

Put your cursor on the first # character, press CtrlV (or CtrlQ for gVim), and go down until the last commented line and press x, that will delete all the # characters vertically.

将光标放在第一个#字符上,按下ctrl(或ctrl + gVim),直到最后一个注释行和按x,这样就可以垂直删除所有的字符。

For commenting a block of text is almost the same:

对于评论一个文本块几乎是一样的:

  1. First, go to the first line you want to comment, press CtrlV. This will put the editor in the VISUAL BLOCK mode.
  2. 首先,转到您想要评论的第一行,按下ctrl键。这将使编辑器处于可视块模式。
  3. Then using the arrow key and select until the last line
  4. 然后使用箭头键并选择到最后一行。
  5. Now press ShiftI, which will put the editor in INSERT mode and then press #. This will add a hash to the first line.
  6. 现在按ShiftI,将编辑器插入插入模式,然后按#。这将向第一行添加一个散列。
  7. Then press Esc (give it a second), and it will insert a # character on all other selected lines.
  8. 然后按Esc(给它一秒钟),它将在所有其他选定的行中插入一个#字符。

For the stripped-down version of vim shipped with debian/ubuntu by default, type : s/^/# in the third step instead.

精简版的vim附带debian / ubuntu默认情况下,类型:s / ^ / #第三步。

#3


618  

To comment out blocks in vim:

  • press Esc (to leave editing or other mode)
  • 按Esc(离开编辑或其他模式)
  • hit ctrl+v (visual block mode)
  • 按ctrl+v(可视块模式)
  • use the up/down arrow keys to select lines you want (it won't highlight everything - it's OK!)
  • 使用向上/向下的箭头键来选择你想要的线(它不会突出任何东西——它是可以的!)
  • Shift+i (capital I)
  • Shift +我(资本)
  • insert the text you want, i.e. %
  • 插入你想要的文本,即%。
  • press EscEsc
  • 新闻EscEsc

To uncomment blocks in vim:

  • press Esc (to leave editing or other mode)
  • 按Esc(离开编辑或其他模式)
  • hit ctrl+v (visual block mode)
  • 按ctrl+v(可视块模式)
  • use the / arrow keys to select the lines to uncomment.

    If you want to select multiple characters, use one or combine these methods:

    如果您想选择多个字符,请使用一个或组合这些方法:

    • use the left/right arrow keys to select more text
    • 使用左/右箭头键选择更多文本。
    • to select chunks of text use shift + / arrow key
    • 选择的文本块使用shift +←/→箭头键
    • you can repeatedly push the delete keys below, like a regular delete button

    • 你可以重复地按下删除键,就像一个普通的删除按钮。
  • press d or x to delete characters, repeatedly if necessary
  • 按d或x删除字符,必要时重复。

#4


202  

Sometimes I'm shelled into a remote box where my plugins and .vimrc cannot help me, or sometimes NerdCommenter gets it wrong (eg JavaScript embedded inside html).

有时我被放在一个远程的盒子里,我的插件和.vimrc无法帮助我,或者有时候NerdCommenter会出错(比如JavaScript嵌入到html中)。

In these cases a low-tech alternative is the built-in norm command, which just runs any arbitrary vim commands at each line in your specified range. For example:

在这些情况下,低技术的替代方法是内置的norm命令,它只在指定范围内的每一行运行任意的vim命令。例如:

Commenting with #:

注释以#:

1. visually select the text rows (using V as usual)
2. :norm i#

This inserts "#" at the start of each line. Note that when you type : the range will be filled in, so it will really look like :'<,'>norm i#

这将在每一行的开头插入“#”。请注意,当您键入时,范围将被填充,因此它将看起来是:'<,>规范i#。

Uncommenting #:

现在#:

1. visually select the text as before (or type gv to re-select the previous selection)
2. :norm x

This deletes the first character of each line. If I had used a 2-char comment such as // then I'd simply do :norm xx to delete both chars.

这将删除每一行的第一个字符。如果我使用了一个2字符的注释,比如//那么我就只做:norm xx来删除两个字符。

If the comments are indented as in the OP's question, then you can anchor your deletion like this:

如果在OP的问题中,注释是缩进的,那么您可以像这样锚定您的删除:

:norm ^x

which means "go to the first non-space character, then delete one character".

意思是“去到第一个非空格字符,然后删除一个字符”。

Note: Since norm is literally just executing regular vim commands, you're not limited just to comments, you could do some complex editing to each line. If you need the escape character as part of your command sequence, type ctrl-v then hit the escape key.

注意:由于norm实际上只是执行常规的vim命令,所以您不仅限于注释,还可以对每一行进行一些复杂的编辑。如果您需要将转义字符作为命令序列的一部分,那么键入ctrl-v然后按escape键。

Note 2: You could of course also add a mapping if you find yourself using norm a lot. Eg putting the following line in ~/.vimrc lets you type ctrl-n instead of :norm after making your visual selection

注2:如果你发现自己经常使用规范,你当然也可以添加一个映射。vimrc允许您在进行可视化选择后键入ctrl-n而不是:norm。

vnoremap <C-n> :norm

Note 3: Bare-bones vim sometimes doesn't have the norm command compiled into it, so be sure to use the beefed up version, ie typically /usr/bin/vim, not /bin/vi

注释3:Bare-bones vim有时没有编译到它的norm命令,所以一定要使用健壮的版本(通常是/usr/bin/vim,而不是/bin/vi)。

(Thanks to @Manbroski and @rakslice for improvements incorporated into this answer)

(感谢@Manbroski和@rakslice将改进纳入了这个答案)

#5


99  

I have the following in my .vimrc:

以下是我的。vimrc:

" Commenting blocks of code.
autocmd FileType c,cpp,java,scala let b:comment_leader = '// '
autocmd FileType sh,ruby,python   let b:comment_leader = '# '
autocmd FileType conf,fstab       let b:comment_leader = '# '
autocmd FileType tex              let b:comment_leader = '% '
autocmd FileType mail             let b:comment_leader = '> '
autocmd FileType vim              let b:comment_leader = '" '
noremap <silent> ,cc :<C-B>silent <C-E>s/^/<C-R>=escape(b:comment_leader,'\/')<CR>/<CR>:nohlsearch<CR>
noremap <silent> ,cu :<C-B>silent <C-E>s/^\V<C-R>=escape(b:comment_leader,'\/')<CR>//e<CR>:nohlsearch<CR>

Now you can type ,cc to comment a line and ,cu to uncomment a line (works both in normal and visual mode).

现在你可以键入,cc来注释一行,cu可以取消注释一行(在正常和可视模式下都可以)。

(I stole it from some website many years ago so I can't completely explain how it works anymore :). There is a comment where it is explained.)

(很多年前我从某个网站上偷了它,所以我无法完全解释它的工作原理:)。这里有一个注释。

#6


76  

Specify which lines to comment in vim:

在vim中指定要评论的行:

Reveal the line numbers:

显示行号:

:set number

then

然后

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

or this:

或:

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

#7


45  

Here is how I do it:

下面是我的做法:

  1. Go to first character on the first line you want to comment out.

    第一行的第一个字符要注释掉。

  2. Hit Ctrl+q in GVIM or Ctrl+v in VIM, then go down to select first character on the lines to comment out.

    在VIM中按下Ctrl+q键或Ctrl+v,然后向下选择要注释的行中的第一个字符。

  3. Then press c, and add the comment character.

    然后按c,添加注释字符。

Uncommenting works the same way, just type a space instead of the comment character.

没有注释的工作方式相同,只是键入一个空格而不是注释字符。

#8


26  

I've come up with a simple addition to my .vimrc file which works pretty well and can be extended easily. You simply add a new filetype to the comment_map and its comment leader.

我提出了一个简单的添加到.vimrc文件中,它工作得很好,可以很容易地扩展。您只需向comment_map和它的comment leader添加一个新的filetype。

I added a mapping to normal and visual modes, but you can remap to anything you like. I prefer only to have a 'toggle' style function. One bears having multiple mappings etc.

我添加了一个映射到正常的和可视的模式,但是你可以重新映射到你喜欢的任何东西。我喜欢只有“切换”样式的功能。一个熊有多个映射等等。

let s:comment_map = { 
    \   "c": '\/\/',
    \   "cpp": '\/\/',
    \   "go": '\/\/',
    \   "java": '\/\/',
    \   "javascript": '\/\/',
    \   "lua": '--',
    \   "scala": '\/\/',
    \   "php": '\/\/',
    \   "python": '#',
    \   "ruby": '#',
    \   "rust": '\/\/',
    \   "sh": '#',
    \   "desktop": '#',
    \   "fstab": '#',
    \   "conf": '#',
    \   "profile": '#',
    \   "bashrc": '#',
    \   "bash_profile": '#',
    \   "mail": '>',
    \   "eml": '>',
    \   "bat": 'REM',
    \   "ahk": ';',
    \   "vim": '"',
    \   "tex": '%',
    \ }

function! ToggleComment()
    if has_key(s:comment_map, &filetype)
        let comment_leader = s:comment_map[&filetype]
        if getline('.') =~ "^\\s*" . comment_leader . " " 
            " Uncomment the line
            execute "silent s/^\\(\\s*\\)" . comment_leader . " /\\1/"
        else 
            if getline('.') =~ "^\\s*" . comment_leader
                " Uncomment the line
                execute "silent s/^\\(\\s*\\)" . comment_leader . "/\\1/"
            else
                " Comment the line
                execute "silent s/^\\(\\s*\\)/\\1" . comment_leader . " /"
            end
        end
    else
        echo "No comment leader found for filetype"
    end
endfunction


nnoremap <leader><Space> :call ToggleComment()<cr>
vnoremap <leader><Space> :call ToggleComment()<cr>

Note:

注意:

I don't use any callbacks or hooks into the file types/loading, because I find they slow down Vim's startup more than the .vimrc static function/map does but that's just my preference. I've also tried to keep it simple and performant. If you do use autocommands you need to be sure to put them in an autocommand group or else the callbacks get added to the filetype multiple times per-file loaded and cause a lot of performance degradation.

我不使用任何回调或钩子到文件类型/加载中,因为我发现它们比.vimrc静态函数/map更慢地减慢了Vim的启动,但这只是我的偏好。我也试着保持它的简单和性能。如果您确实使用自动命令,那么您需要确保将它们放入autocommand组,否则回调会被添加到文件类型的多次加载中,并导致大量性能下降。

#9


22  

Use Control-V to select rectangles of text: go to the first # character, type Ctrl+V, move right once, and then down, up to the end of the comments. Now type x: you're deleting all the # characters followed by one space.

使用Control-V来选择文本的矩形:选择第一个#字符,键入Ctrl+V,右移一次,然后向下,直到注释的末尾。现在键入x:删除所有的#字符,然后是一个空格。

#10


18  

Toggle comments

If all you need is toggle comments I'd rather go with commentary.vim by tpope.

如果你所需要的只是切换评论,我宁愿选择评论。由tpope vim。

在Vim中,什么是快速评论/取消评论的方式?

Installation

Pathogen:

病原体:

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

vim-plug:

vim-plug:

Plug 'tpope/vim-commentary'

Vundle:

Vundle:

Plugin 'tpope/vim-commentary'

Further customization

Add this to your .vimrc file: noremap <leader>/ :Commentary<cr>

将此添加到.vimrc文件:noremap /:注释

You can now toggle comments by pressing Leader+/, just like Sublime and Atom.

现在你可以通过按下Leader+/,就像崇高和原子一样切换评论。

#11


16  

First press --> CtrlV

第一次新闻- - > CtrlV

Press arrow key up or down as needed

按需要按箭头键向上或向下。

Then press --> ShiftI

然后按- - > ShiftI

Then insert comment using --> Shift#

然后使用->移位#插入注释。

Esc

Esc

#12


13  

Here is a section of my .vimrc:

这是我的。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>

In normal and in visual mode, this lets me press ,ic to insert comments and,rc to remove comments.

在正常和可视模式下,这让我按下,ic插入注释,rc删除评论。

#13


9  

CtrlV

CtrlV

drop down using arrow key

使用箭头键向下拉。

ShiftI

ShiftI

Shift#

转变#

Esc

Esc

then wait and done

然后等着做

#14


8  

I like to use the tcomment plugin: http://www.vim.org/scripts/script.php?script_id=1173

我喜欢使用tcomment插件:http://www.vim.org/scripts/script.php?script_id=1173。

I have mapped gc and gcc to comment a line or a highlighted block of code. It detects the file type and works really well.

我已经映射了gc和gcc来注释一行或高亮显示的代码块。它检测文件类型,并且工作得很好。

#15


6  

I use EnhancedCommentify. It comments everything I needed (programming languages, scripts, config files). I use it with visual-mode bindings. Simply select text you want to comment and press co/cc/cd.

我使用EnhancedCommentify。它评论我所需要的一切(编程语言、脚本、配置文件)。我使用它的视觉模式绑定。简单地选择你想要评论的文本,然后按co/cc/cd。

vmap co :call EnhancedCommentify('','guess')<CR>
vmap cc :call EnhancedCommentify('','comment')<CR>
vmap cd :call EnhancedCommentify('','decomment')<CR> 

#16


6  

With 30 answers ahead of me, I'll try to give an even easier solution: Insert a # at the beginning of the line. Then go down a line and press dot (.). To repeat, do j,.,j,., etc...To uncomment, remove a # (you can hit x over the #), and do the reverse using k,.,etc...

在我前面有30个答案,我将尝试给出一个更简单的解决方案:在一行的开头插入一个#。然后沿着线和按点(。)重复,做j。j。等……若要取消注释,请删除#(您可以在#上单击x),然后使用k进行反向操作,等等……

#17


5  

If you already know the line numbers, then n,ms/# // would work.

如果你已经知道行号,那么n,ms/# //就可以了。

#18


5  

I mark the first and last lines (ma and mb), and then do :'a,'bs/^# //

马克我第一个和最后一个行(马和mb),然后做:',' b / ^ # / /

#19


5  

Yes, there are 33 (mostly repetitive) answers already to this question.

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

Here is another approach to how to comment lines out in Vim: motions. The basic idea is to comment or uncomment lines out using the same method as yanking a paragraph by typing yip or deleting 2 lines by typing dj.

下面是另一种方法,如何在Vim中注释行:动作。基本的想法是用相同的方法来评论或取消注释,比如通过键入yip或删除2行,通过输入dj来删除一个段落。

This approach will let you do things like:

这种方法可以让你做如下事情:

  • ccj to comment the next 2 lines out, and cuk to uncomment them;

    ccj对下面两行进行注释,cuk取消注释;

  • cci{ to comment a block out, and cui{ to uncomment it;

    cci{to comment a block out, and cui{to uncomment it;

  • ccip to comment a whole paragraph out, and cuip to uncomment it.

    ccip评论一整个段落,和cuip取消评论。

  • ccG to comment everything out down to the last line, and cugg to uncomment everything up to the first line.

    ccG把所有的东西都写在最后一行,而cugg把所有的东西都写在第一行。

All you need are 2 functions that operate over motions, and 2 mappings for each function. First, the mappings:

你所需要的是两个运行在运动上的函数,以及两个函数的映射。首先,映射:

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>

(See the manual about the g@ operator and the operatorfunc variable.)

(参阅有关g@操作符和operatorfunc变量的手册)。

And now the functions:

现在的功能:

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

Modify the regular expressions above to suit your taste as to where the # should be:

修改上面的正则表达式,以符合你的口味:

#20


4  

I use Tim Pope's vim-commentary plugin.

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

#21


4  

How to uncomment the following three lines in vi:

如何对以下三行进行注释:

#code code
#code
#code code code

Place the cursor over the upper left # symbol and press CtrlV. This puts you in visual block mode. Press the down arrow or J three times to select all three lines. Then press D. All the comments disappear. To undo, press U.

将光标放置在左上角,并按下ctrl键。这将使您处于可视块模式。按下箭头或J三次,选择所有三行。然后按d,所有的评论都消失了。取消,按U。

How to comment the following three lines in vi:

如何对以下三行进行注释:

code code
code
code code code

Place the cursor over the upper left character, press CtrlV. This puts you in visual block mode. Press or J three times to select all three lines. Then press:

将光标置于左上方的字符,按下ctrl键。这将使您处于可视块模式。按↓或J三次选择所有三行。然后按:

I//Esc

我/ / Esc

That's a capital I, //, and Escape.

那是一个大写的I, //,和Escape。

When you press ESC, all the selected lines will get the comment symbol you specified.

当您按ESC时,所有选定的行将得到您指定的注释符号。

#22


3  

I combined Phil and jqno's answer and made untoggle comments with spaces:

我把Phil和jqno的答案结合在一起,然后用空格做了一些不可思议的评论:

autocmd FileType c,cpp,java,scala let b:comment_leader = '//'
autocmd FileType sh,ruby,python   let b:comment_leader = '#'
autocmd FileType conf,fstab       let b:comment_leader = '#'
autocmd FileType tex              let b:comment_leader = '%'
autocmd FileType mail             let b:comment_leader = '>'
autocmd FileType vim              let b:comment_leader = '"'
function! CommentToggle()
    execute ':silent! s/\([^ ]\)/' . b:comment_leader . ' \1/'
    execute ':silent! s/^\( *\)' . b:comment_leader . ' \?' . b:comment_leader . ' \?/\1/'
endfunction
map <F7> :call CommentToggle()<CR>

#23


3  

Here's a basic one-liner based on the C-v followed by I method outlined above.

这是基于C-v的一种基本的一行程序,然后是上面概述的方法。

This command (:Comment) adds a chosen string to the beginning of any selected lines.

此命令(:Comment)将选择的字符串添加到任意选定行的开头。

command! -range -nargs=1 Comment :execute "'<,'>normal! <C-v>0I" . <f-args> . "<Esc><Esc>"

Add this line to your .vimrc to create a command that accepts a single argument and places the argument at the beginning of every line in the current selection.

将这一行添加到.vimrc中,创建一个命令,该命令接受一个参数,并在当前选择的每一行的开始处放置参数。

E.g. if the following text is selected:

如选择下列文字:

1
2

and you run this: :Comment //, the result will be:

你运行这个::Comment //,结果将是:

//1
//2

#24


3  

Starting with the ideas in answers here, I started my own comment function. It toggles comments on and off. It can handle things like //print('blue'); //this thing is blue and just toggles the first comment. Furthermore it adds comments and a single space just where the first non whitespace is and not at the very start of the line. Aditionally it doesn't unnecessarily copy the whitespaces, but uses zooms (:h \zs for help) to avoid this extra work, when commenting and indented line. Hope it helps some minimalists out there. Suggestions are welcome.

从这里的答案开始,我开始了自己的评论功能。它可以来回切换注释,它可以处理诸如//print('blue')之类的东西;//这个东西是蓝色的,只需要切换第一个注释。此外,它还添加了注释和一个空格,这是第一个非空格的位置,而不是在行的开头。从本质上说,它并不会不必要地复制空白,而是使用zooms (:h \zs)来避免这种额外的工作,在注释和缩进行中。希望它能帮助一些极简主义者。欢迎提出您的建议。

" these lines are needed for ToggleComment()
autocmd FileType c,cpp,java      let b:comment_leader = '//'
autocmd FileType arduino         let b:comment_leader = '//'
autocmd FileType sh,ruby,python  let b:comment_leader = '#'
autocmd FileType zsh             let b:comment_leader = '#'
autocmd FileType conf,fstab      let b:comment_leader = '#'
autocmd FileType matlab,tex      let b:comment_leader = '%'
autocmd FileType vim             let b:comment_leader = '"'

" l:pos   --> cursor position
" l:space --> how many spaces we will use b:comment_leader + ' '

function! ToggleComment()
    if exists('b:comment_leader')
        let l:pos = col('.')
        let l:space = ( &ft =~ '\v(c|cpp|java|arduino)' ? '3' : '2' )
        if getline('.') =~ '\v(\s*|\t*)' .b:comment_leader
            let l:space -= ( getline('.') =~ '\v.*\zs' . b:comment_leader . '(\s+|\t+)@!' ?  1 : 0 )
            execute 'silent s,\v^(\s*|\t*)\zs' .b:comment_leader.'[ ]?,,g'
            let l:pos -= l:space
        else
            exec 'normal! 0i' .b:comment_leader .' '
            let l:pos += l:space
        endif
        call cursor(line("."), l:pos)
    else
        echo 'no comment leader found for filetype'
    end
endfunction

nnoremap <Leader>t :call ToggleComment()<CR>
inoremap <Leader>t <C-o>:call ToggleComment()<CR>
xnoremap <Leader>t :'<,'>call ToggleComment()<CR>

#25


3  

I use comments.vim from Jasmeet Singh Anand (found on vim.org),

我使用注释。来自Jasmeet Singh Anand的vim(在vim.org上找到),

It works with 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, and normal files

它使用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和普通文件。

It comments and un-comments lines in different source files in both normal and visual mode

它在不同的源文件中以正常的和可视的方式评论和取消评论。

Usage:

用法:

  • CtrlC to comment a single line
  • 对一行进行注释。
  • CtrlX to un-comment a single line
  • ctrl +取消注释一行。
  • ShiftV and select multiple lines, then CtrlC to comment the selected multiple lines
  • ShiftV并选择多个行,然后按ctrl键对选中的多行进行注释。
  • ShiftV and select multiple lines, then CtrlX to un-comment the selected multiple lines
  • ShiftV和选择多行,然后ctrl +取消选中的多行。

#26


3  

There is this life changing plugin by tpope called vim-commentary

有一种生活变化的插件被tpope称为vim评论。

https://github.com/tpope/vim-commentary

https://github.com/tpope/vim-commentary

This plugin provides:

这个插件提供了:

  • Sanity
  • 理智
  • Properly indented comments
  • 适当的缩进的评论
  • Does not comment out empty/unnecessary lines
  • 不注释空/不必要的行吗?

Usage:

用法:

  • Install via Vundle (or Pathogen I guess).
  • 通过Vundle(或病原体)安装。
  • Highlight your text and press : which will show as :<,'>
  • 突出你的文本和媒体:它将显示为:<,>。
  • Type Commentary here :<,'>Commentary and press Enter.
  • 类型注释:<,>评论和按回车。
  • Boom. Your done bud.
  • 繁荣。你做的萌芽状态。

#27


2  

This simple snippet is from my .vimrc:

这个简单的片段来自我的。vimrc:

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

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

It's for //-Comments, but you can adapt it easily for other characters. You could use autocmd to set a leader as jqno suggested.

它是//-评论,但你可以很容易地改编成其他角色。您可以使用autocmd作为jqno建议的领导者。

This is a very simple and efficient way working with ranges and visual mode naturally.

这是一种非常简单有效的方法,可以很自然地使用范围和视觉模式。

#28


2  

You can use vim-commentary by tpope (https://github.com/tpope/vim-commentary) you can use it as following:

您可以使用tpope的vim评论(https://github.com/tpope/vim评论),您可以使用它如下:

Enter visual mode by pressing

通过按压进入视觉模式。

'v'

Then press

然后按

'j' repeatedly or e.g 4j to select 4 row

Now all you have to do with the selection is enter keys:

现在你所要做的选择是输入键:

'gc'

This will comment out all the selection, to uncomment repead keys:

这将注释掉所有的选择,取消评论的重复键:

'gc'

#29


2  

I use vim-multiple-cursors for this.

我用vim- multicursors来做这个。

  1. To select the region, go to the first character of the first or last line of the region to be commented out by pressing 0 (it's zero, not letter "o"). Then press V and select the region using J, K or up and down arrow keys.
  2. 要选择该区域,请选择该区域的第一个或最后一行的第一个字符,按0(它是0,而不是字母“o”)注释掉该区域。然后按V,选择使用J、K或上下方向键的区域。
  3. Then put a virtual cursor on each line of the selection by pressing CtrlN.
  4. 然后按下ctrl键,在选择的每一行上放置一个虚拟光标。
  5. Then press I to simultaneously edit each line of the selection.
  6. 然后按我同时编辑每一行的选择。

#30


2  

The quickest and the most intuitive method of them all is to remap ) for walk-down-commenting of lines, and then ( for walk-up-uncommenting. Try it and you won't go back.

其中最快捷、最直观的方法是重新映射),用于对行进行简单的注释,然后(对未进行注释的)进行重新映射。尝试一下,你就不会回来了。

In Ruby or Bash, with 2-space indents:

在Ruby或Bash中,有2个空格的缩进:

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

In C/C++ or PHP, with 4-space indents:

在C/ c++或PHP中,有4个空格:

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

Downsides are that you lose ( and ) for sentence-movement (but das can fill in there), and you'll occasionally fall back on select-and-replace or CtrlV for handling long sections. But that's pretty rare.

缺点是你丢失了(和)的句子移动(但是das可以在那里填充),并且你偶尔会退回到选择-替换或ctrl +来处理长段。但这是非常罕见的。

And for C-style, the long comments are best handled with:

对于c风格,长篇大论最好的处理方式是:

set cindent
set formatoptions=tcqr

... Which combines well with using V[move]gq to redo the word-wrapping.

…它很好地结合使用V[move]gq来重做单词包装。

#1


154  

I use the NERD Commenter script. It lets you easily comment, uncomment or toggle comments in your code.

我用的是书呆子的评论脚本。它允许您轻松地评论、取消注释或在您的代码中切换注释。

#2


1637  

For those tasks I use most of the time block selection.

对于那些任务,我使用了大部分的时间块选择。

Put your cursor on the first # character, press CtrlV (or CtrlQ for gVim), and go down until the last commented line and press x, that will delete all the # characters vertically.

将光标放在第一个#字符上,按下ctrl(或ctrl + gVim),直到最后一个注释行和按x,这样就可以垂直删除所有的字符。

For commenting a block of text is almost the same:

对于评论一个文本块几乎是一样的:

  1. First, go to the first line you want to comment, press CtrlV. This will put the editor in the VISUAL BLOCK mode.
  2. 首先,转到您想要评论的第一行,按下ctrl键。这将使编辑器处于可视块模式。
  3. Then using the arrow key and select until the last line
  4. 然后使用箭头键并选择到最后一行。
  5. Now press ShiftI, which will put the editor in INSERT mode and then press #. This will add a hash to the first line.
  6. 现在按ShiftI,将编辑器插入插入模式,然后按#。这将向第一行添加一个散列。
  7. Then press Esc (give it a second), and it will insert a # character on all other selected lines.
  8. 然后按Esc(给它一秒钟),它将在所有其他选定的行中插入一个#字符。

For the stripped-down version of vim shipped with debian/ubuntu by default, type : s/^/# in the third step instead.

精简版的vim附带debian / ubuntu默认情况下,类型:s / ^ / #第三步。

#3


618  

To comment out blocks in vim:

  • press Esc (to leave editing or other mode)
  • 按Esc(离开编辑或其他模式)
  • hit ctrl+v (visual block mode)
  • 按ctrl+v(可视块模式)
  • use the up/down arrow keys to select lines you want (it won't highlight everything - it's OK!)
  • 使用向上/向下的箭头键来选择你想要的线(它不会突出任何东西——它是可以的!)
  • Shift+i (capital I)
  • Shift +我(资本)
  • insert the text you want, i.e. %
  • 插入你想要的文本,即%。
  • press EscEsc
  • 新闻EscEsc

To uncomment blocks in vim:

  • press Esc (to leave editing or other mode)
  • 按Esc(离开编辑或其他模式)
  • hit ctrl+v (visual block mode)
  • 按ctrl+v(可视块模式)
  • use the / arrow keys to select the lines to uncomment.

    If you want to select multiple characters, use one or combine these methods:

    如果您想选择多个字符,请使用一个或组合这些方法:

    • use the left/right arrow keys to select more text
    • 使用左/右箭头键选择更多文本。
    • to select chunks of text use shift + / arrow key
    • 选择的文本块使用shift +←/→箭头键
    • you can repeatedly push the delete keys below, like a regular delete button

    • 你可以重复地按下删除键,就像一个普通的删除按钮。
  • press d or x to delete characters, repeatedly if necessary
  • 按d或x删除字符,必要时重复。

#4


202  

Sometimes I'm shelled into a remote box where my plugins and .vimrc cannot help me, or sometimes NerdCommenter gets it wrong (eg JavaScript embedded inside html).

有时我被放在一个远程的盒子里,我的插件和.vimrc无法帮助我,或者有时候NerdCommenter会出错(比如JavaScript嵌入到html中)。

In these cases a low-tech alternative is the built-in norm command, which just runs any arbitrary vim commands at each line in your specified range. For example:

在这些情况下,低技术的替代方法是内置的norm命令,它只在指定范围内的每一行运行任意的vim命令。例如:

Commenting with #:

注释以#:

1. visually select the text rows (using V as usual)
2. :norm i#

This inserts "#" at the start of each line. Note that when you type : the range will be filled in, so it will really look like :'<,'>norm i#

这将在每一行的开头插入“#”。请注意,当您键入时,范围将被填充,因此它将看起来是:'<,>规范i#。

Uncommenting #:

现在#:

1. visually select the text as before (or type gv to re-select the previous selection)
2. :norm x

This deletes the first character of each line. If I had used a 2-char comment such as // then I'd simply do :norm xx to delete both chars.

这将删除每一行的第一个字符。如果我使用了一个2字符的注释,比如//那么我就只做:norm xx来删除两个字符。

If the comments are indented as in the OP's question, then you can anchor your deletion like this:

如果在OP的问题中,注释是缩进的,那么您可以像这样锚定您的删除:

:norm ^x

which means "go to the first non-space character, then delete one character".

意思是“去到第一个非空格字符,然后删除一个字符”。

Note: Since norm is literally just executing regular vim commands, you're not limited just to comments, you could do some complex editing to each line. If you need the escape character as part of your command sequence, type ctrl-v then hit the escape key.

注意:由于norm实际上只是执行常规的vim命令,所以您不仅限于注释,还可以对每一行进行一些复杂的编辑。如果您需要将转义字符作为命令序列的一部分,那么键入ctrl-v然后按escape键。

Note 2: You could of course also add a mapping if you find yourself using norm a lot. Eg putting the following line in ~/.vimrc lets you type ctrl-n instead of :norm after making your visual selection

注2:如果你发现自己经常使用规范,你当然也可以添加一个映射。vimrc允许您在进行可视化选择后键入ctrl-n而不是:norm。

vnoremap <C-n> :norm

Note 3: Bare-bones vim sometimes doesn't have the norm command compiled into it, so be sure to use the beefed up version, ie typically /usr/bin/vim, not /bin/vi

注释3:Bare-bones vim有时没有编译到它的norm命令,所以一定要使用健壮的版本(通常是/usr/bin/vim,而不是/bin/vi)。

(Thanks to @Manbroski and @rakslice for improvements incorporated into this answer)

(感谢@Manbroski和@rakslice将改进纳入了这个答案)

#5


99  

I have the following in my .vimrc:

以下是我的。vimrc:

" Commenting blocks of code.
autocmd FileType c,cpp,java,scala let b:comment_leader = '// '
autocmd FileType sh,ruby,python   let b:comment_leader = '# '
autocmd FileType conf,fstab       let b:comment_leader = '# '
autocmd FileType tex              let b:comment_leader = '% '
autocmd FileType mail             let b:comment_leader = '> '
autocmd FileType vim              let b:comment_leader = '" '
noremap <silent> ,cc :<C-B>silent <C-E>s/^/<C-R>=escape(b:comment_leader,'\/')<CR>/<CR>:nohlsearch<CR>
noremap <silent> ,cu :<C-B>silent <C-E>s/^\V<C-R>=escape(b:comment_leader,'\/')<CR>//e<CR>:nohlsearch<CR>

Now you can type ,cc to comment a line and ,cu to uncomment a line (works both in normal and visual mode).

现在你可以键入,cc来注释一行,cu可以取消注释一行(在正常和可视模式下都可以)。

(I stole it from some website many years ago so I can't completely explain how it works anymore :). There is a comment where it is explained.)

(很多年前我从某个网站上偷了它,所以我无法完全解释它的工作原理:)。这里有一个注释。

#6


76  

Specify which lines to comment in vim:

在vim中指定要评论的行:

Reveal the line numbers:

显示行号:

:set number

then

然后

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

or this:

或:

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

#7


45  

Here is how I do it:

下面是我的做法:

  1. Go to first character on the first line you want to comment out.

    第一行的第一个字符要注释掉。

  2. Hit Ctrl+q in GVIM or Ctrl+v in VIM, then go down to select first character on the lines to comment out.

    在VIM中按下Ctrl+q键或Ctrl+v,然后向下选择要注释的行中的第一个字符。

  3. Then press c, and add the comment character.

    然后按c,添加注释字符。

Uncommenting works the same way, just type a space instead of the comment character.

没有注释的工作方式相同,只是键入一个空格而不是注释字符。

#8


26  

I've come up with a simple addition to my .vimrc file which works pretty well and can be extended easily. You simply add a new filetype to the comment_map and its comment leader.

我提出了一个简单的添加到.vimrc文件中,它工作得很好,可以很容易地扩展。您只需向comment_map和它的comment leader添加一个新的filetype。

I added a mapping to normal and visual modes, but you can remap to anything you like. I prefer only to have a 'toggle' style function. One bears having multiple mappings etc.

我添加了一个映射到正常的和可视的模式,但是你可以重新映射到你喜欢的任何东西。我喜欢只有“切换”样式的功能。一个熊有多个映射等等。

let s:comment_map = { 
    \   "c": '\/\/',
    \   "cpp": '\/\/',
    \   "go": '\/\/',
    \   "java": '\/\/',
    \   "javascript": '\/\/',
    \   "lua": '--',
    \   "scala": '\/\/',
    \   "php": '\/\/',
    \   "python": '#',
    \   "ruby": '#',
    \   "rust": '\/\/',
    \   "sh": '#',
    \   "desktop": '#',
    \   "fstab": '#',
    \   "conf": '#',
    \   "profile": '#',
    \   "bashrc": '#',
    \   "bash_profile": '#',
    \   "mail": '>',
    \   "eml": '>',
    \   "bat": 'REM',
    \   "ahk": ';',
    \   "vim": '"',
    \   "tex": '%',
    \ }

function! ToggleComment()
    if has_key(s:comment_map, &filetype)
        let comment_leader = s:comment_map[&filetype]
        if getline('.') =~ "^\\s*" . comment_leader . " " 
            " Uncomment the line
            execute "silent s/^\\(\\s*\\)" . comment_leader . " /\\1/"
        else 
            if getline('.') =~ "^\\s*" . comment_leader
                " Uncomment the line
                execute "silent s/^\\(\\s*\\)" . comment_leader . "/\\1/"
            else
                " Comment the line
                execute "silent s/^\\(\\s*\\)/\\1" . comment_leader . " /"
            end
        end
    else
        echo "No comment leader found for filetype"
    end
endfunction


nnoremap <leader><Space> :call ToggleComment()<cr>
vnoremap <leader><Space> :call ToggleComment()<cr>

Note:

注意:

I don't use any callbacks or hooks into the file types/loading, because I find they slow down Vim's startup more than the .vimrc static function/map does but that's just my preference. I've also tried to keep it simple and performant. If you do use autocommands you need to be sure to put them in an autocommand group or else the callbacks get added to the filetype multiple times per-file loaded and cause a lot of performance degradation.

我不使用任何回调或钩子到文件类型/加载中,因为我发现它们比.vimrc静态函数/map更慢地减慢了Vim的启动,但这只是我的偏好。我也试着保持它的简单和性能。如果您确实使用自动命令,那么您需要确保将它们放入autocommand组,否则回调会被添加到文件类型的多次加载中,并导致大量性能下降。

#9


22  

Use Control-V to select rectangles of text: go to the first # character, type Ctrl+V, move right once, and then down, up to the end of the comments. Now type x: you're deleting all the # characters followed by one space.

使用Control-V来选择文本的矩形:选择第一个#字符,键入Ctrl+V,右移一次,然后向下,直到注释的末尾。现在键入x:删除所有的#字符,然后是一个空格。

#10


18  

Toggle comments

If all you need is toggle comments I'd rather go with commentary.vim by tpope.

如果你所需要的只是切换评论,我宁愿选择评论。由tpope vim。

在Vim中,什么是快速评论/取消评论的方式?

Installation

Pathogen:

病原体:

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

vim-plug:

vim-plug:

Plug 'tpope/vim-commentary'

Vundle:

Vundle:

Plugin 'tpope/vim-commentary'

Further customization

Add this to your .vimrc file: noremap <leader>/ :Commentary<cr>

将此添加到.vimrc文件:noremap /:注释

You can now toggle comments by pressing Leader+/, just like Sublime and Atom.

现在你可以通过按下Leader+/,就像崇高和原子一样切换评论。

#11


16  

First press --> CtrlV

第一次新闻- - > CtrlV

Press arrow key up or down as needed

按需要按箭头键向上或向下。

Then press --> ShiftI

然后按- - > ShiftI

Then insert comment using --> Shift#

然后使用->移位#插入注释。

Esc

Esc

#12


13  

Here is a section of my .vimrc:

这是我的。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>

In normal and in visual mode, this lets me press ,ic to insert comments and,rc to remove comments.

在正常和可视模式下,这让我按下,ic插入注释,rc删除评论。

#13


9  

CtrlV

CtrlV

drop down using arrow key

使用箭头键向下拉。

ShiftI

ShiftI

Shift#

转变#

Esc

Esc

then wait and done

然后等着做

#14


8  

I like to use the tcomment plugin: http://www.vim.org/scripts/script.php?script_id=1173

我喜欢使用tcomment插件:http://www.vim.org/scripts/script.php?script_id=1173。

I have mapped gc and gcc to comment a line or a highlighted block of code. It detects the file type and works really well.

我已经映射了gc和gcc来注释一行或高亮显示的代码块。它检测文件类型,并且工作得很好。

#15


6  

I use EnhancedCommentify. It comments everything I needed (programming languages, scripts, config files). I use it with visual-mode bindings. Simply select text you want to comment and press co/cc/cd.

我使用EnhancedCommentify。它评论我所需要的一切(编程语言、脚本、配置文件)。我使用它的视觉模式绑定。简单地选择你想要评论的文本,然后按co/cc/cd。

vmap co :call EnhancedCommentify('','guess')<CR>
vmap cc :call EnhancedCommentify('','comment')<CR>
vmap cd :call EnhancedCommentify('','decomment')<CR> 

#16


6  

With 30 answers ahead of me, I'll try to give an even easier solution: Insert a # at the beginning of the line. Then go down a line and press dot (.). To repeat, do j,.,j,., etc...To uncomment, remove a # (you can hit x over the #), and do the reverse using k,.,etc...

在我前面有30个答案,我将尝试给出一个更简单的解决方案:在一行的开头插入一个#。然后沿着线和按点(。)重复,做j。j。等……若要取消注释,请删除#(您可以在#上单击x),然后使用k进行反向操作,等等……

#17


5  

If you already know the line numbers, then n,ms/# // would work.

如果你已经知道行号,那么n,ms/# //就可以了。

#18


5  

I mark the first and last lines (ma and mb), and then do :'a,'bs/^# //

马克我第一个和最后一个行(马和mb),然后做:',' b / ^ # / /

#19


5  

Yes, there are 33 (mostly repetitive) answers already to this question.

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

Here is another approach to how to comment lines out in Vim: motions. The basic idea is to comment or uncomment lines out using the same method as yanking a paragraph by typing yip or deleting 2 lines by typing dj.

下面是另一种方法,如何在Vim中注释行:动作。基本的想法是用相同的方法来评论或取消注释,比如通过键入yip或删除2行,通过输入dj来删除一个段落。

This approach will let you do things like:

这种方法可以让你做如下事情:

  • ccj to comment the next 2 lines out, and cuk to uncomment them;

    ccj对下面两行进行注释,cuk取消注释;

  • cci{ to comment a block out, and cui{ to uncomment it;

    cci{to comment a block out, and cui{to uncomment it;

  • ccip to comment a whole paragraph out, and cuip to uncomment it.

    ccip评论一整个段落,和cuip取消评论。

  • ccG to comment everything out down to the last line, and cugg to uncomment everything up to the first line.

    ccG把所有的东西都写在最后一行,而cugg把所有的东西都写在第一行。

All you need are 2 functions that operate over motions, and 2 mappings for each function. First, the mappings:

你所需要的是两个运行在运动上的函数,以及两个函数的映射。首先,映射:

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>

(See the manual about the g@ operator and the operatorfunc variable.)

(参阅有关g@操作符和operatorfunc变量的手册)。

And now the functions:

现在的功能:

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

Modify the regular expressions above to suit your taste as to where the # should be:

修改上面的正则表达式,以符合你的口味:

#20


4  

I use Tim Pope's vim-commentary plugin.

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

#21


4  

How to uncomment the following three lines in vi:

如何对以下三行进行注释:

#code code
#code
#code code code

Place the cursor over the upper left # symbol and press CtrlV. This puts you in visual block mode. Press the down arrow or J three times to select all three lines. Then press D. All the comments disappear. To undo, press U.

将光标放置在左上角,并按下ctrl键。这将使您处于可视块模式。按下箭头或J三次,选择所有三行。然后按d,所有的评论都消失了。取消,按U。

How to comment the following three lines in vi:

如何对以下三行进行注释:

code code
code
code code code

Place the cursor over the upper left character, press CtrlV. This puts you in visual block mode. Press or J three times to select all three lines. Then press:

将光标置于左上方的字符,按下ctrl键。这将使您处于可视块模式。按↓或J三次选择所有三行。然后按:

I//Esc

我/ / Esc

That's a capital I, //, and Escape.

那是一个大写的I, //,和Escape。

When you press ESC, all the selected lines will get the comment symbol you specified.

当您按ESC时,所有选定的行将得到您指定的注释符号。

#22


3  

I combined Phil and jqno's answer and made untoggle comments with spaces:

我把Phil和jqno的答案结合在一起,然后用空格做了一些不可思议的评论:

autocmd FileType c,cpp,java,scala let b:comment_leader = '//'
autocmd FileType sh,ruby,python   let b:comment_leader = '#'
autocmd FileType conf,fstab       let b:comment_leader = '#'
autocmd FileType tex              let b:comment_leader = '%'
autocmd FileType mail             let b:comment_leader = '>'
autocmd FileType vim              let b:comment_leader = '"'
function! CommentToggle()
    execute ':silent! s/\([^ ]\)/' . b:comment_leader . ' \1/'
    execute ':silent! s/^\( *\)' . b:comment_leader . ' \?' . b:comment_leader . ' \?/\1/'
endfunction
map <F7> :call CommentToggle()<CR>

#23


3  

Here's a basic one-liner based on the C-v followed by I method outlined above.

这是基于C-v的一种基本的一行程序,然后是上面概述的方法。

This command (:Comment) adds a chosen string to the beginning of any selected lines.

此命令(:Comment)将选择的字符串添加到任意选定行的开头。

command! -range -nargs=1 Comment :execute "'<,'>normal! <C-v>0I" . <f-args> . "<Esc><Esc>"

Add this line to your .vimrc to create a command that accepts a single argument and places the argument at the beginning of every line in the current selection.

将这一行添加到.vimrc中,创建一个命令,该命令接受一个参数,并在当前选择的每一行的开始处放置参数。

E.g. if the following text is selected:

如选择下列文字:

1
2

and you run this: :Comment //, the result will be:

你运行这个::Comment //,结果将是:

//1
//2

#24


3  

Starting with the ideas in answers here, I started my own comment function. It toggles comments on and off. It can handle things like //print('blue'); //this thing is blue and just toggles the first comment. Furthermore it adds comments and a single space just where the first non whitespace is and not at the very start of the line. Aditionally it doesn't unnecessarily copy the whitespaces, but uses zooms (:h \zs for help) to avoid this extra work, when commenting and indented line. Hope it helps some minimalists out there. Suggestions are welcome.

从这里的答案开始,我开始了自己的评论功能。它可以来回切换注释,它可以处理诸如//print('blue')之类的东西;//这个东西是蓝色的,只需要切换第一个注释。此外,它还添加了注释和一个空格,这是第一个非空格的位置,而不是在行的开头。从本质上说,它并不会不必要地复制空白,而是使用zooms (:h \zs)来避免这种额外的工作,在注释和缩进行中。希望它能帮助一些极简主义者。欢迎提出您的建议。

" these lines are needed for ToggleComment()
autocmd FileType c,cpp,java      let b:comment_leader = '//'
autocmd FileType arduino         let b:comment_leader = '//'
autocmd FileType sh,ruby,python  let b:comment_leader = '#'
autocmd FileType zsh             let b:comment_leader = '#'
autocmd FileType conf,fstab      let b:comment_leader = '#'
autocmd FileType matlab,tex      let b:comment_leader = '%'
autocmd FileType vim             let b:comment_leader = '"'

" l:pos   --> cursor position
" l:space --> how many spaces we will use b:comment_leader + ' '

function! ToggleComment()
    if exists('b:comment_leader')
        let l:pos = col('.')
        let l:space = ( &ft =~ '\v(c|cpp|java|arduino)' ? '3' : '2' )
        if getline('.') =~ '\v(\s*|\t*)' .b:comment_leader
            let l:space -= ( getline('.') =~ '\v.*\zs' . b:comment_leader . '(\s+|\t+)@!' ?  1 : 0 )
            execute 'silent s,\v^(\s*|\t*)\zs' .b:comment_leader.'[ ]?,,g'
            let l:pos -= l:space
        else
            exec 'normal! 0i' .b:comment_leader .' '
            let l:pos += l:space
        endif
        call cursor(line("."), l:pos)
    else
        echo 'no comment leader found for filetype'
    end
endfunction

nnoremap <Leader>t :call ToggleComment()<CR>
inoremap <Leader>t <C-o>:call ToggleComment()<CR>
xnoremap <Leader>t :'<,'>call ToggleComment()<CR>

#25


3  

I use comments.vim from Jasmeet Singh Anand (found on vim.org),

我使用注释。来自Jasmeet Singh Anand的vim(在vim.org上找到),

It works with 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, and normal files

它使用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和普通文件。

It comments and un-comments lines in different source files in both normal and visual mode

它在不同的源文件中以正常的和可视的方式评论和取消评论。

Usage:

用法:

  • CtrlC to comment a single line
  • 对一行进行注释。
  • CtrlX to un-comment a single line
  • ctrl +取消注释一行。
  • ShiftV and select multiple lines, then CtrlC to comment the selected multiple lines
  • ShiftV并选择多个行,然后按ctrl键对选中的多行进行注释。
  • ShiftV and select multiple lines, then CtrlX to un-comment the selected multiple lines
  • ShiftV和选择多行,然后ctrl +取消选中的多行。

#26


3  

There is this life changing plugin by tpope called vim-commentary

有一种生活变化的插件被tpope称为vim评论。

https://github.com/tpope/vim-commentary

https://github.com/tpope/vim-commentary

This plugin provides:

这个插件提供了:

  • Sanity
  • 理智
  • Properly indented comments
  • 适当的缩进的评论
  • Does not comment out empty/unnecessary lines
  • 不注释空/不必要的行吗?

Usage:

用法:

  • Install via Vundle (or Pathogen I guess).
  • 通过Vundle(或病原体)安装。
  • Highlight your text and press : which will show as :<,'>
  • 突出你的文本和媒体:它将显示为:<,>。
  • Type Commentary here :<,'>Commentary and press Enter.
  • 类型注释:<,>评论和按回车。
  • Boom. Your done bud.
  • 繁荣。你做的萌芽状态。

#27


2  

This simple snippet is from my .vimrc:

这个简单的片段来自我的。vimrc:

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

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

It's for //-Comments, but you can adapt it easily for other characters. You could use autocmd to set a leader as jqno suggested.

它是//-评论,但你可以很容易地改编成其他角色。您可以使用autocmd作为jqno建议的领导者。

This is a very simple and efficient way working with ranges and visual mode naturally.

这是一种非常简单有效的方法,可以很自然地使用范围和视觉模式。

#28


2  

You can use vim-commentary by tpope (https://github.com/tpope/vim-commentary) you can use it as following:

您可以使用tpope的vim评论(https://github.com/tpope/vim评论),您可以使用它如下:

Enter visual mode by pressing

通过按压进入视觉模式。

'v'

Then press

然后按

'j' repeatedly or e.g 4j to select 4 row

Now all you have to do with the selection is enter keys:

现在你所要做的选择是输入键:

'gc'

This will comment out all the selection, to uncomment repead keys:

这将注释掉所有的选择,取消评论的重复键:

'gc'

#29


2  

I use vim-multiple-cursors for this.

我用vim- multicursors来做这个。

  1. To select the region, go to the first character of the first or last line of the region to be commented out by pressing 0 (it's zero, not letter "o"). Then press V and select the region using J, K or up and down arrow keys.
  2. 要选择该区域,请选择该区域的第一个或最后一行的第一个字符,按0(它是0,而不是字母“o”)注释掉该区域。然后按V,选择使用J、K或上下方向键的区域。
  3. Then put a virtual cursor on each line of the selection by pressing CtrlN.
  4. 然后按下ctrl键,在选择的每一行上放置一个虚拟光标。
  5. Then press I to simultaneously edit each line of the selection.
  6. 然后按我同时编辑每一行的选择。

#30


2  

The quickest and the most intuitive method of them all is to remap ) for walk-down-commenting of lines, and then ( for walk-up-uncommenting. Try it and you won't go back.

其中最快捷、最直观的方法是重新映射),用于对行进行简单的注释,然后(对未进行注释的)进行重新映射。尝试一下,你就不会回来了。

In Ruby or Bash, with 2-space indents:

在Ruby或Bash中,有2个空格的缩进:

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

In C/C++ or PHP, with 4-space indents:

在C/ c++或PHP中,有4个空格:

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

Downsides are that you lose ( and ) for sentence-movement (but das can fill in there), and you'll occasionally fall back on select-and-replace or CtrlV for handling long sections. But that's pretty rare.

缺点是你丢失了(和)的句子移动(但是das可以在那里填充),并且你偶尔会退回到选择-替换或ctrl +来处理长段。但这是非常罕见的。

And for C-style, the long comments are best handled with:

对于c风格,长篇大论最好的处理方式是:

set cindent
set formatoptions=tcqr

... Which combines well with using V[move]gq to redo the word-wrapping.

…它很好地结合使用V[move]gq来重做单词包装。