Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing parts of CamelCase words in vim

Using vim, I find cw very handy for changing an entire word. Vim's separation of motion commands and action verbs makes for very powerful combinations. I just now had to change DefaultHandler to ContentHandler. I naturally thought of it as "change up to the next uppercase letter", but I couldn't find a motion command that moved from one uppercase letter to the next.

In this case, I could have used ctH, but is there a way to change (or delete, etc) the first part of a CamelCase word regardless of which uppercase letter comes next?

like image 212
Ned Batchelder Avatar asked Dec 28 '10 13:12

Ned Batchelder


2 Answers

Vim doesn't provides a CamelCase word text object by default, so we'll have to create it by ourselves. The good new is that we don't need to reinvent the wheel since a plugin already exists and we can use it as a base: camelCaseMotion

This script defines motions ,w, ,b and ,e (similar to w, b, e), which do not move word-wise (forward/backward), but Camel-wise; i.e. to word boundaries and uppercase letters. The problem is that it doesn't define a text object similar to iw to select an entire word. So let's create it:

To be complete, a text object need two definitions: one for the visual mode and another one for the operator pending mode. Here are our definitions (to add to the .vimrc):

vmap ,i <Esc>l,bv,e
omap ,i :normal v,i<CR>

As you can see we make a use of the ,b and ,e motions defined by the plugin.

The first definition allow to type ,i when we are in visual mode and it will select the current "inner camelCase word". (The l motion is a workaround to always get the word the cursor is on. Otherwise we get the previous one when the cursor is on the first letter of a word)

The second definition uses the first one to let operators like d or c work with ,i

After we installed the plugin and added the definitions to our .vimrc we can do what you wanted. For example if I take this example:

DefaultHandlerWord

If my cursor is on the letter n of Handler I can use:

  • ,e to go to the last letter of Handler
  • ,b to go to the first letter of Handler
  • ,w to go to the first letter of Word
  • d,i to delete Handler and get only DefaultWord
  • c,i to delete Hanlder and get a chance to replace it by another word
like image 181
statox Avatar answered Oct 19 '22 03:10

statox


I just had the same question, and resolved it with this .vimrc mapping:

nmap W /[A-Z]<CR>

Of course you can include numbers in the range if you want but instead of regular words via w, you can now "search forward for next capital letter" with W. You many want to turn off highlight search in this case though.

like image 1
John Ko Avatar answered Oct 19 '22 02:10

John Ko