0

I think a nice way to do the comments is key mapping. I need to comment/un-comment c style code, here is my mapping

nnoremap <leader>c 0<insert>//<Esc>                                                                  
nnoremap <leader>' 0xx

the second one is for un-commenting, it just moves the cursor to the beginning of the line and delete 2 times.

I wonder is there a possibility to write an if statements here, I mean moving the cursor in the beginning of the line and check if the first two characters is backslash, if yes, then delete twice, if not, do nothing

Thanks

1

I wonder is there a possibility to write an if statements here, I mean moving the cursor in the beginning of the line and check if the first two characters is backslash, if yes, then delete twice, if not, do nothing

That's certainly possible. However, it's much simpler if done with a simple regex:

nnoremap <leader>' :s/^\/\/<cr>

Thankfully, we can choose what separator to use, so we won't need to escape the slashes if we change separators:

nnoremap <leader>' :s;^//<cr>

As a side note, if you run this in a macro, and you run it on a line without a comment at the beginning of it, it will stop the macro from running. If you don't want this to happen, add the /e flag, e.g.:

nnoremap <leader>' :s;^//;;e<cr>

Additionally, if you would like to also uncomment lines where the comment after some whitespace, for example:

//Remove these comments
    //And these ones too

Then I would do:

nnoremap <leader>' :s;^\s*//<cr>

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.