Vim macro to Camel_Case_With_Underscores

142 Views Asked by At

I want a quick macro to allow me to convert text like qty_on_hand to Qty_On_Hand. Words that have no underscores should be capitalised so description would become Description. Case in the source text is not going to be consistent, so it might be QTY_on_Hand -> Qty_On_Hand.

Any ideas?

1

There are 1 best solutions below

2
On

Try the following:

:let @t="caw\<C-r>=join(map(split(@\", '_', 1), 'toupper(v:val[:0]).tolower(v:val[1:])'), '_')\n\e"

Then when you type @t in normal mode you will get current word replaced as you requested. If you want to just blindly replace everything, then use

:%s/\<\w\+\>/\=join(map(split(submatch(0), "_", 1), "toupper(v:val[:0]).tolower(v:val[1:])"), "_")/g

Add c after g flag if you want vim to ask you about each replacement.

Second solution assumes that there are no non-ASCII identifiers in your source code.