Auto Indent HTML in Sublime Text on  Save

Automatically indent HTML files on save in Sublime Text.

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.

Manual Auto-indent for HTML

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:

  1. Select the HTML you want to indent
  2. Go to the Edit > Line > Reindent menu

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.

Performing Actions on Save

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.

Define HTML Syntax-specific Rules

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.

Automating Workflow with Hooks

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:

  • Run jshint on when a *.js file is saved
  • Check PHP syntax with PHP’s php_check_syntax method
  • Save a minified or gzipped copy of an asset on save
  • Run gulp commands and build scripts when a file is saved with changes

In 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!

Meet the Author

Kevin Leary, WordPress Consultant

I'm a freelance web developer and WordPress consultant in Boston, MA with 17 years of experience building websites and applications. View a portfolio of my work or request an estimate for your next project.