Search code examples
vim

How to replace a search word in VIM using "c"?


I have strings in the following way in VIM:

SetDynamicFrictionDoesNothingIfProvidedArgumentIsInvalid
SetDynamicFrictionCreatesCollidableIfItDoesNotExist

Without doing a search and replace (i.e :%s/DynamicFriction/Restitution), I want to be able to replace the word "DynamicFriction" with "Restitution." I really like using the c command in VIM to do remove and enter edit mode in one command because I can combine this with search and easily go through lines and decide what I want to update.

How can I achieve this? I tried the following but it did not work:

Note that "+" means combining in this context, not a VIM thing

c + /DynamicFriction/e

But this goes to the end of the whole word and basically removes the entire line. How can I make it so that, only the "DynamicFriction" is removed.


Solution

    1. c is an operator.
    2. An operator "operates" on a motion.

    DynamicFriction being pretty much a random string found within another, larger, random string, you can't really expect it to be covered by an existing built-in motion.

    Moreover…

    • c/pattern<CR> would change all the text from the cursor to the next match,
    • c/pattern/e<CR> would do the same but including the match.

    so you can't expect that approach yield anything useful either.

    If you really don't want to use a substitution for this—which is a shame because it is by far the best method—you can use :help gn in two steps.

    1. Search for your pattern with:

      /DynamicFriction<CR>
      
    2. Change the current match (or next match if the cursor is not on a match) with:

      cgnRestitution<Esc>
      

    Note that cgn is an interesting operator+motion combo that a) uses a very special motion: "jump to next match unless already on a match and visually select it"), and b) is repeatable with .. This makes that kind of things possible:

    /DynamicFriction<CR>    " search for pattern
    cgnRestitution<Esc>     " change match
    .                       " repeat change
    .                       " etc.
    

    cgn