问题
So I currently like this solution to commenting multiple lines in vim:
- Press
CTRL-v
(to go into Visual Block mode) - Select the lines you want to comment
- Press
Shift-i
(to go into Insert mode) - Type whatever comment characters your language uses
- Press
ESC ESC
(pressing the escape key twice makes the results appear faster)
But I would like some help mapping these steps into my vimrc file. I currently use the following to comment lines out:
vnoremap ;/ <C-v>0I// <ESC>
For those who want an explanation of what the command does:
You basically type ;/
when you're in Visual mode to use this (Visual, Visual Line, and Visual Block mode all work since the <C-v>
part forces you into Visual Block mode, which is correct).
The 0I
part will put you in Insert mode at the beginning of the line.
The // <ESC>
part will insert the comment characters //
and put you back into Normal mode.
The part I need help with is uncommenting the lines. How do I write a function in my vimrc that will basically let me toggle the //
characters?
Ideally, the solution would involve the following:
- Selecting the lines
- Pressing
;/
- If there are NO
//
characters then it will insert them - If there ARE
//
characters then it will remove them
回答1:
Put this in your .vimrc
file:
vnoremap <silent> ;/ :call ToggleComment()<cr>
function! ToggleComment()
if matchstr(getline(line(".")),'^\s*\/\/.*$') == ''
:execute "s:^://:"
else
:execute "s:^\s*//::"
endif
endfunction
回答2:
check the Commentary plugin. It allows to have one binding for all languages.
回答3:
Pretty easy with python script
function! Comment()
python3 << EOF
import vim
r = vim.current.range
line = vim.current.buffer[r.start]
if line.startswith('// '):
vim.current.buffer[r.start] = vim.current.buffer[r.start].replace('// ', '')
else:
vim.current.buffer[r.start] = '// ' + vim.current.buffer[r.start]
EOF
endfunction
" ctrl slash
noremap <C-_> :call Comment()<CR>
来源:https://stackoverflow.com/questions/38669233/function-to-comment-multiple-lines-vimrc