vimtricks.wiki Concise Vim tricks, one at a time.

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~iwhELLO
  • g~iw again → Hello (back to original)
  • gUiwHELLO (forced uppercase regardless)
  • guiwhello (forced lowercase regardless)

In Visual mode

  • ~ toggles the case of the selected text
  • U forces the selection to uppercase
  • u forces the selection to lowercase

Tips

  • ~ alone (no motion) is a quick "fix this character" shortcut — it toggles the character under the cursor and moves forward
  • g~g~ on a constant like MY_CONSTANT produces my_constant — toggle case of a whole line
  • These are dot-repeatable: . replays the last g~{motion} on the same motion
  • In a macro, g~iw is more robust than gUiw/guiw when you don't know the original case of the text

Next

How do I run a search and replace only within a visually selected region?