How do I toggle, uppercase, or lowercase text using motion commands in Vim?
Answer
g~~
Explanation
Vim has three case-change operators that work like any other operator — you can combine them with motions, text objects, or double them to act on the whole line. This lets you perform case transformations without entering visual mode.
How it works
g~{motion}— toggle case (upper↔lower) over a motiongU{motion}— convert to uppercase over a motiongu{motion}— convert to lowercase over a motion- Doubling the command applies to the entire current line:
g~~,gUU,guu
Example
Given:
Hello World
| Command | Result |
|---|---|
g~~ |
hELLO wORLD |
gUU |
HELLO WORLD |
guu |
hello world |
gUiw (cursor on Hello) |
HELLO World |
g~ap |
toggles case of entire paragraph |
Tips
- Combine with any text object:
gUi"uppercases the text inside quotes,gu2wlowercases the next two words - In visual mode,
U,u, and~do the same thing asgU,gu, andg~on the selection - Use with
iw,is,iptext objects for word, sentence, or paragraph transforms gUgUis a (less common) equivalent togUU