Archive for January, 2010

Simple JavaScript HTML parser

Saturday, January 30th, 2010

Once I needed a very simple and fast HTML parser written in actionscriptunlike John Resig I didn’t want to pretty print or fix broken markup; all I needed to is the structure and the attributes – and since it had to be run many times in a second, I tried not to use regexp. I know, it’s silly – but it works.

Now I “ported” that to javascript and eventually to a jEdit macro – why is this good? Because unlike a full blown SAX parser, this tool will not choke on php tags, so I use it to select the innerHTML or outerHTML in a text/html/php file – or just to find a matching tag. Unfortunately right now it parses the full file, so it’s a bit slow, but I may fix that sometime in the future.

Furthmore since this is javascript, it would be very easy to port it to editors with a javascript macro engine (Notepad++ has a rough one, and we also have Aptana, but I find Aptana’s – pretty much discontinued – scriptmonkey buggy and unreliable).

Download the jEdit javascript macro from here

Format JSON with jEdit

Thursday, January 14th, 2010

Sometimes I have to debug or check a json response from the server: I just paste the response to jEdit and reformat it with a macro (yes, I know about the online json beautifier and I think we did have a firebug extension for this, but still, it’s fun to see how flexible javascript macros are):

Download the json2.js from json.org, place it into your lib directory (see: startup.js), then use this ridiculously simple macro to reformat a valid javascript object (in buffer or selection):

(function(){
if (buffer.isReadOnly())
return;

var text = "",
selections = textArea.getSelection(),
bufferSelected = false,
obj;

if (selections.length == 1) {
text = textArea.getSelectedText(selections[0]);
} else {
text = textArea.getText();
bufferSelected = true;
}

obj = eval("(" + text + ")");
include(MACROLIBPATH + "json.org/json2.js");
textArea[bufferSelected ? "setText" : "setSelectedText"](JSON.stringify(obj, null, '\t'));
})();

You can download this and some of my other macros from here.