ChatGPT解决这个技术问题 Extra ChatGPT

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?

Also if you use Vintage mode you can simply use gg=G in normal mode.
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.

J
Josh Correia

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.


By the way, this works for non HTML source code also, like eg Ruby or JS
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.
Perfect! On mac you need super for the cmd key, so such: { "keys": ["super+shift+r"], "command": "reindent" , "args": {"single_line": false}}
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.
For newbies, click "Preferences", then choose "Key Binding - User", and paste peter's code between the square brackets and save the file.
W
Wavesailor

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