Vim Tips Wiki
Advertisement

Sometimes the coding style is CamelCase, other times it's under_scores. Here is some Vim code to switch between them. The following mappings change the visually selected text.

under_scores to CamelCase

" Change name_with_underscores to NamesInCameCase for visually selected text.
" mnemonic *c*amelCase
vmap ,c :s/_\([a-z]\)/\u\1/g<CR>gUl

To use this you would go into Visual Mode (press v) then select the word (iw, which stands for inner word) then type ,c in visual mode.

This changes this_is_my_func to ThisIsMyFunc.

If you want the style to be thisIsMyFunc you can remove the gUl which changes the first character to Uppercase.

How it works

It substitutes the characters so that _a becomes A. The \u\1 uppercases the match. The <CR> hits the enter key for you and the cursor ends up at the beginning of the selection. We use gUl to Uppercase the character under the cursor.

Some might have used the ~ (tilde) to uppercase it, but if it was already uppercase it would have made it lowercase. Also, the tilde moves the cursor to the right which is not what we want.

CamelCase to under_scores

" Change CamelCase to name_with_underscore for visually selected text.
" mnemonic *u*nderscores.
vmap ,u :s/\<\@!\([A-Z]\)/\_\l\1/g<CR>gul

This changes ThisIsMyFunc to this_is_my_func.

How it works

It substitutes the characters so that A becomes _a. The \_ put in the underscore the \l\1 (which difficult to see that the first is a lowercase L, the second is the number 1) forces the matched character to be lowercase.

The \<\@! tells substitute to ignore the first match. The gul changes the character under the cursor to be lower-case.

See also

References

Comments

Advertisement