How to create custom TextWrangler filters with PHP

I’ve been using TextWrangler  for years because it’s fast, it has all I need and best of all it’s free. Even though I don’t use it as an IDE, many times I wish it had a few features such as auto-formatting JSON strings. Fortunately, it is very easy to write custom text filters and use them from within TextWrangler. I will show you how to write a “Pretty JSON” filter which takes any valid JSON string and formats it so that it is easier for humans to read while still remaining valid JSON. I will be using php to achieve this.

First we need to write the script. It needs to be able to run as a shell script so you will need to include a shebang pointing to your php executable. To find your php executable, open a Terminal window and type:

$which php

The which command tells you the full path to a program on your path. The output should look something similar to this:

/usr/bin/php

In this case, my php path is /usr/bin/php. We will be using that for our shebang.

Then you need to make a php program that can take input from stdin and output to stdout. Here’s the full php script we will be using:

#!/usr/bin/php 
<?php

$data = file_get_contents('php://stdin');

$json = json_decode($data);

if ($json == null) {
    // Problem decoding json
    return $data;
}

echo json_encode($json, JSON_PRETTY_PRINT);

Basically we capture whatever came from stdin into $data and then decode it into $json. Since the input could be invalid JSON we want to return it untouched in case of error. This is important because if our php program produces any errors, you will then see it in TextWrangler when you use your filter and lose the original data. If we return the original data in case of error, our filter will appear to do nothing which is much better than losing the original data.

Lastly, we return the newly encoded string except that we used JSON_PRETTY_PRINT so that php will add extra whitespace to our string.

Save this script somewhere and copy (or create a symlink like I did) to TextWrangler’s filters dir. This is located here:

~/Library/Application Support/TextWrangler/Text Filters

Note that the name of the file minus the extension will become the name of the text filter inside TextWrangler so you should give it something meaningful.

Now open up TextWrangler (I believe you need to restart it if you already had it open). Under the menu “Text”, the very first option should be a drop-down menu called “Apply Text Filters” and in there should be your filter. Let’s give it a try. Type this into a blank document:

{"testing":123,"hello":"world"}

After you run your new filter your text should look like this:

{
 "testing": 123,
 "hello": "world"
}

Note that the filter could be written in any language, and you can even use already available utilities like aws, sed, etc, to automate everyday tasks.