October 14, 2008

Komodo macro for automatically finishing img tags

You know how you’re supposed to add the height and width attributes to an img tag? I know, I know, this is the sort of thing we’re supposed to use computers for. After all, it’s tedious to look up that information, and it makes your HTML more brittle, since when you change the image the rest of the tag also goes out of date.  This is so first-normal-form, and yet apparently some people still hit the web via dial-up.

Well, here’s a Komodo macro to automate finishing the tag.  If you change the src attribute, delete the rest of the tag and rerun. Never copy image attributes again. And hopefully in a decade or so this sort of thing will be obsolete.


var scimoz = ko.views.manager.currentView; // scintilla/mozilla editor object
var currentPos = scimoz.currentPos;
var currentLine = scimoz.lineFromPosition(currentPos);
var lineStartPos = scimoz.positionFromLine(currentLine);
var lineEndPos = scimoz.getLineEndPosition(currentLine);
var text = scimoz.getTextRange(lineStartPos, lineEndPos);
if (/<img.*src=["'](.+?)["']/.test(text)) {
    var url = RegExp.$1;
    var img = new Image();
    img.src = url;
    var newText = (' height="' + img.height + '" ' +
                   ' width="' + img.width + '"');
    scimoz.insertText(lineEndPos, newText);
} else {
    alert("Can't get image info from URL '" + text + '"');

// Test line.  Put the cursor somewhere on this line, run the macro.
// <img src="http://upload.wikimedia.org/wikipedia/commons/thumb/0/04/WhiteandKeynes.jpg/200px-WhiteandKeynes.jpg"
Eric Promislow

Eric Promislow

Eric Promislow is a senior developer who's worked on Komodo since the very beginning. He has a M.Sc. in Computing Science from Queen's University and a B.Sc. in Biophysics from the University of Toronto. Before joining ActiveState, he helped create the OmniMark text-processing language.