emacs org-mode live preview

Posted on Di 22. Dezember 2015 in programming • Tagged with emacs, org-mode, live, previewLeave a comment

I am currently writing my Bachelor thesis using the most powerful editor - emacs. Almost all of my classmates use Latex for a clean and scientific layout and that’s definitely a good way to go. But there is an simple alternative: emacs org-mode, an awesome emacs package written by Carsten Dominik. It offers the possibility to write my thesis in an markdown like syntax without that annoing latex commands and all the time consuming backslashes. This plain text org-mode file can be converted into a bunch of formats including latex and html but normally you have to initiate that export step by hand. While writing it would be nice to have something like a live preview, a feature many latex editors offer. So let’s build that in emacs! It is a one liner. All you have to do, is to add the desired org-export command to the after-save-hook, so every time you save your document, it is exported automatically. For exporting to html you can insert the following in the first line of your org-file.

# -*- after-save-hook: org-html-export-to-html; -*-

After reopening the file the export is triggered on every file save (The security warning can be ignored). Notice, that the html will not open. I suggest to open the file in your favorit browser and to install an autoreload plugin which reloads the page on every file change.

But we can do better! If you want to export to latex or your org file becomes bigger and bigger, the export will take a while and emacs will freeze in the meantime. So an asynchroneous export would be great. If you use org-mode version > 8.3 this is built in! Only change the first line to the following:

# -*- after-save-hook: org-html-export-to-html; org-export-in-background: t; -*-

Now emacs will start a background task to export the current file and you are able to work in the meantime. Because html export ist much faster than latex processing in my current setup I export to html and have emacs on the left half of the screen and on the other my browser. Every time I save my document the browser preview updates automatically. Thats great!