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

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

  • gUgU or gUU operates on the current line (doubling the operator)
  • These compose with Vim's grammar: gU is an operator like d, c, or y
  • Use gUit to uppercase inside an HTML tag, gUi" inside quotes
  • In visual mode, U uppercases and u lowercases the selection
  • For single characters, ~ toggles case and advances the cursor
  • The substitute-case-conversion trick (\u, \U, \l, \L) handles case in :s commands

Next

How do I run the same command across all windows, buffers, or tabs?