Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim inline remap to check first character

I am trying to do a comment remap in Vim with an inline if to check if it's already commented or not. This is what I have already and of course it's not working ha ha:

imap <c-c> <Esc>^:if getline(".")[col(".")-1] == '/' i<Delete><Delete> else i// endif

What I want to do is check the first character if it's a / or not. If it's a / then delete the first two characters on that line, if it's not a / then add two // in front of the line.

What I had originally was this:

imap <c-c> <Esc>^i//

And that worked perfectly, but what I want is to be able to comment/uncomment at a whim.

like image 259
jfreak53 Avatar asked Mar 04 '26 06:03

jfreak53


1 Answers

I completely agree with @Peter Rincker's answer warning against doing this in insert mode, and pointing you to fully-featured plugins.

However, I couldn't resist writing this function to do precisely what you ask for. I find it easier to deal with this kind of mapping with functions. As an added bonus, it returns you to insert mode in the same position on the line as you started (which has been shifted by inserting or deleting the characters).

function! ToggleComment()
    let pos=getpos(".")
    let win=winsaveview()
    if getline(".") =~ '\s*\/\/'
        normal! ^2x
        let pos[2]-=1
    else 
        normal! ^i//
        let pos[2]+=3
    endif
    call winrestview(win)
    call setpos(".",pos)
    startinsert
endfunction   

inoremap <c-c> <Esc>:call ToggleComment()<CR>

Notice the modifications to pos to ensure the cursor is returned to the correct column. The command startinsert is useful in this type of function to return to insert mode. It is always safer to use noremap for mappings, unless there is a very good reason not to.

This seems to work well, but it is not very Vim-like, and you might find other plugins more flexible in the long run.

like image 88
Prince Goulash Avatar answered Mar 07 '26 04:03

Prince Goulash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!