Reformatting a CSS file with Vim

Derek Slager wrote a post (and made a screencast) of how you would clean up an ugly CSS file. I decided to do it in Vim. Here are the steps. No screencast from me, unfortunately.

" Replace all sequences of white spaces with one space
:%s/[ \\t\\n]\\+/ /g

" Go to the end of the command, then forward one character and insert
" a newline
]/lr^M

" Add a newline after every semi-colon
:%s/;/;^M/g

" Add a newline after every opening brace and make put one space
" between it and the preceeding text
:%s/\\([^ ]*\\) *{/\\1 {^M/g

" Add two newlines after every closing brace
:%s/}/}^M^M/g

" Remove 'trailing' spaces in front of the semi-colons
:%s/ *;/;/g

" Make sure there is only one space after a colon
:%s/: */: /g

" Make the text before the colon lowercase
:%s/\\(.\\{-}\\):/\\L\\1:/g

" Remove all trailing spaces at the beginning of lines
:%s/^ \\+//g

" Go to the beginning of the file
gg

" Record a macro to sort the attributes
qa2jV}2k:sort^M}q

" Repeat the macro a few times
20@a

" Indent the whole file
gg=G

Edit: Fixed the backslashes. WordPress sucks.

2 Responses to “Reformatting a CSS file with Vim”

  1. Vincent Says:

    Argh! Stupid WordPress deleted all my backslashes!

  2. Derek Says:

    Hehe, I thought those regexps looked awfully compact. Nice one!

Comments are closed.