Formatting Javascript HTML
As I worked on my blog, I found myself looking for a code beautifier like I use in my professional life. I had looked previously, but never found anything that worked simply or with any consistency. Today, however, I found a way.
I ran across http://jsbeautifier.org/. Fortunately, the folks there have written a beautifier in javascript that they publish with an open license. Using it through the web interface was not what I was after. I wanted something that would integrate into my editor. I found that some shell scripting, a couple of libraries, and automator would solve the problem simply. Unfortunately, this will only work on a Mac. Since it is java/javascript based, it is possible to integrate it in other ways on other platforms.
Here’s how to do it:
- Download the beautifier library: tar.gz
- Download the Rhino javascript implementation.
- You are going to keep these files. So, extract them somewhere that won’t be trashed.
- Since jsbeautifier does not handle stdin, we will have to run stdin through a temporary file. Create a shell script as follows:
#!/bin/sh cat > /tmp/tmptidy java -cp [path_to_rhino]/rhino/js-14.jar org.mozilla.javascript.tools.shell.Main [path_to_jsbeautify]/einars-js-beautify/beautify-cl.js /tmp/tmptidy exit 0
- Save this script to /usr/local/bin and make it executable (chmod +x /usr/local/bin/myscipt)
- Create an Automator Service
- Open Automator (Mac OSX)
- Choose to create a new Service
- By default, the new service will be setup up to recieve text.
- Drag the ‘Run Shell Script’ action to the workflow.
- By default, the action will run bash and pass input to stdin
- In the action, type /usr/local/bin/my_script
- Save the action with the name that you want to appear in the Service menu.
That’s it!. Go into your favorite MacOSX text editor, highlight your javascript/html, right-click, select services and your service name. If you don’t see your service, you may need to go into Service Preferences and enable it. While you are in there, you can assign a univeral keystroke to it making it even more convenient.
About this entry
You’re currently reading “Formatting Javascript HTML,” an entry on _mindMeld
- Published:
- 1.23.10 / 6pm
- Category:
- Java, Technology
- Tags:










0 Comments
Jump to comment form | comments rss [?] | trackback uri [?]