1

I have this two lines in my .vimrc:

nnoremap <leader>d :s/$/ die();<CR>
nnoremap <leader>dd :s/ die();/<CR>

For debugging purposes I usually use die();

Maybe, someone knows, how I can toggle die();: Pressing <leader>d would add die(); and the next time I press <leader>d it would remove die(); if die(); is present on current line?

2

You can use something like that:

nnoremap <leader>d :call AddDie()<CR>

function! AddDie()
    if ( match(getline('.'), "die()") == -1 )
        execute ":s/$/ die();/"
    else
        execute ":s/ die();/"
    endif
endfunction

The function will test if the current line contains die(), if it doesnt it will add it at the end of the line otherwise it will remove it.

The mapping calls the function.

Edit: You can also make it a one liner, I don't like it because it is not as readable as a function but that is a good reminder of how to use a conditional structure in a mapping:

nnoremap <leader>d :if ( match(getline('.'), "die()") == -1 ) <bar> execute ":s/$/ die();/" <bar> else <bar> execute ":s/ die();/" <bar> endif<CR>
| improve this answer | |
  • 1
    Example of expression mapping: nnoremap <expr> <leader>d ':keeppatterns s/' . (match(getline('.'), "die();$") == -1 ? '$/ die();/' : ' die();$/') . "\<cr>" – Peter Rincker Aug 18 '16 at 19:00

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.