Last Updated: February 25, 2016
· scott2b

Managing letter case in vim

The fact that the ~ (lettercase toggle) operation in vi automatically advances to the next letter makes it all too easy to fall into the habit of just repeating the ~ for however many letters you need to toggle.

Unless you are still setting movable type that you store in your California Job Case, you probably shouldn't be doing things one letter at a time.

The g modifier is among the more protean of vi commands. Here's how you can use it to sling letter case with aplomb.

The setup. Use one of these, depending on whether you need to toggle, or explicitly set upper or lower case:

g~  # prepare to toggle case

gU  # prepare to set to upper-case

gu  # prepare to set to lower-case

Once set to go, enter a movement command to modify the case. Here are some examples:

g~w  # toggle case from here through the end of the word. Some will use g~iw to toggle through the inner-word, but I'm not sure of any situation where this matters for case setting.

gUG  # set the whole rest of the file to uppercase

gu$  # set the rest of the line to lowercase

g~^  # toggle everything on the line before this point

Be sure to get a sense of how inclusiveness works on these movements. Backwards movements can seem tricky as they do not operate on the current position, starting rather before that position. E.g. if you are on the last letter of a line and type: gU^, this will leave a dissatisfactory lower-case letter at the end of your line. Similarly, if you were going to toggle the previous word, you should be positioned after the word to issue the g~b, rather than on the last letter of the word.

You can also combine this technique with the f movement for precision casing.

E.g. turn foobarbat into fooBARbat starting on the first letter:


You can also carve out a chunk of your file by line number. E.g.:

gU10G  # uppercase the current line forward through the 10th line

g~2gg  # toggle everything from this line upwards to line 2.

Now, go forth and toggle.

2 Responses
Add your response

Nice tips ! Cheers

over 1 year ago ·

please don't forget: you can apply letter case alternation for text selected in visual mode. All commands ~ , u , U

over 1 year ago ·