Sort thebibliography (LaTeX) alphabetically using Vim

If you write a paper in LaTeX and choose not to use a *.bib file and BibTeX, but in stead simply use thebibliography to manage your citations, the citations will appear in the order that you entered them in thebibliography. There is no automatic way to have the references appear in alphabetical order. But with some (not so simple) Vim commands, the entries can be sorted quickly.

Imagine we have the following entries in thebibliography.

bibitem{ref1}
Carlton N
(2013)
Some Interesting Title
Journal of Something
12:34-45.

bibitem{paper3}
Aaron T
(2013)
Another Interesting Title
Journal of Something Else
23:56-67.

The problem is that we have to sort blocks of code according to the second line of each block. The following worked for me:

First add a ‘unique’ character to the beginning of each non-empty line (here I assumed you copied the references you want to sort to a seperate buffer).

:%s/v^./#&/
#bibitem{ref1}
#Carlton N
#(2013)
#Some Interesting Title
#Journal of Something
#12:34-45.

#bibitem{paper3}
#Aaron T
#(2013)
#Another Interesting Title
#Journal of Something Else
#23:56-67.

Second, restructure the bibitems, so that you have a single bibitem per line. Before executing this statement, make sure you have an empty line as the last line of your document.

:g/^./ .,/^$/-1 join
#bibitem{ref1} #Carlton N #(2013) #Some Interesting Title #Journal of Something #12:34-45.

#bibitem{paper3} #Aaron T #(2013) #Another Interesting Title #Journal of Something Else #23:56-67.

Third, sort every line in the document. The difficulty here is that we want to sort on the autor names. This can be done by defining the right ‘offset’ that should be used for the sorting. The code below tells Vim to sort based on the string that follows the first pound sign after the text “bibitem” (also note the use of “zs”):

:%sort /\bibitem[^#]*#zs/ 
#bibitem{paper3} #Aaron T #(2013) #Another Interesting Title #Journal of Something Else #23:56-67.
#bibitem{ref1} #Carlton N #(2013) #Some Interesting Title #Journal of Something #12:34-45.

Finally, the remaining problem is to put the bibitems back in the original structure. This is easily done by replacing each pound sign with a “newline”:

:%s/#/r/g 
bibitem{paper3} 
Aaron T 
(2013) 
Another Interesting Title 
Journal of Something Else 
23:56-67.

bibitem{ref1} 
Carlton N 
(2013) 
Some Interesting Title 
Journal of Something 
12:34-45.

Done!