Saturday, June 13, 2015

Beautify javascript on your clipboard on osx with a keyboard shortcut

Working with people's websites, it's fairly common to want to know what a minified script on the page is doing. Usually, this involves copying the script, pasting it into a minifier, copying the result, and pasting it again.

To beautify the contents of the clipboard using a keyboard shortcut, you'll need to install a command line minifier, set up an Automator service that uses the minifier, and assign it a keyboard shortcut.

The following instructions are based on osx 10.10 with pip already installed.

Install the minifier

You can use whichever minifier you want, as long as it takes input from stdin. I use js-beautify. The easiest way to install it is pip install js-beautify.

To minify code provided to stdin, run it like this:

$ echo "function(  ) { return   3;  }" | js-beautify --stdin

which returns

function() {
    return 3;
}

Minify clipboard contents

To minify the contents of the clipboard, you can use the pbpaste and pbcopy commands.

pbpaste | js-beautify --stdin | pbcopy

Create an Automator service

Open Automator, and you'll be prompted with these choices. Choose "Service".


Now, add an action that runs a shell script, set it up to receive "no input" in "any application" and add the command that minifies the contents of the clipboard.


Copy some minified javascript to the clipboard, and click "Run" in the upper right corner to test the script out. You'll probably get an error telling you that the js-beautify command isn't recognized. You need to find the path to the js-beautify command, and include it explicitly.

Scripts that are installed with python packages are installed in the same folder as the python executable, by default. That folder can be found by starting up python and checking sys.executable.

$ python
>>> import sys
>>> sys.executable
'//anaconda/bin/python'

This tells me that the script is located at anaconda/bin/js-beautify. If you use your system's default python installation, it will be different.

Update the Automation path command to include the full path to js-beautify, and the service should work.

pbpaste | /anaconda/bin/js-beautify --stdin | pbcopy

Save the service with a meaningful name. You'll use the name to set up a keyboard shortcut.

Set up a keyboard shortcut

At this point, your service is available in all applications' menus (e.g. Chrome > Services > my javascript beautifier), but can't be run using a keyboard shortcutt.

Open up system preferences, and go to the "Shortcuts" tab of the "Keyboard" section. Select "Services" from the list on the left, and scroll to the bottom, where you should see all user-created services. Assign your clipboard beautifier a shortcut, and you're done!


I went with control-option-command-B, since it's unlikely to clash with any other keyboard shortcuts, it's easy to press all of the buttons at once, and B stands for Beautify.

No comments:

Post a Comment