How do I reformat HTML code using Sublime Text 2?
Asked Answered
P

16

1395

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?

Planetarium answered 12/1, 2012 at 17:49 Comment(4)
See also #9495507Irrelevancy
Also if you use Vintage mode you can simply use gg=G in normal mode.Bloodshed
You can waste your time reading through this whole page, or you can just get github.com/akalongman/sublimetext-codeformatter and get back to work.Lune
Reindent doesn't work at all, playing around with it is a waste of time. Please follow shaneparson's recommendation.Lavern
A
2151

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.

Alpha answered 4/6, 2012 at 21:47 Comment(25)
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.Wristband
By the way, this works for non HTML source code also, like eg Ruby or JSAlpha
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.Antiicer
Perfect! On mac you need super for the cmd key, so such: { "keys": ["super+shift+r"], "command": "reindent" , "args": {"single_line": false}}Swenson
This works on many file types - e.g. set the file syntax to be JSON and it will indent as well.Cut
For some reason, this doesn't do anything on an HTML file I have, which has gotten all line breaks removed.Cradling
@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 wishesAlpha
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.Jumbo
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.Fantinlatour
@Cradling same issue here. Installed Tag for reformatting.Rodgers
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. :DCharterhouse
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-combinationAlpha
For newbies, click "Preferences", then choose "Key Binding - User", and paste peter's code between the square brackets and save the file.Ewald
I did this on a mac { "keys": ["super+enter"], "command": "reindent" , "args": { "single_line": false } }Adeline
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.Yacov
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).Robbi
Tidy HTML ate my <svg> tags. :(Imitative
Umm.. I have setting my preferences. but I don't know why it's not workingCheremkhovo
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 betterPuccoon
Reindent doesn't work for HTML without line breaks before each tag, such as HTML generated by an engine for example.Coelenterate
Reindent seems to break on custom HTML tags as used by Ionic framework.Cuccuckold
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.Cryptonym
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 } }Errant
what about while pasting code? { "keys": ["ctrl+v"], "command": "paste_and_reindent" } doesn't workPlateau
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.Styx
T
401

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.

Trowbridge answered 18/1, 2014 at 16:29 Comment(12)
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.Fist
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)Expeditionary
Tried all the others, but the only one that worked (for an snippet of HTML) was HTML-CSS-JS Prettify. Thank you!Clupeoid
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.Clupeoid
Does this work with non html extensions? i tried on php and other templates, it didnt work.Subcontinent
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.Downy
To indent <head> and <body> also, you can set in Preferences "indent_inner_html" = true.Orlantha
HTML-CSS-JS Prettify requires node.js to be installed.Exocentric
HTMLBeautify doesn't support moustache JS or any templating engine that use {{ }} I found HTML-CSS-JS Prettify more consistent.Dedicated
This was amazingly helpful, thank you very much! HTMLPrettify ended up being exactly what I needed.Fracture
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.Condescension
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: github.com/victorporof/Sublime-HTMLPrettify/issues/532Gusman
F
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.

Fur answered 13/1, 2012 at 23:12 Comment(5)
a better plugin is Tidy HTMLGimcrack
thanks... just knew now about packages :D. saw some cool stuff for sublime text here as well. arlando.net/blog/…Charterhouse
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!Hyoscyamine
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.Bolen
@JonnyLeeds It kind of does, but not always correctly. For XML specifically, try Indent XML or IndentX among others.Electroplate
T
64

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

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

Done!

Tripoli answered 7/1, 2015 at 3:22 Comment(4)
You need Node.js for using that plugin. Not very comfortable for normal users.Perfect
Comparing with the usefulness of this plugin, we can ignore the trouble of installing Node.js ;)Tripoli
Instructions to install packagecontrol.io/packages/HTML-CSS-JS%20Prettify worked great. thanks.Unmoving
To add PHP extension support: github.com/victorporof/Sublime-HTMLPrettify/issues/532Gusman
A
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 :)

Agist answered 1/11, 2012 at 15:17 Comment(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?Conquer
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.Planetarium
C
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.

Capstone answered 24/6, 2013 at 11:34 Comment(0)
A
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

Anton answered 27/7, 2014 at 16:1 Comment(3)
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.Whangee
Note: For anyone interested, the plugin in this answer requires installing node.js.Chlor
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.Commemorate
O
15

There's a plugin called SublimeHtmlTidy which works pretty well

https://github.com/welovewordpress/SublimeHtmlTidy

Outlast answered 8/9, 2012 at 11:0 Comment(0)
W
11

Simply go to

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

Whorish answered 9/10, 2012 at 0:23 Comment(2)
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?Ayesha
You have to install Tag from the Package Manager. But I have one problem with it. When <b>somthing</b> 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.Cyrenaic
A
9

I think this is what you're looking for:

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

Ankus answered 14/1, 2012 at 12:59 Comment(3)
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."Planetarium
I believe that specific package requires Node to be installed which is an additional undertaking... dandean.com/nodejs-npm-express-osx disregard the NPM and expressHumes
@Allan Is this work on Windows. I have node.js installed in my computer.Terenceterencio
G
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

Goldia answered 21/1, 2013 at 18:46 Comment(8)
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.Savil
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. :)Goldia
I did, the script was available, it just didn't Change anything in the file.Savil
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. :(Goldia
Apart from formatting everything works as I'd expect it to - maybe it's because I'm running a german version of windows?Savil
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!Goldia
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 workSterilization
Worked for me on OSX and Subl 2. Unlike other packages, it did not wreck the display of the HTML. Thanks.Edmonson
L
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.

Liard answered 18/2, 2012 at 22:46 Comment(0)
L
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]--> 
Loyola answered 21/11, 2012 at 10:10 Comment(0)
P
7

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

Petersham answered 23/4, 2014 at 7:34 Comment(3)
Note: This requires a local PHP install.Chlor
I've found this to be the only good plugin.. and i've tried almost all of them.Lune
Looks like this one has settings to format HTML attributes. I don't see any of the other plugins do that? Or am I missing one?Whithersoever
C
3

you can set shortcut key F12 easy!!!

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

see detail here.

Cortez answered 21/11, 2014 at 15:55 Comment(1)
Worthless answer; this is a duplicate of the accepted answer.Workbag
H
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.

Hast answered 3/2, 2021 at 20:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.