I want to make block commenting easy. To comment out a range of lines, what I can do is something like: :17,21s/^/# This will comment lines 17 to 21 in Python. But I don't want to write the whole string search and replacement pattern all the time.
Initially I thought of making a parameterized mapping for this, where I could pass the line numbers as parameters to string search and replacement map but then realised that mappings cannot have parameters.
Then I got this function which will comment a range and the comment character can be passed to it as well (like # in Python and // in JavaScript):
command! -range -nargs=? Co call CommentThis(<line1>, <line2>, <q-args>)
function! CommentThis(l1, l2, lead)
let l:lead = a:lead == '' ? '#' : a:lead
exe printf('%i,%is+^+%s', a:l1, a:l2, l:lead)
endf
Now doing something like :17,21Co will achieve the task and I can do :17,21Co// (for adding // instead of default #)
My question is: How can I modify this function so as to make it work as a comment toggle? Or add a different command line to it so that I can use command 'Co' for commenting and 'Cu' to uncomment? A search and replace pattern to uncomment a python comment would be :17,21s/^#/.
PS:
The reason I don't want to use NERD Commentor is that it doesn't support ranges, it just supports count, where I have to either take the cursor to the line I want to comment or select it.
Another plugin I found is Commentary VIM but its command :17,21Commentary is too long for me.
:Commentaryto:Colike so:17,21Co. – romainl Oct 27 '15 at 11:11:17,21call NERDComment('n', 'Toggle')– Sato Katsura Oct 27 '15 at 11:26commandfor it. The function does the heavy lifting for you. – Sato Katsura Oct 27 '15 at 11:28command! -range Co <line1>,<line2>call NERDComment('n', 'Toggle')– Sato Katsura Oct 27 '15 at 12:08:17,21Co<CR>. – romainl Oct 27 '15 at 12:40