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

How do I convert text to title case in Vim using a substitution command?

Answer

:%s/\v(\w+)/\u\L\1/g

Explanation

Vim's substitution engine supports case-modifier sequences in the replacement string, making it possible to convert text to title case in a single command. The \u\L combination is the key: \u capitalizes the very next character, and \L lowercases everything that follows until the end of the matched group or \E. Together they produce true title case — first letter upper, rest lower — regardless of the original casing.

How it works

  • \v — enables "very magic" mode so (...) groups don't need escaping
  • (\w+) — captures each word (sequence of word characters)
  • \u — capitalizes the first character of the captured group
  • \L — lowercases the remainder of the captured group
  • \1 — inserts the captured group with the case modifiers applied
  • g flag — replaces all occurrences across the line

Example

Given the text:

hello WORLD foo BAR

After running :%s/\v(\w+)/\u\L\1/g:

Hello World Foo Bar

Tips

  • Limit scope to a visual selection: :'<,'>s/\v(\w+)/\u\L\1/g
  • Without \L, \u\1 only capitalizes the first letter and leaves the rest unchanged
  • Use \U\1 to UPPERCASE the entire word, or \L\1 to lowercase the entire word
  • The \E marker explicitly ends a \U or \L span: \u\L\1\E is equivalent when there is only one group

Next

How do I open the directory containing the current file in netrw from within Vim?