How do I toggle the case of a character in Vim?
Answer
~
Explanation
The ~ command toggles the case of the character under the cursor — uppercase becomes lowercase and vice versa — then advances the cursor one position to the right. It is a quick and simple way to fix capitalization without deleting or retyping.
How it works
~toggles the case of the single character under the cursor- The cursor moves one position to the right after each toggle
- If you hold
~or use a count like5~, it toggles multiple characters in sequence
Example
Given the text with the cursor on the h:
hello World
Pressing ~ five times results in:
HELLO World
Each character's case is flipped individually as the cursor advances.
Using with motions
By default, ~ works on a single character. If you enable tildeop, it works like an operator and can be combined with motions:
:set tildeop
With tildeop enabled:
~wtoggles the case of the current word~$toggles the case to the end of the line~iwtoggles the case of the inner word
Tips
- Use
g~iwto toggle the case of an entire word without enablingtildeop - Use
g~g~org~~to toggle the case of the entire current line - Use
gUiwto force a word to UPPERCASE - Use
guiwto force a word to lowercase - In visual mode, select text and press
~to toggle the case of the entire selection - Use
Uin visual mode to uppercase the selection, oruto lowercase it - The
~command is especially handy for fixing accidental caps lock typing — select the affected text withvand press~