Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
nerdcommenter for vim may be useful for this see spf13.com/post/vim-plugins-nerd-commenter – harish.venkat Jan 23 '12 at 14:36
up vote 5 down vote accepted

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)

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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