Monthly Archives: July 2011

Auto format a document using vim

To auto indent the content of a file:

gg=G

The above command means perform formatting from the 1st to the last line.

=

is the command to perform formatting,

gg G

says where to start and where to end.

G=gg

does the same thing as well.

The indentation is performed based on the file type. If the file type is unknown, set it with the following command first:

:set filetype=xml

The above example will set the file type as XML. If you execute the formatting command stated earlier, the content will be formatted as a XML document.

If you have many XML files that needs to be formatted, you may use vim to do it for you.

First, you need to create a simple script, let’s name it format.vim with the following content:

gg=G :wq!

Then you run the following command:

find . -name "*.xml" -exec vim -s format.vim {} \;