1390

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?

ragnarswanson
  • 315
  • 3
  • 10
Ravi Ram
  • 24,078
  • 21
  • 82
  • 113

16 Answers16

2146

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.

Josh Correia
  • 3,807
  • 3
  • 33
  • 50
peter
  • 41,770
  • 5
  • 64
  • 108
  • 3
    Further, you can add a key binding in a Mac enviro to automate "Reindent." I used option + shift + return, but really, use any you like. – arxpoetica Jun 26 '12 at 04:07
  • 20
    By the way, this works for non HTML source code also, like eg Ruby or JS – peter Jul 22 '12 at 17:57
  • 85
    This works great if the code doesn't have multiple tags opening on one line that don't also close on one line or vice versa. – Charlie Gorichanaz Nov 07 '12 at 05:32
  • 32
    Perfect! On mac you need super for the cmd key, so such: { "keys": ["super+shift+r"], "command": "reindent" , "args": {"single_line": false}} – Geert Weening Nov 07 '12 at 12:28
  • 2
    This works on many file types - e.g. set the file syntax to be JSON and it will indent as well. – philwinkle Jan 04 '13 at 05:22
  • 5
    For some reason, this doesn't do anything on an HTML file I have, which has gotten all line breaks removed. – RipperDoc Feb 09 '13 at 07:20
  • @RipperDoc, no but i believe that is for the best, indentation is only for lines, but if you don't have lines.. A complete reformating tool is sametimes necessary and i'm sure that on this page alone there are allready good solutions for that but it would need a lot of configuration to fit everyone's wishes – peter Feb 09 '13 at 10:40
  • 1
    This works for simple files, but if all your tags are inline (don't ask) then it's not so helpful. I vote for the answer from @dardub. – Kevin Feb 20 '13 at 12:57
  • 180
    line reindent absolutely does NOT work for reformatting arbitrary HTML. such as when there are multiple html tags without line breaks. The HtmlTidy answer from @anneke is superior. Far as I can tell, regardless of linebreaks, it completely and properly reformats the source html into nicely indented source. – jpw Apr 13 '13 at 19:22
  • 1
    @RipperDoc same issue here. Installed [Tag](https://github.com/SublimeText/Tag) for reformatting. – nil May 06 '13 at 05:06
  • 1
    Edit>Line>Reindent works. but that takes 3 clicks. and no ctrl shortcut. i wish there is 1 click option like the 'tidy up' in jsfiddle. :D – mars-o Jul 09 '13 at 12:01
  • 1
    Hey mars-o, try to add the shortcut i published in my answer, if you haven't used keyboard shortcuts before, it's under "Preferences, Key - bindings user" Just paste the line there and make sure you use a free key-combination – peter Jul 16 '13 at 06:57
  • 34
    For newbies, click "Preferences", then choose "Key Binding - User", and paste peter's code between the square brackets and save the file. – sigmapi13 Jul 31 '13 at 13:53
  • 2
    I did this on a mac `{ "keys": ["super+enter"], "command": "reindent" , "args": { "single_line": false } }` – Raj Oct 19 '13 at 11:36
  • 2
    this won't work if you have a bunch of HTML comments, or strangely formatted html. remove the garbage first then format, works like a charm. – botbot Jan 18 '14 at 23:26
  • 1
    A neater and faster alternative to clicking through menus and without digging through keybindings is to use the **command palette**. Bring it up using Ctrl+Shift+P, then search for the command (i.e. reindent). – Albert Xing Jun 05 '14 at 17:00
  • Tidy HTML ate my tags. :( – john k Oct 31 '14 at 22:57
  • 1
    Umm.. I have setting my preferences. but I don't know why it's not working – Alfian Busyro Nov 13 '14 at 06:23
  • 3
    If you have trouble because of multiple html tags on the same line, just select one of the `<` characters and hit `alt` + `F3` to select all of them, hit the left arrow once and then enter. It's not perfect, but that will put every opening/closing tag on a new line, which makes the `reindent` command work better – Chaulky Dec 11 '14 at 05:27
  • Reindent doesn't work for HTML without line breaks before each tag, such as HTML generated by an engine for example. – Matt Sinclair Apr 03 '15 at 12:13
  • Reindent seems to break on custom HTML tags as used by Ionic framework. – Richard Le Mesurier Jun 10 '15 at 14:56
  • 1
    With the key binding set, using without selecting anything in ST3 does the entire file by default, no ctrl-A needed. It's not the best, but at one keystroke is quick and easy and not too bad for PHP code and some other languages. – Nick Jul 06 '15 at 17:40
  • 3
    I wanted to replicate the VS keybinding for reformat. You can chord easily in Sublime. `{ "keys": ["ctrl+e, ctrl+d"], "command": "reindent" , "args": { "single_line": false } }` – Iain M Norman Jul 24 '15 at 10:34
  • what about while pasting code? `{ "keys": ["ctrl+v"], "command": "paste_and_reindent" }` doesn't work – user924 Oct 27 '17 at 16:07
  • Before doing this, I have to first de-indent everything (SHIFT+TAB many times) and then reindent, to hav clean indents of the same number of spaces everywhere. – Basj Feb 03 '22 at 19:10
399

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 not expand minimized or 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.

ninjoncrak
  • 107
  • 1
  • 9
Josh Earl
  • 18,151
  • 15
  • 62
  • 91
  • 13
    2nded on Prettify. The re-indent didn't work on the html I had, couldn't find Tag and HtmlTidy didn't do anything when I called it. – jcollum Mar 05 '14 at 21:14
  • 2
    just tried it out and HTML-CSS-JS Prettify worked in my use case ideally (handled cleaning up the html far better than the built in reindent or other reformatter packages) – Mark Essel Apr 25 '14 at 11:17
  • 2
    Tried all the others, but the only one that worked (for an snippet of HTML) was HTML-CSS-JS Prettify. Thank you! – zumek May 03 '15 at 04:44
  • 1
    Also wanted to mention that you can remove all the indentation (once the markup has been edited, for instance) simply by using ST's built in functionality - select the block and press ctrl+j. – zumek May 03 '15 at 04:54
  • 1
    Does this work with non html extensions? i tried on php and other templates, it didnt work. – Abdul Rehman Jul 16 '15 at 13:08
  • HTML-CSS-JS Prettify does not support chinese file name properly, when I open a HTML file named `方法.html` in ST2 and use Ctrl-A , Ctrl+Shift+H , it prompts me "node.js" not found. **But for `method.html` it works well.** – pimgeek Sep 09 '15 at 08:32
  • To indent `` and `` also, you can set in **Preferences** `"indent_inner_html" = true`. –  Sep 18 '15 at 04:41
  • HTML-CSS-JS Prettify requires node.js to be installed. – RN Kushwaha Sep 29 '15 at 12:39
  • HTMLBeautify doesn't support moustache JS or any templating engine that use {{ }} I found HTML-CSS-JS Prettify more consistent. – Matteo Boscolo Aug 10 '18 at 09:53
  • This was amazingly helpful, thank you very much! HTMLPrettify ended up being exactly what I needed. – Michael Armes Aug 15 '18 at 14:53
  • For styling HTML I tried install **Tag**, **HTMLTidy**, **HTMLBeautify**. But some not found in Package control and some not styling HTML when multiple tags opening on one line that don't also close on one line. And only **HTML-CSS-JS** Prettify do work. But for working you should do `apt-get install nodejs`. – Eric Korolev Dec 21 '18 at 11:41
  • The `HTML-CSS-JS Prettify` approach works wonders! In my case I wanted a quick way to prettify HTML snippets embedded within PHP files (Laravel blade.php files to be exact) so I had to adjust the `allowed_file_extensions` setting as shown here: https://github.com/victorporof/Sublime-HTMLPrettify/issues/532 – Rick Feb 28 '22 at 19:38
181

The only package I've been able to find is Tag.

You can install it using the package control. https://sublime.wbond.net

After installing package control. Go to package control (Preferences -> Package Control) then type install, hit enter. Then type tag and hit enter.

After installing Tag, highlight the text and press the shortcut Ctrl+Alt+F.

tristansokol
  • 4,054
  • 2
  • 17
  • 32
dardub
  • 3,166
  • 5
  • 29
  • 31
  • 21
    a better plugin is Tidy HTML – MatthewFord May 21 '12 at 14:53
  • 1
    thanks... just knew now about packages :D. saw some cool stuff for sublime text here as well. http://arlando.net/blog/setting-up-sublime-text-2-for-front-end-development/ – mars-o Jul 09 '13 at 12:06
  • 3
    This honestly is the only thing that worked perfectly with some HTML code that had hundreds of random line breaks, tags that were incorrectly nested. It basically cleaned up one of the messiest HTML pages I've ever seen! – justinhartman Dec 09 '13 at 20:11
  • 1
    I disagree with @mars-o; this plugin is great. Tidy does a few things really well, and is very established, but this plugin does quite a few other interesting things. Thanks for the post. – zedd45 Jan 29 '14 at 16:18
  • @JonnyLeeds It kind of does, but not always correctly. For XML specifically, try `Indent XML` or `IndentX` among others. – Joel Mellon Feb 18 '15 at 01:47
62

I recommend this plugin: HTML/CSS/JS Prettify, It really works.

After the installation, just select the code and press CTRL+SHIFT+H.

Done!

Josh Correia
  • 3,807
  • 3
  • 33
  • 50
Peter Zhu
  • 1,154
  • 3
  • 15
  • 27
42

Just a general tip. What I did to auto-tidy up my HTML, was install the package HTML_Tidy, and then add the following keybinding to the default settings (which I use):

{ "keys": ["enter"], "command": "html_tidy" },

this runs HTML Tidy with every enter. There may be drawbacks to this, I'm quite new to Sublime myself, but it seems to do what I want :)

Anneke
  • 421
  • 4
  • 2
  • 2
    I imagine this plugin might become a bit intensive on big files, which might become sluggish if it runs every time you hit enter? – Rikki Dec 15 '13 at 20:28
  • 2
    I used the ENTER keybinding for about a day then removed it. it was too slow and kept taking the cursor to the top of the screen in v2. – Ravi Ram Apr 23 '14 at 14:06
30

Altough the question is for HTML, I would also additionally like to give info about how to auto-format your Javascript code for Sublime Text 2;

You can select all your code(CTRL+A) and use the in-app functionality, reindent(Edit -> Line -> Reindent) or you can use JsFormat formatting plugin for Sublime Text 2 if you would like to have more customizable settings on how to format your code to addition to the Sublime Text's default tab/indent settings.

https://github.com/jdc0589/JsFormat

You can easily install JsFormat with using Package Control (Preferences -> Package Control) Open package control then type install, hit ENTER. Then type js format and hit ENTER, you're done. (The package controller will show the status of the installation with success and errors on the bottom left bar of Sublime)

Add the following line to your key bindings (Preferences -> Key Bindings User)

{ "keys": ["ctrl+alt+2"], "command": "js_format"}

I'm using CTRL+ALT+2, you can change this shortcut key whatever you want to. So far, JsFormat is a good plugin, worth to try it!

Hope this will help someone.

Josh Correia
  • 3,807
  • 3
  • 33
  • 50
Gokhan Tank
  • 3,786
  • 1
  • 22
  • 19
16

For me, the HTML Prettify solution was extremely simple. I went to the HTML Prettify page.

  1. Needed the Sublime Package Manager
  2. Followed the Instructions for installing the package manager here
  3. typed CMD+SHIFT+P to bring up the menu
  4. Typed prettify
  5. Chose the HTML prettify selection in the menu

Boom. Done. Looks great

Josh Correia
  • 3,807
  • 3
  • 33
  • 50
insaineyesay
  • 336
  • 2
  • 7
  • This solution worked exactly how I wanted it to and takes all but 2 seconds if you have the PM installed already. Might want to add that you need to install the prettify package. – doogle Sep 03 '14 at 21:31
  • 3
    Note: For anyone interested, the plugin in this answer requires installing node.js. – Fake Name Sep 25 '14 at 08:22
  • Doesn't work properly; only indented/line-breaked the HTML up to a certain level of indentation and left the rest un-indented and on the same line. – Jonathan Sep 19 '19 at 04:33
15

There's a plugin called SublimeHtmlTidy which works pretty well

https://github.com/welovewordpress/SublimeHtmlTidy

Christian Hagelid
  • 8,275
  • 4
  • 40
  • 63
11

Simply go to

Edit -> Tag -> Auto-format tags on document

Ricardo Martins
  • 5,702
  • 3
  • 40
  • 59
  • 6
    I don't see that menu option in `Sublime Text 2 Version 2.0.1, Build 2217` on Mac. Are you sure it's a standard feature? – ostergaard Jan 13 '13 at 07:22
  • 1
    You have to install Tag from the Package Manager. But I have one problem with it. When `somthing` is followed by a comma, the comma is put on a new line, resulting in a space between something and the comma in a browser view. – reitermarkus Feb 13 '13 at 17:33
9

I created a Package called HTMLBeautify that does a decent job of reformatting HTML. I based it off of a Perl script I found back in 1997—I updated it to work with all the new fangled modern tags. :)

Check it out and let me know what you think!

https://github.com/rareyman/HTMLBeautify

Ross
  • 111
  • 1
  • 4
  • 4
    I installed it but when I run HTMLBeautify on the demo file it does nothing. A message Displays that the file is beautified, but nothing happens to the file Contents. – Sam Jun 09 '13 at 21:08
  • My guess is you are using Windows…? On Windows, you need to restart SublimeText 2 for the script to be available. Try that and let me know what happens. :) – Ross Jun 19 '13 at 17:04
  • I did, the script was available, it just didn't Change anything in the file. – Sam Jun 20 '13 at 12:25
  • Strange. I am assuming all other plugins/packages work as normal? I cannot seem to replicate this issue in my test environments—so I am unsure what to tell you. :( – Ross Jun 21 '13 at 17:44
  • Apart from formatting everything works as I'd expect it to - maybe it's because I'm running a german version of windows? – Sam Jun 24 '13 at 14:05
  • Maybe the script can't access the settings file that has the definitions of tags to indent/unindent, etc.? Open the script source and look for: settings.get('…') (lines 19-29). Then, open the settings file and look for the string containing the tags. You can copy the "tag" strings and put them directly into the script to see if that helps. (Normally, the script will look at the settings file to figure out what to indent/unindent—maybe in your case this isn't working…?) HTH! – Ross Jun 25 '13 at 18:06
  • This worked for perfectly me in ST2 and Windows 7; i also tried HTML-CSS-JS Prettify and Tag but they did not seem to work – vein Jul 12 '14 at 09:10
  • Worked for me on OSX and Subl 2. Unlike other packages, it did not wreck the display of the HTML. Thanks. – Soferio Sep 04 '14 at 10:54
9

I think this is what you're looking for:

https://github.com/victorporof/Sublime-HTMLPrettify

Allen Bargi
  • 14,674
  • 9
  • 59
  • 58
  • I followed the instructions but it did not work. The plugin gives me errors. "'{' is not recognized as an internal or external command, operable program or batch file." – Ravi Ram Jan 16 '12 at 15:32
  • I believe that specific package requires Node to be installed which is an additional undertaking... http://dandean.com/nodejs-npm-express-osx/ disregard the NPM and express – bgreater Apr 05 '12 at 00:12
  • @Allan Is this work on Windows. I have node.js installed in my computer. – Anirudha Gupta Oct 01 '12 at 02:34
7

I am yet to have the privilege to comment so this is simply additional information related to @peter's answer above answer.

I found HTML did not align as expected if IE conditional comments in the header were not completely in-line e.g. flush to the left:

<!--[if lt IE 7]>
<p class='chromeframe'>Your browser is <em>unsupported</em>. <a href="http://browsehappy.com/">Upgrade to a different browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to experience this site.</p>
<![endif]-->
<!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]--> 
Community
  • 1
  • 1
newtriks
  • 1,434
  • 11
  • 13
7

There is a nice open source CodeFormatter plugin, which(along reindenting) can beautify dirty code even all of it is in single line.

side2k
  • 2,054
  • 3
  • 17
  • 13
7

I'm using tidy together with custom build system to prettify HTML.

I have HTMLTidy.sublime-build in my Packages/User/ directory:

{
  "cmd": ["tidy", "-config", "$packages/User/tidy_config.cfg", "$file"]
}

and tidy_config.cfg file in the same directory:

indent: auto
tab-size: 4
show-warnings: no
write-back: yes
quiet: yes
indent-cdata: yes
tidy-mark: no
wrap: 0

And just select build system and press CTRL+B or CMD+B to reformat file content. One minor issue with that is that ST2 does not automatically reload the file so to see the results you have to switch to some other file and back (or to other application and back).

On Mac I've used macports to install tidy, on Windows you'd have to download it yourself and specify working directory in the build system, where tidy is located:

"working_dir": "c:\\HTMLTidy\\"

or add it to the PATH.

Josh Correia
  • 3,807
  • 3
  • 33
  • 50
rchl
  • 146
  • 1
  • 4
3

you can set shortcut key F12 easy!!!

{ "keys": ["f12"], "command": "reindent" , "args": { "single_line": false } }

see detail here.

Heinrich Cloete
  • 702
  • 5
  • 12
2

HTML-CSS-JS Prettify - Hands down the best.

  1. Install Package Control
  2. ⌘ + left shift + p (or ctrl + alt + left shift + p) -> Package Control: Install Package
  3. Enter HTML-CSS-JS Prettify
  4. Install node
  5. Restart Sublime Text

Enjoy.

Luis
  • 280
  • 3
  • 11