Chasing the casing in Vim
A lot of programming is really just taking data in one form and turning it into another. Imports and exports. Within different contexts, different conventions apply. Within Laravel, database columns are usually snake_case
, yet within PHP most variables are camelCased
. Within HTML and CSS, things are usually kebab-cased
, until you find a React component, which are usually PascalCased
.
Every once in a while I end up copying names from one source and having to turn them into another case. With the Vim language of editing, turning a_cased_string
into aCasedString
usually involves me typing f_
to jump my cursor to the next underscore, and then x~
to delete that underscore and turn the next character into it's uppercase variant. I then have to do that for however many times there are underscores in my target string. (Subsequent jumps to underscores can be made with ;
though.)
The conversion back from aCasedString
to a_cased_string
is always a bit more bothersome, because you need to insert a lot of underscores. I usually do it with a second pass: use fC
to jump to the first insert point, then use i_
and escape to insert the underscore, then jump with fS
, and use the .
to repeat my last insert. Then when I am done with the string, I use guiw
to change the case of the 'inner word' to lowercase (gu
).
The nice thing about that approach is that it feels efficient: I am using all kinds of obscure Vim keystrokes to get my work done and I feel like a wizard. I never touch my mouse! The bad thing about the approach is that it is still a lot of work, especially in longer strings or with many occurrences. Today I thought: there must be a better way for this. Maybe there is even a plugin?
And yes there is, and of course it's by Tim Pope. It's called Abolish and it's main purpose seems to be auto-replacement (which I don't want to use) but it also adds a very handy :Subvert
command, and precisely the mappings I wanted to have.
If I now every have to change any token to camelCase
, I can just jump my cursor to it and type crc
. Do I need snake_case
? Just crs
and that's it, no matter how long it is. And of course it works with the .
command as well. Why have I allowed myself to do all the nonsense I just described above? Just install the tpope-plugin and you're done.