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 {} \;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: