Let' say I want to comment and uncomment a line.

I know I can


and then


Now what if I want this as an one-liner?

Basically, if a line starts with // then remove it, else add it.

I want to map this command to one shortcut instead of having two.


1 Answer 1


I'm quite certain this can't be done directly. However, I came up with a function for you. Put this in your ~/.vimrc:

function! Toggle()

(This will change any xxx// you already have at the beginning of a line into //, but I'd imagine this is a rare occurrence). You could call this whenever you want with :call Toggle(), but you will probably find it more convenient to map it to a key/combo. The following will map it to Ctrl+/; of course you can substitute whatever key combo you prefer (ask if you need help mapping to another combo). Put this too in your ~.vimrc:

nnoremap <C-/> :call Toggle()<CR>
vnoremap <C-/> :call Toggle()<CR>
inoremap <C-/> <Esc>:call Toggle()<CR>i

These map Ctrl+/ to the function in normal, visual, and insert mode, respectively. Note that the insert mapping will return you to insert mode but move the cursor to the beginning of the line. If you prefer to remain in normal mode, just drop the i from the end of the inoremap line.

(Updated to deal with white space. Removes // after white space, but always inserts at the beginning of the line)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .