Monday, May 3, 2010

Textmate Javascript API

TextMate has a lot of really cool APIs that you might not be aware of. The biggest one as far as I know is the Ruby wrapper which is really impressive. I'll write a post about that on a later date.

In this post I'll cover the Javascript wrapper. This is how the LaTex Bundle allows you to typeset/clean/etc. your tex files by clicking on buttons.

How to use it

When you display output as HTML you have access to the TextMate javascript object. One very interesting method of the TextMate object is the system method which enables you to run system (shell) commands from Javascript.

Here's an example from the Javascript Console bundle I'm currently working on:

var JsConsoleHelper = (function() {

 var helper = {};
 
 helper.openGlobalConfig = function() { 
  var cmd = 'cd "${TM_BUNDLE_SUPPORT}"; mate jsconsole_config.yaml',
    myCommand = TextMate.system(cmd);
  myCommand.onreadoutput = function(str) { console.log("read: " + str); };
  myCommand.onreaderror = function(str) { console.log("error: " + str); };
 };
 
 helper.openProjectConfig = function() {
  var cmd = 'cd "${TM_PROJECT_DIRECTORY:-$TM_DIRECTORY}"; mate jsconsole_config.yaml',
    myCommand = TextMate.system(cmd);
  myCommand.onreadoutput = function(str) { console.log("read: " + str); };
  myCommand.onreaderror = function(str) { console.log("error: " + str); };
 };
 
 return helper;
 
})();

The system function returns a RuntimeObject. It has hooks for handling output and error output. In my example I currently just write to the console but what you would most likely want to do is update the DOM in some way to notify the user of what's going on.