Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reformat HTML code using Sublime Text 2?

I've got some poorly-formatted HTML code that I'd like to reformat. Is there a command that will automatically reformat HTML code in Sublime Text 2 so it looks better and is easier to read?

like image 986
Ravi Ram Avatar asked Jan 12 '12 17:01

Ravi Ram


People also ask

How do I format my HTML code?

To improve the formatting of your HTML source code, you can use the Format Document command Ctrl+Shift+I to format the entire file or Format Selection Ctrl+K Ctrl+F to just format the selected text.


2 Answers

You don't need any plugins to do this. Just select all lines (CTRL+A) and then from the menu select Edit → Line → Reindent. This will work if your file is saved with an extension that contains HTML like .html or .php.

If you do this often, you may find this key mapping useful:

{ "keys": ["ctrl+shift+r"], "command": "reindent" , "args": { "single_line": false } } 

If your file is not saved (e.g. you just pasted in a snippet to a new window), you can manually set the language for indentation by selecting the menu View → Syntax → language of choice before selecting the reindent option.

like image 176
peter Avatar answered Oct 08 '22 10:10

peter


There are half a dozen or so ways to format HTML in Sublime. I've tested each of the most popular plugins (see the writeup I did on my blog for full details), but here's a quick overview of some of the most popular options:

Reindent command

Pros:

  • Ships with Sublime, so no plugin install needed

Cons:

  • Doesn't delete extra blank lines
  • Can't handle minified HTML, lines with multiple open tags
  • Doesn't properly format <script> blocks

Tag

Pros:

  • Supports ST2/ST3
  • Removes extra blank lines
  • No binary dependencies

Cons:

  • Chokes on PHP tags
  • Doesn't handle <script> blocks correctly

HTMLTidy

Pros:

  • Handles PHP tags
  • Some settings to tweak formatting

Cons:

  • Requires PHP (falls back to web service)
  • ST2 only
  • Abandoned?

HTMLBeautify

Pros:

  • Supports ST2/ST3
  • Simple and no binaray dependencies
  • Support for OS X, Win and Linux

Cons:

  • Chokes a bit with inline comments
  • Does expand minimized/compressed code

HTML-CSS-JS Prettify

Pros:

  • Supports ST2/ST3
  • Handles HTML, CSS, JS
  • Great integration with Sublime's menus
  • Highly customizable
  • Per-project settings
  • Format on save option

Cons:

  • Requires Node.js
  • Not great for embedded PHP

Which is best?

HTML-CSS-JS Prettify is the winner in my book. Lots of great features, not much to complain about.

like image 28
Josh Earl Avatar answered Oct 08 '22 11:10

Josh Earl