Changing Words

3.5
(71)

We’ve written before about how Vim commands can be combined with motions or text objects to achieve powerful editing combinations. In a nutshell:

<number of times> + <command> + <text object or motion>

With that in mind, there are 3 different ways you can change words in Vim:

  • cw – Change from cursor to the end of the word.
  • caw – Change around the word, including trailing whitespace.
  • ciw – Change inside the word, excluding trailing whitespace.

Let’s explain how each of these differ. Watch the brief screencast:

As you can see, cw removes everything including the character under the cursor up to the next non-alphanumeric character. Then it drops you into insert mode so you can begin typing a replacement. This works by combining w, a motion, with the command c for change.

Next is ciw which removes the current word up to the whitespace on either side and again, leaves you in insert mode. This works differently. Instead of combining a command with a motion, we’re combining with a text object: iw for inside word.

Lastly is caw. This differs slightly from ciw in that it removes all the trailing whitespace as well. Again, here we are combining the c command with a text object, aw for a word (or “around word”).

When would you use these? Well, cw I use quite frequently for just about any text editing or programming, especially when combined with w to move between words. And ciw is extremely useful for building up commands that can be repeated with with the . character.

In a recent project I needed to change several instances of various class names all to a single class name. Watch the demo below. First, I search for pattern contained in all the classes I’m trying to swap using /. My cursor lands in the middle of the word — a perfect time to use ciw to change it. Now I press n to go to the next match and skip it. Then press n to go to the next match and repeat my ciw action with a dot.

How useful was this tip?

Average rating 3.5 / 5. Vote count: 71

No votes so far! Be the first to rate this tip.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Written by

Colin Bartlett

70 Posts

Vim enthusiast and software developer for more than 20 years.
View all posts

Leave a reply

Your email address will not be published. Required fields are marked *