Exporting JavaScript from a Babel Source Block

One of the nice things about Org mode is that “You’ll never have to write HTML again.” That’s not quite true, of course, but it mostly is. Just write in Org markdown, including tables, and then export it to HTML all from the comfort of Emacs. That’s how Irreal gets published everyday.

If you know a bit about writing non-trivial Web pages, you may want to embed some JavaScript in the final HTML. I do this all the time when I embed a tweet in a post. When I tell Twitter that I want to embed a tweet, it gives me the code (surrounded by <script>, </script>) that I include in the post by simply putting it between #+BEGIN_EXPORT HTML and #+END_EXPORT tags in my Org source. That’s easy because Twitter provides all the code I need.

But what if you want to add your own JavaScript? That’s pretty easy too. You just type <h Tab to get the export tags and then Ctrl+' to be put in a buffer where you can write your JavaScript. That’s fine but there are a couple of problems. First the editing buffer you get put in is in HTML mode not JavaScript mode so you don’t get the syntax highlighting and the other benefits of JavaScript mode. Secondly you have to add all the <script>, </script> boilerplate by hand. Finally, it’s not how you embed source for other languages in an Org document so it’s a special case.

Over at the Emacs reddit, oantolin provides a really nice fix for this. With just a few lines of Elisp he adds JavaScript to the languages that Babel knows about. Now when you want to embed some JavaScript, you just put it in a Babel source block as you would with any other supported language. When you type Ctrl+' you get put in JavaScript mode and the boilerplate will be inserted for you when you execute the block.

What’s really amazing about all this is how easy it is; take a look and see. I hope the Org folks add this to the code base so it will be available without adding the Elisp to your init.el. Even if they don’t, it’s such a minimal amount of code that it’s not much of a burden to add it yourself.

This entry was posted in General and tagged , . Bookmark the permalink.