Sudar
Sudar

Reputation: 19982

Format and Indent HTML in Vim

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.

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

Thanks!

Upvotes: 29

Views: 24855

Answers (4)

bekkou68
bekkou68

Reputation: 842

Thank you. I solved HTML-formatting problem with Chris Morgan's answer like below:

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

And I'd like to define Vim mapping for doing the above procedure.

The Vim mapping is like below:

nnoremap <Leader>a :<C-u>s/<[^>]*>/\r&\r/g<CR>:<C-u>g/^$/d<CR>gg=G

Then, by typing a leader key and A key, HTML-formatting finishes.

Upvotes: 0

chtenb
chtenb

Reputation: 16184

For a better result, you should use specialized external format programs.

You can integrate both tidy and html-beautify automatically by installing the plugin vim-autoformat. After that, you can execute whichever formatter is installed with a single keystroke.

Upvotes: 4

New Alexandria
New Alexandria

Reputation: 7324

It would be better to use the tidy utility, as described in this answer.

Good tools have already been written for this job

Upvotes: 1

Chris Morgan
Chris Morgan

Reputation: 90712

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>

Upvotes: 54

Related Questions