If you’re tired of manually re-formatting, indenting, structuring or beautifying HTML code in Sublime Text then you can use the following approach to automatically indent HTML files when you Save.
Based on common questions the following manual approach is provided.
If you don’t want to do this on Save you can easily do it manually with the following approach:
This will perform the reindent
command which provides auto-indentation for HTML if your file is and *.html file. If you want to automate this process then read one to learn how to do this when you save any *.html file.
To do this we need the ability to run sublime commands on common event hooks, like on_pre_save
for example. The Hooks plugin by twolfson is a is very stable plugin that provides this functionality for us.
So the first step to get this working is to install the Hooks plugin for Sublime Text.
Once you have Hooks installed open up an HTML file in Sublime and open the following menu:
Sublime Text > Preferences > Settings: Syntax Specific
This will open the HTML.sublime-settings
file (in Sublime 3.X). Add the following rule to define our HTML auto-indent rules:
Add the following to your HTML’s syntax specific settings:
{
"on_pre_save_user": [{
"command": "reindent"
}]
}
This rule basically says to run Sublime’s built-in reindent
command right before a Save action is performed. We use the pre_save instead of the save action so that indentation occurs before the file is actually saved. This avoids us saving a file without the improvements.
On a more general level I highly recommend exploring the Hooks plugin docs to understand how it works and how you can leverage it to improve and automate your Sublime Text development workflow. I use it for all kinds of action such as:
jshint
on when a *.js file is savedphp_check_syntax
methodIn general I think it’s a great idea to always find ways to improve and automate your workflow. If you agree then understanding how Hooks works at a high level will be a useful asset.
As always, if you have any feedback or trouble implementing this let me know in the comments below. Thanks!