Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change last word on line in Vim

Tags:

vim

I'm using Vim to edit C code, and I enjoy using c<movement> to quickly change parts of my file. In particular, I find things like c2W useful to "change two space-delimited words."

But there's one use case that has escaped me: when my cursor is at the last character of a word, the command cb, "change back a word," does not delete the last character of the word I want to edit. This makes sense, as the cursor was technically before that last character, but it's not what I want.

Here's what happens, with the cursor indicated by |:

Start with:

This is just a typ|ical series of words

I would like to change "typical" to "different." I press e:

This is just a typica|l series of words

And then cb:

This is just a |l series of words

Now there's a hanging l (a lowercase L, to be clear) left over! That's not what I wanted.

The more astute of you have already noticed that I could in this example simply have used the combination bcw, which would put my cursor before the beginning of the word, and then changed through the whole word. True! But what if I had wanted to change "words" to "strings?"

Start with:

This is just a typ|ical series of words

I would like to change "words" to "strings." I press $:

This is just a typical series of word|s

Same problem! Pressing cb will leave a hanging "s" (although in this example that would be fine, since "strings" ends in "s" anyways). Of course, I could press bcw, but that's one additional key, and thus unacceptable.

Do I just have to live with this incredible hardship?

like image 651
ravron Avatar asked Jun 17 '13 18:06

ravron


People also ask

How do I move the last word of a line in Vim?

I usually type the command db to remove one word backwards in Vim. Doing this at the end of a line without whitespace leaves the last character of the word since the cursor starts removing from the second last character.

How do I change a whole line in Vim?

Use c$ or just C to quickly change from the cursor to the end of a line, cc to change an entire line, or cis for a sentence. The standard change word command requires you to type cw , then a new word, then press Escape.


2 Answers

You can use the iw ("inner word") motion to select the whole word the cursor is currently positioned in. So combined with the c ("change") command, that'd leave you with ciw.

That would also apply to your first example: instead of first moving forward to the end of word with e and then using cb to change the backwards word, you could also use ciw from your current position.

like image 79
earl Avatar answered Oct 24 '22 20:10

earl


Try one of these guys: caw or ciw.

This way you can replace word while your cursor is in the middle of the word.

like image 37
Ruslan Osipov Avatar answered Oct 24 '22 21:10

Ruslan Osipov