Vim Tips Wiki
Advertisement

Proposed tip Please edit this page to improve it, or add your comments below (do not use the discussion page).

Please use new tips to discuss whether this page should be a permanent tip, or whether it should be merged to an existing tip.
created July 25, 2010 · complexity basic · version 7.0

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.

Change under_scores to CamelCase

" Change selected text from name_like_this to NameLikeThis.
vnoremap ,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.

Change CamelCase to under_scores

" Change selected text from NameLikeThis to name_like_this.
vnoremap ,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

 TO DO 

  • Need to fix some bugs, I think.
  • The :s/// will act on each whole line in the selected area. Perhaps fix with \%V before and after pattern.
  • The patterns need to use \C to make them independent of 'ignorecase'.
  • Probably should add e flag (:s///ge) so no error if not found.
  • Can the ,u mapping use a pattern like \C\l\(\u\) so it does not convert an all uppercase name?
  • The gUl and gul code (which could be vU or vu) seems to assume something that I can't quite work out at the moment.
  • Should this be merged with the 'see also' tip?

JohnBeckett aka JohnBot 08:21, September 20, 2010 (UTC)

Advertisement