简体   繁体   中英

Function to Comment Multiple Lines Vimrc

So I currently like this solution to commenting multiple lines in vim:

  1. Press CTRL-v (to go into Visual Block mode)
  2. Select the lines you want to comment
  3. Press Shift-i (to go into Insert mode)
  4. Type whatever comment characters your language uses
  5. 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 <Cv> 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:

  1. Selecting the lines
  2. Pressing ;/
  3. If there are NO // characters then it will insert them
  4. If there ARE // characters then it will remove them

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

check the Commentary plugin. It allows to have one binding for all languages.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM