Vim: Capitalize every first character of every word in a sentence

Today I got a request from a publisher to make all my references ‘title style’, meaning that all principal words in the title of the articles should be upper case. With the powerful editor Vim, this boring task can be easily automated. Below you can find a way to accomplish this using regular expressions. In order to make the final code easier to digest, I provide a step-by-step guide.


Basic vim find and replace:

:s/foo/bar/g


To avoid that the above statement would also change ‘foobar’ into ‘barbar’:

:s/\<foo\>/bar/g

< :: beginning of word
>
:: end of word


or, equivalent (with \v you can avoid escaping special characters all the time):

:s/\v<foo>/bar/g


Capitalize the first letter of the first word of a line:

:s/\v^\a/\u&/g

^      :: beginning of line
\a
   :: any alphabetic character
\u
   :: make next character uppercase
&
    :: matched pattern


Capitalize every first letter of every word of a line:

:s/\v<\a/\u&/g


Capitalize the first letter of any word of a line that appears in list (‘in’,’ik’):

:s/\v<(in>|ik>)/\u&/g

(in>|ik>) :: matches only words that end on ‘in’ or ‘ik’


Capitalize the first letter of any word of a line that does not appear in list (‘in’,’ik’):

:s/\v<(in>|ik>)@!\a/\u&/g

(in>|ik>)@!    :: machtes only words that do not end on ‘in’ or ‘ik’
<(in>|ik>)@!\a
:: matches first character of any word that is not in the list (‘in’,’ik’):


Capitalize every first letter of every word of a line, but not the words in the list (‘in’,’ik’) except if (‘in’,’ik’) is first word of line:

:s/\v^\a|<(in>|ik>)@!\a/\u&/g


Capitalize every first letter of every word of a line, but not the words in the list (‘in’,’ik’) except if (‘in’,’ik’) is first word of line or if (‘in’,’ik’) is the first word following a colon:

:s/\v^\a|\:\s\a|<(in>|ik>)@!\a/\U&/g

\:\s\a :: patter is ‘colon followed by a space followed by any alphabetical character’
\U          :: since the character to capitalize appears at the end, uppercase entire match


The expression that I used to capitalize the titles of the journal articles in my bibliography is:

:s/\v^\a|\:\s\a|<%(in>|the>|at>|with>|a>|and>|for>|of>|on>|from>|by>)@!\a/\U&/g
Advertenties

Geef een reactie

Vul je gegevens in of klik op een icoon om in te loggen.

WordPress.com logo

Je reageert onder je WordPress.com account. Log uit / Bijwerken )

Twitter-afbeelding

Je reageert onder je Twitter account. Log uit / Bijwerken )

Facebook foto

Je reageert onder je Facebook account. Log uit / Bijwerken )

Google+ photo

Je reageert onder je Google+ account. Log uit / Bijwerken )

Verbinden met %s