HTML indenter written in Python

Using BeautifulSoup

There are a dozen ways to use the BeautifulSoup module and it's prettify function. Here are some examples to get you started.

From the Commandline

$ python -m BeautifulSoup < somefile.html > prettyfile.html

Within VIM (manually)

You don't have to write the file back to disk if you don't want to, but I included the step that would get the identical effect as the commandline example.

$ vi somefile.html
:!python -m BeautifulSoup < %
:w prettyfile.html

Within VIM (define key-mapping)

In ~/.vimrc define:

nmap =h !python -m BeautifulSoup < %<CR>

Then, when you open a file in vim and it needs beautification

$vi somefile.html
=h
:w prettyfile.html

Once again, saving the beautification is optional.

Python Shell

$ python
>>> from BeautifulSoup import BeautifulSoup as parse_html_string
>>> from os import path
>>> uglyfile = path.abspath('somefile.html')
>>> path.isfile(uglyfile)
True
>>> prettyfile = path.abspath(path.join('.', 'prettyfile.html'))
>>> path.exists(prettyfile)
>>> doc = None
>>> with open(uglyfile, 'r') as infile, open(prettyfile, 'w') as outfile:
...     # Assuming very simple case
...     htmldocstr = infile.read()
...     doc = parse_html_string(htmldocstr)
...     outfile.write(doc.prettify())

# That's it; you can manually manipulate the dom too though
>>> scripts = doc.findAll('script')
>>> meta = doc.findAll('meta')
>>> print doc.prettify()
[imagine beautiful html here]

>>> import jsbeautifier
>>> print jsbeautifier.beautify(script.string)
[imagine beautiful script here]
>>> 

you can use the built-in module xml.dom.minidom's toprettyxml function:

>>> from xml.dom import minidom
>>> x = minidom.parseString("<ul><li>Item</li><li>Item\n</li></ul>")
>>> print x.toprettyxml()
<?xml version="1.0" ?>
<ul>
    <li>
        Item
    </li>
    <li>
        Item
    </li>
</ul>

BeautifulSoup has a function called prettify which does this. See this question