1

I have the following within my .vimrc:

" toggle comments
noremap <C-m> :<Left><Left><Left><Left><Left>exe "<Right><Right><Right><C-Right><Right>normal! I".g:commentType<CR>
autocmd BufReadPost *.php let g:commentType='//'      "Perl files
autocmd BufReadPost *.styl let g:commentType='//' "C files
autocmd BufReadPost *.js let g:commentType='//' "C files

I want it so if I do 'ctrl+m' on a line that is already commented, it'll uncomment it, and if the line doesn't have comments, it'll add it

So

blah blah text

becomes

// blah blah text

and if I do it again

// blah blah text

becomes

blah blah text

How may i do this?

  • 1
    Why do you have so many <left> and <right>? This works just fine for me: noremap <C-m> :exe "normal! I".g:commentType<CR> – DJMcMayhem Jun 9 '16 at 19:18
7

if you're willing to use a plugin, there are many commenting plugins out there. Some of the most popular examples are:

All of these have mappings for toggling comments. You can remap <C-m> to this command. For example, if you go with tpope/commentary, you could do:

nmap <C-m> gcc

which toggles a line.

If you don't want to install a plugin, you'll need to write a vimscript that detects if a line starts with a comment, and then adds or removes it accordingly. This is definitely possible, but I don't know how to do it myself, so I'll let someone else answer that if they want to.

  • I've tried nnoremap <C-m> gcc with tpop vim commentary, but it doesn't work. Any idea why? gcc works tho. – ditto Jun 9 '16 at 19:39
  • 3
    @ditto Whoops, my bad. I say nnoremap by default. In this case you want nmap since gcc itself is a mapping. (see here) – DJMcMayhem Jun 9 '16 at 19:41
  • Awesome, have it working now. Tar. Am I able to highlight several rows and toggle them in 1 go? I've tried a few times and can't seem to get it working. – ditto Jun 9 '16 at 19:48
  • 2
    @ditto With <C-m>? Surround vim's mapping for visual mode is gc so if you want that to work you'll have to do xmap <C-m> gc. – DJMcMayhem Jun 9 '16 at 19:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.