1

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?

Community
  • 1
  • 1
meduz
  • 3,903
  • 1
  • 28
  • 40
  • Possible duplicate of [What's a quick way to comment/uncomment lines in Vim?](https://stackoverflow.com/questions/1676632/whats-a-quick-way-to-comment-uncomment-lines-in-vim) – Big McLargeHuge Mar 30 '18 at 15:57

2 Answers2

5

There's also NERD Commenter from Scrooloose, the maker of NERD Tree. It seems to more extensive than vim-commentary.

The only map I use though is <leader>c<space> (,c for my config), toggling a comment.

timss
  • 9,982
  • 4
  • 34
  • 56
4

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.

meduz
  • 3,903
  • 1
  • 28
  • 40
Marco
  • 849
  • 1
  • 7
  • 21
  • 1
    An excellent plugin. The default mapping is `gcc` and it does exactly what you're looking for: toggle commented/uncommented. – glts May 25 '13 at 12:59