At the moment, my commenting and un-commenting is done by two different strokes listed below:

nnoremap <leader>c 0<insert>//<Esc>
nnoremap <leader><leader>c :s;^\s*//<cr>

Which is tedious for me, can someone help me to write a mapping macro that <leader>c stroke removes the comments, if there are any, or add one otherwise.

If the comments/uncomments will all be done by the single lovely <leader>c, that would be a lot less pain in my ......



If you intended to learn Vimrc, read the answer, try those cool solutions. However, here comes the better pain killer: NERD Commenter,

2 Answers 2


You can achieve this kind of effect simply with an expression map and the ternary operator:

nnoremap <expr> <leader>c getline('.')[0:1] == '//'
  \ ? ":s;^\s*//<cr>"
  \ : "0<insert>//<Esc>"

An expression mapping maps your <leader>c to the result of an expression. In this case, it tests if the first two character in the line are // and then carries one of the commands you already wrote.

For more details, see:


If you want to use your own mappings you can try something like this:

nnoremap <expr> <Leader>c IsCommented() ? ":s;^\s*//<cr>" : "0<insert>//<Esc>"

function! IsCommented()
    return substitute(getline('.'), '^\s*', '', '')[0] == "/" && substitute(getline('.'), '^\s*', '', '')[0] == substitute(getline('.'), '^\s*', '', '')[1]

IsCommented() will return true is the first two characters of the current line are / and false otherwise (note that it will ignore the leading whitespaces) and the mapping is conditioned by the result of this command (See :h :map-expression)

However, I would recommend not to reinvent the wheel and use a plugin like NERDCommenter or vim-commentary which are pretty powerful and lightweight.

Edit As @Rich said: tcomment never gets any love.

  • 2
    Man, tcomment never gets any love.
    – Rich
    Jan 19, 2018 at 12:50
  • 1
    Ahah @Rich actually I used NERDCommenter when I started using plugins and never switched, I added commentary to give OP some choice but I never really looked for another commenting plugin.
    – statox
    Jan 19, 2018 at 12:52
  • 1
    I actually haven't gotten around to trying tcomment yet, either ;). Neither NERDCommenter nor vim-commentary can be configured to comment the way I like, though, so I actually still comment/uncomment manually using visual-block mode!
    – Rich
    Jan 19, 2018 at 12:55
  • 1
    Whatever floats your boat as they say :) I actually like a lot the "sexy commenting" (<leader>cs) and the "comment and yank" (<leader>cy) features of NERDCommenter.
    – statox
    Jan 19, 2018 at 12:57
  • @statox You know what!, NERDCommenter is very sexy!
    – SLN
    Jan 19, 2018 at 14:10

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.