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 appliedgflag — 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\1only capitalizes the first letter and leaves the rest unchanged - Use
\U\1to UPPERCASE the entire word, or\L\1to lowercase the entire word - The
\Emarker explicitly ends a\Uor\Lspan:\u\L\1\Eis equivalent when there is only one group