Custom code formatters in Sublime Text 2

I’m starting to fall in love with Sublime Text 2. It’s the text editor I’ve been looking for since I’ve been editing text.

It’s fast (instant startup, no lag ever). It’s truly cross-platform (looks, feels and runs identically on OS X and Windows). It works beautifully out-of-the-box, but there are plugins galore. It has split windows. It has code completion. It’s pretty.

I could go on.

Anyway, having written my own PHP and JSON beautifiers, I was looking for a quick-and-dirty way of integrating them into ST2 (i.e. without wrapping them up in a dedicated plugin – I’m not fluent with Python yet). Turns out ST2’s build system is almost perfect for this.

Go to Tools > Build System > New Build System, and drop something like this in the window that opens:

    "cmd": ["php", "/path/to/pretty.php", "$file"],
    "selector": "source.json"

Now, assuming there’s a PHP CLI binary on your path, you’re done! Press Cmd+B in a JSON file and it will be “built”, i.e. formatted.

There’s only one shortcoming I’m aware of: Sublime Text 2 doesn’t check for changes in the source file post-build. So you’ll need to use your favourite method to force a file reload.