Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

I know I can

:s!^!//!

and then

:s!^//!!

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
2  
nerdcommenter for vim may be useful for this see spf13.com/post/vim-plugins-nerd-commenter –  harish.venkat Jan 23 '12 at 14:36
add comment

1 Answer 1

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()
    s!^\(\s*/\?[^/\s]/\?\)!xxx//\1!e
    s!^\(\s*\)//!\1!e
    s!^xxx//!//!e
endfunc

(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
add comment

Your Answer

 
discard

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.