pythonvimeditcomments

How to toggle between comment and uncomment in Vim for Python code


I wish to have a single command to toggle commenting in a line / block of python code.

I am using the following code in my .vimrc file:

" (un-)commenting
" comment line, selection with Ctrl-N,Ctrl-N
au BufEnter *.py nnoremap ,c mn:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR>:noh<CR>`n
au BufEnter *.py inoremap ,c <C-O>mn<C-O>:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR><C-O>:noh<CR><C-O>`n
au BufEnter *.py vnoremap ,c mn:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR>:noh<CR>gv`n
"
" " uncomment line, selection with Ctrl-N,N
au BufEnter *.py nnoremap ,u mn:s/^\(\s*\)#\([^ ]\)/\1\2/ge<CR>:s/^#$//ge<CR>:noh<CR>`n
au BufEnter *.py inoremap ,u <C-O>mn<C-O>:s/^\(\s*\)#\([^ ]\)/\1\2/ge<CR><C-O>:s/^#$//ge<CR><C-O>:noh<CR><C-O>`n
au BufEnter *.py vnoremap ,u mn:s/^\(\s*\)#\([^ ]\)/\1\2/ge<CR>gv:s/#\n/\r/ge<CR>:noh<CR>gv`n

(adapted from this StackOverflow entry)

but, is thee a way to have a toggle, that is, using the same shortcut to comment if it's uncommented or uncomment if it's commented?


Solution

  • You can use the vim-commentary plugin from Tim Pope. Then you can create a mapping, for example

    nmap ,cc <Plug>CommentaryLine
    

    With this mapping you can comment and uncomment with the same key sequence. It also automatically adapts to the file type. For not supported file types you can set commentstring manually.

    The default mapping is gcc and it does exactly what you're looking for: toggle commented/uncommented.