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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.