6
autocmd FileType cpp nnoremap <buffer> C ct;
autocmd FileType cpp nnoremap <buffer> D dt;

These two are quite useful, but sometimes there is no ; after the cursor and then D doesn't do anything. And then I have to press 3 keys to delete t$. (!)

How to check if the last action (i.e. Dt;) didn't change anything, and in that case, execute something else (Dt$)?
or
How how to check if there's a semicolon after the cursor and do Dt;, otherwise Dt$?

  • 2
    Actually it only needs 2 characters, you can just do d$ instead of dt$ – f41lurizer Jul 7 '16 at 19:24
  • @f41lurizer or D instead of d$; it's alllmost possible to do with d/;\|$ but the end-of-line matching is a bit weird. "Delete to end of line" does exactly that, "delete to (search end of line)" leaves the last character. – TessellatingHeckler Jul 9 '16 at 17:24
  • @TessellatingHeckler you made me feel stupid... it had been so simple! There's no problem with your suggestion - if you add a x to the mapping after the search, it will delete the last character, too. And, in order not to delete the ;, if matched, you'll use lookahead. I think you should write this as an answer. – Al.G. Jul 9 '16 at 18:02
7

This should do the trick for you:

nnoremap <buffer> <expr> C (getline('.')[getpos('.')[2]:] =~ ';')? "ct;" : "c$"
  • <expr> allows us to do conditional mapping
  • getline('.') =~ ';' searches the current line for a semicolon
  • getpos('.')[2] finds the column that the cursor is on and only searches after it

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.