How do I change the case of text using operators and motions?
Answer
gU{motion} / gu{motion} / g~{motion}
Explanation
Vim has three case operators that work with any motion or text object: gU for uppercase, gu for lowercase, and g~ for toggle case. Unlike ~ which works on single characters, these operators scale to words, lines, paragraphs, or any text object.
The case operators
| Operator | Effect |
|---|---|
gU |
UPPERCASE |
gu |
lowercase |
g~ |
tOGGLE cASE |
Common patterns
gUiw " UPPERCASE inner word
guiw " lowercase inner word
g~iw " Toggle case of inner word
gUU " UPPERCASE entire line
guu " lowercase entire line
g~~ " Toggle case of entire line
gUip " UPPERCASE entire paragraph
gui{ " lowercase inside braces
gU$ " UPPERCASE to end of line
gu'a " lowercase from cursor to mark a
Example
Convert a constant name:
Before: const maxRetryCount = 5
gUiw on 'maxRetryCount': const MAXRETRYCOUNT = 5
Convert an entire SQL keyword:
Before: select * from users where id = 1
gUU: SELECT * FROM USERS WHERE ID = 1
Tips
gUgUorgUUoperates on the current line (doubling the operator)- These compose with Vim's grammar:
gUis an operator liked,c, ory - Use
gUitto uppercase inside an HTML tag,gUi"inside quotes - In visual mode,
Uuppercases andulowercases the selection - For single characters,
~toggles case and advances the cursor - The
substitute-case-conversiontrick (\u,\U,\l,\L) handles case in:scommands