Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

  • 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!

like image 253
Sudar Avatar asked Apr 03 '12 05:04

Sudar


People also ask

How do I indent code in Vim?

To indent the current line, or a visual block: ctrl-t, ctrl-d - indent current line forward, backwards (insert mode) visual > or < - indent block by sw (repeat with . ) then try hitting the F5 key while in insert mode (or just :set paste ).

How do I select and indent in Vim?

Press V then move the cursor to select a range of lines, then press = to indent the selection.

How do I beautify in Vim?

First, go to the start point of codes to be formatted, then press v to start selection. Second, go to the end point. Third, press = to format the codes that have been selected. All braces and indentations will be aligned.


2 Answers

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> 
like image 172
Chris Morgan Avatar answered Sep 21 '22 12:09

Chris Morgan


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.

like image 37
chtenb Avatar answered Sep 19 '22 12:09

chtenb