The capital letter of each word in the selection using vim

In vim, I know we can use ~ to use a single char (as mentioned in this question ), but is there a way to capitalize the first letter of each word in a selection with vim?

For example, if I want to change

 hello world from stackoverflow 

to

 hello world from stackoverflow 

How do I do this in vim?

+45
vim regex capitalize replace find
Jul 03 '13 at 5:53 on
source share
5 answers

You can use the following substitution:

 s/\<./\u&/g 
  • \< matches the beginning of a word
  • . matches the first character of a word
  • \u tells Vim to lowercase the next character in the wildcard string (&)
  • & means replacing LHS compliant
+101
Jul 03 '13 at 6:05
source share

:help case says:

 To turn one line into title caps, make every first letter of a word uppercase: > : s/\v<(.)(\w*)/\u\1\L\2/g 

Explanation:

 : # Enter ex command line mode. space # The space after the colon means that there is no # address range ie line,line or % for entire # file. s/pattern/result/g # The overall search and replace command uses # forward slashes. The g means to apply the # change to every thing on the line. If there # g is missing, then change just the first match # is changed. 

This part of the template makes this sense.

 \v # Means to enter very magic mode. < # Find the beginning of a word boundary. (.) # The first () construct is a capture group. # Inside the () a single ., dot, means match any # character. (\w*) # The second () capture group contains \w*. This # means find one or more word caracters. \w* is # shorthand for [a-zA-Z0-9_]. 

The result or part of the replacement has this meaning:

 \u # Means to uppercase the following character. \1 # Each () capture group is assigned a number # from 1 to 9. \1 or back slash one says use what # I captured in the first capture group. \L # Means to lowercase all the following characters. \2 # Use the second capture group 

Result:

 ROPER STATE PARK Roper State Park 

An alternative to a very magical mode:

  : % s/\<\(.\)\(\w*\)/\u\1\L\2/g # Each capture group requires a backslash to enable their meta # character meaning ie "\(\)" verses "()". 
+24
Jul 03 '13 at 6:08
source share

The Wim Tips Wiki has a TwiddleCase mapping that switches the visual selection to lowercase, uppercase, and title.

If you added the TwiddleCase function to your .vimrc , then you simply visually select the desired text and click the tilde symbol ~ to cycle through each case.

+9
Jul 03 '13 at 6:13
source share

Try this regular expression ..

 s/ \w/ \u&/g 
+2
Jul 03 '13 at 12:03
source share

There is also a very useful vim-titlecase plugin for this.

+1
Jan 13 '16 at 20:07
source share



All Articles