Tuesday, October 26, 2010

Greasemonkey script for HiFi Regex evaluator

In my last post, I had mentioned that HiFi Regex Evaluator is great for playing around with regular expressions. Some of the UI features that I really like are:

  1. Uncluttered interface: Just like Google search interface, this site has the regex input field right in the top center, focusing my attention
  2. No submit button: After typing in a regular expression, I don't have to click a button to evaluate it on the text. It does that as I keep typing. Like Google Suggest.
  3. Color coding: The matches are split according to capturing groups and displayed separately and color coded. So it's easy to figure out capturing groups' matching.
  4. Cheatsheet: A handy cheat sheet is embedded on the right side for quick reference. So, no switching tabs to refresh my memory about syntax.
With these features, it is a good fit for prototyping/debugging fairly long regular expressions. Almost like when you are in a REPL session, you can change a small part of the regex, get feedback about the change, tweak again and go on till your regex is ready. However, since I was debugging a huge regular expression (some of which was not JS compliant regex syntax) I wanted the ability to evaluate partial chunks of the regular expression. Initially I started off by putting the big regex in a text file and copying and pasting chunks into HiFi Regex and seeing it's effect. However, switching back and forth between HiFi Regex and the text file was distracting. So, I decided to add on to the site's functionality using Greasemonkey.

My idea was to have an additional text field at the top into which I would paste the bigger regular expression, for once. When I selected a chunk from this original, it should automatically transfer the chunk into the original HiFi Regex text field and trigger a keyup event (programatically). This would eliminate the need to switch between apps for copying chunks. With Greasemonkey and jQuery this was easily done.

However, during the development, I learned that handling the DOM can be a bit tricky within Greasemonkey since the DOM objects are wrapped with XPCNativeWrapper objects for security reasons. After reading the excellent articles on avoiding pitfalls, I was able to understand that jQuery trigger would not work as expected on the XPCNativeWrapper object and instead had to use the dispatchEvent method.

If you want to give it a try, please install Greasemonkey add-on for Firefox and install the script and visit the HiFi Regex site. Please let me know if it helps you in regex construction.

No comments:

Post a Comment