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?

1 Answer 1


You can use something like that:

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

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

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>
  • 1
    Example of expression mapping: nnoremap <expr> <leader>d ':keeppatterns s/' . (match(getline('.'), "die();$") == -1 ? '$/ die();/' : ' die();$/') . "\<cr>" Commented Aug 18, 2016 at 19:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.