sponsor Vim development Vim logo Vim Book Ad

intermediate Tip #617: Fun with case twiddling

 tip karma   Rating 131/39, Viewed by 5702 

Read and edit this tip on the Vim tip wiki. The wiki may have a more recent version of this tip.

created:   December 10, 2003 23:01      complexity:   intermediate
author:   Tofer Chagnon      as of Vim:   5.7

Someone came on #vim asking about "sentence case", meaning Capitalization Of Every Word.

I came up with some bad solutions before learning this:


This inspired me to come up with a silly script for rotating between ALL CAPS, all lower, and Sentence Case.
MiXed Case is set to UPPER.

Then I mapped it (in visual mode) to ~, thus breaking the wonderful tilde :)

Here's the script:

fun! TwiddleCase(str)
if a:str == toupper(a:str)
let ans = tolower(a:str)
elseif a:str == tolower(a:str)
let ans = substitute(a:str,"\\(^\\|\\s\\)\\([a-z]\\)","\\1\\U\\2","g")
let ans = toupper(a:str)
return ans

And the mapping:

vmap ~ x:call setreg('"', TwiddleCase(getreg('"')))^MP

 rate this tip  Life Changing Helpful Unfulfilling 

<< Have Vim check automatically if the file has changed externally | how to make and submit a patch >>

Additional Notes

Anonymous, December 10, 2003 23:02
Sorry about the indentation, I won't try to cut-and-paste tabs next time :)
Anonymous, December 10, 2003 23:20
Remind me never to type in a tip at 2AM again.

What I meant to be talking about was "Title Case".  "Sentence Case" is the style I skipped.
Anonymous, December 11, 2003 6:18
s/\<\(.\)/\U\1/g  is easier
george@like_vim_a_lot.com, December 11, 2003 9:32
Found an easier way to upper / lower case the whole file/part file.

do a visual select of the lines you want to do the modifications and
gU ==> uppercase and    gu  ==> lowercase
Anonymous, December 15, 2003 4:31
With a visual selection, just U is sufficient to switch to uppercase and u gives you all lowercase. No need to type a 'g' before the u or U!
mmr@b1n.org, February 5, 2004 11:07
use ~ (tilde) to toggle between upper and lower case.
mttrhll@hotmail.com, June 21, 2004 8:16
here is the easiest way: ggVG (to select all) then hit U or u
Anonymous, October 19, 2004 13:04
omg, ggVG. How cool is that? Thanks!
Anonymous, October 25, 2005 17:48

Converts ALL UPPER or all lower words (or any combination) to Title Case.
\< and \> are start and end of word (you could leave them off in this case, because greedy matching will match the whole word; it's still good defensive regexp coding practice). \( \) wrap each subexpression so it can be recalled later with \1..\9.
Anonymous, November 3, 2005 5:55
Umm yer...

ggVg? you just need V for select line...
so to upper case the current line just do
to lower case the current line do:
If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to the maillist. Help Bram help Uganda.
Sponsored by Web Concept Group Inc. SourceForge.net Logo