How do I toggle the case of a character or text object without knowing if it is upper or lower?
Answer
g~{motion}
Explanation
g~ is Vim's toggle case operator — it swaps uppercase to lowercase and lowercase to uppercase for each character in the motion's range. It is complementary to gU (force uppercase) and gu (force lowercase), but useful when you want to flip case without checking the current state first.
Commands
| Command | Action |
|---|---|
g~{motion} |
Toggle case of characters covered by motion |
g~~ or g~g~ |
Toggle case of the entire current line |
g~iw |
Toggle case of the word under cursor |
g~ip |
Toggle case of the current paragraph |
~ (tilde) |
Toggle case of the character under cursor and advance |
gU{motion} |
Force UPPERCASE |
gu{motion} |
Force lowercase |
Example
With the word Hello:
g~iw→hELLOg~iwagain →Hello(back to original)gUiw→HELLO(forced uppercase regardless)guiw→hello(forced lowercase regardless)
In Visual mode
~toggles the case of the selected textUforces the selection to uppercaseuforces the selection to lowercase
Tips
~alone (no motion) is a quick "fix this character" shortcut — it toggles the character under the cursor and moves forwardg~g~on a constant likeMY_CONSTANTproducesmy_constant— toggle case of a whole line- These are dot-repeatable:
.replays the lastg~{motion}on the same motion - In a macro,
g~iwis more robust thangUiw/guiwwhen you don't know the original case of the text