A Komodo customer recently asked for us to make adding image tags painless the way he was used to in his previous editor. Instead of typing some HTML and the URI, he wanted to pick the image file via a dialog box, and have Komodo do all the work. Well, I could file a bug, and he could then wait for the next development cycle to release a fix. But it’s an easy macro. And since it’s not that complex, and shows the basic parts of the Komodo API, I figured I’d publish the macro here, with annotations explaining how it works.
problems and relay them with an alert statement.
try { var view = ko.views.manager.currentView; var dirName = view.koDoc.file. dirName;
The above two lines are standard for getting information on the current document. I’m assuming the image file will be somewhere near the document we’re working on. You can change it to other asset directories.
var res = ko.filepicker.browseForFile(dirName, null, "Choose an image file to insert"); if (!res) { return; } var url = ko.uriparse.localPathToURI(res);
We need to work with URIs, not local paths. This code will just convert the local path to a “file://” URI, you’ll probably need to write a mapper that’s aware of the structure of your site.
if (!url) { alert("Can't get url from path'" + res + '"'); return; } var scimoz = view.scimoz; var currentLine = scimoz.lineFromPosition(scimoz.currentPos); var lineEndPos = scimoz.getLineEndPosition(currentLine);
Finally, get the current location in the document, create a new JS Image object, set its src field, and if and when the image is loaded, you can get the height and width settings of the tag. The call to “view.scintilla.focus()” ensures we can continue to type after the tag has been inserted.
var img = new Image(); img.onload = function() { var qq = function(s) { return '"' + s + '"'; } var newText = ('<img src=' + qq(url) + ' height=' + qq(img.height) + ' width=' + qq(img.width) + '>'); scimoz.beginUndoAction(); try { scimoz.insertText(lineEndPos, newText); scimoz.gotoPos(lineEndPos + newText.length); } finally { scimoz.endUndoAction(); } view.scintilla.focus(); } img.src = url; } catch(ex) { alert(ex); }
The Komodo API is huge when you include all the Mozilla infrastructure it includes, and the initial learning curve can be steep (yes, I know tough learning curves are actually shallow, but that’s being pedantic). But once you get a few functions like these working, you can take Komodo into directions we never anticipated.
Title image courtesy of BRRT from Pixabay.