10 December 2025

in vim, how to capitalise every word?

To capitalize the first letter of every word in a line or selection in Vim, you can utilize a combination of commands.
For a single line:
  • Place the cursor at the beginning of the line.
  • Enter the following command in normal mode:
Code
    :s/\<\(\w\)\(\w*\)\>/\U\1\L\2/g
  • : enters command-line mode.
  • s/ initiates a substitute command.
  • \<\(\w\)\(\w*\)\> matches a whole word:
    • \< matches the beginning of a word.
    • \(\w\) captures the first word character into group 1.
    • \(\w*\) captures the remaining word characters into group 2.
    • \> matches the end of a word.
  • \U\1\L\2 replaces the matched word:
    • \U\1 converts the first captured character (group 1) to uppercase.
    • \L\2 converts the remaining captured characters (group 2) to lowercase.
  • /g ensures all occurrences on the line are processed.
For a visual selection (multiple lines or a block):
  • Enter visual mode (e.g., by pressing vV, or Ctrl-v).
  • Select the desired text.
  • Enter the following command:
Code
    :'<,'>s/\<\(\w\)\(\w*\)\>/\U\1\L\2/g
  • '<,'> automatically populates the range for the visual selection.
  • The rest of the command is identical to the single-line substitution.
For the entire file:
  • Enter the following command in normal mode:
Code
    :%s/\<\(\w\)\(\w*\)\>/\U\1\L\2/g
  • % specifies the entire file as the range for the substitution.
  • The rest of the command is identical to the single-line substitution.

No comments:

Post a Comment