Saturday, 28 February 2009

Publishing an emacs buffer

Yes, another emacs post, in row, but I found this so amazingly cool that I couldn't just keep quiet.

I told myself today: "It would be cool if I could convert what is rendered in an emacs buffer to html so I can show it to others". Of course, some people had already beaten me to it.

Making it happen

I used an emacs add-on by Hrvoje Niksic called htmlize. It does all the hard work, and it does it very well.

Still, I wanted a one key solution to publish it. So I just coded these small emacs-lisp functions:

(defun publish-buffer-to (file)
"Converts buffer to html and writes it to file"
(interactive "Ffile: ")
(require 'htmlize)
(with-current-buffer (htmlize-buffer (current-buffer))
(write-file file)
(kill-buffer (current-buffer))))
(message (concat "current buffer contents published to " file)))

(defun publish-buffer ()
"Converts buffer to html and writes it to ~/public_html/emacs.html"
(publish-buffer-to "~/public_html/emacs.html"))

(snnipets provided by htmlize! =) )

Now all that was left was to provide a simple key shortcut.

(global-set-key [f7] 'publish-buffer)

And thanks to Ruslan Spivak's code I could also add an easy way to create code snippets out of regions.

So now I can easily share my emacs buffers not only on my local server but on my blog =).

Apparently there's another module to do this that might be added to emacs soon, but for now I'm very happy with this solution.

In the future, I'd like to integrate this with tramp and add better file management support so I can seamlessly post to a remote server. I would also like to make it autoreload so it can track live changes, but we'll see.

If you liked this, you can check out my .emacs


  1. some guy named pluskid uses this `htmlize' plug-in to implement `src' tag in muse to. may be you could find something in common from him.