Format and Indent HTML in Vim

Sudar picture Sudar · Apr 3, 2012 · Viewed 16.4k times · Source

I currently have a huge HTML file which doesn't have line breaks and just appears in a single line.

I want to format it in vim (macvim in particular). I tried the following options, but none of them has worked for me.

  • Selected the text and pressed = . This will only auto intend the code. But since the entire code is present in one line, it doesn't do anything
  • I tried this Plugin http://www.vim.org/scripts/script.php?script_id=3613 This kind of works but will insert linebreaks only for the current tag. I want the entire file to be formatted

Is there a way to do this either using a Plugin or otherwise?

Thanks!

Answer

Chris Morgan picture Chris Morgan · Apr 3, 2012

One way to start it is to split all tags onto their own lines.

:s/<[^>]*>/\r&\r/g
:g/^$/d

If you have floating < or > symbols (e.g. invalid HTML, JavaScript comparison operators, CSS direct descendant selector part), this won't work properly and you could switch to something like just doing end tags - <\/[^>]*>. It provides a solid start, anyway.

Demonstration:

With a idealised document like this,

<!DOCTYPE html><html><head><title>hello</title></head><body>world</body></html>

This produces this:

<!DOCTYPE html>
<html>
<head>
<title>
hello
</title>
</head>
<body>
world
</body>
</html>

Then, = will produce what you want:

<!DOCTYPE html>
<html>
    <head>
        <title>
            hello
        </title>
    </head>
    <body>
        world
    </body>
</html>