Thursday, 25 July 2013

Org-Mode (version 8) and pdf export with syntax highlighting

This post is will describe how to get a nice syntax-highlighted PDF file by using Emacs' org-mode with LaTeX and Python.


I like to keep my notes in org-mode files as those are plain-text and thus can be edited using Emacs (or any other good text editor) while remaining easy to search.

However, sometimes these notes tend to become big enough to warrant the production of a small document. One of the easiest ways to produce a pretty output remains LaTeX. And it is equally easy to make the source code exports look really nice!


This guide assumes that org-mode >= version 8 is used and LaTeX (including the minted package) is already installed.1

Next a installed version of pygments is needed2. The easiest way to obtain that is via pip:

pip install pygments

Next we have to setup the org-mode LaTeX-export to use the minted package:

;; Include the latex-exporter
(require 'ox-latex)
;; Add minted to the defaults packages to include when exporting.
(add-to-list 'org-latex-packages-alist '("" "minted"))
;; Tell the latex export to use the minted package for source
;; code coloration.
(setq org-latex-listings 'minted)
;; Let the exporter use the -shell-escape option to let latex
;; execute external programs.
;; This obviously and can be dangerous to activate!
(setq org-latex-pdf-process
      '("xelatex -shell-escape -interaction nonstopmode -output-directory %o %f"))

To test the process you can simply evaluate these commands in the *scratch*-buffer.

If you want to toggle these options in org-mode on a per-file basis you can simple put the following snippet at the top of your org-file:

#+BEGIN_SRC emacs-lisp :exports results :results silent
  (require 'ox-latex)
  (add-to-list 'org-latex-packages-alist '("" "minted"))
  (setq org-latex-listings 'minted)
  (setq org-latex-pdf-process
        '("xelatex -shell-escape -interaction nonstopmode -output-directory %o %f"))

No matter which way you choose the following command should produce a PDF-file with syntax highlighted source-code:




Installing new packages in modern LaTeX distributions like texlive or miktex is really simple and explained: here (texlive) and here (miktex).


I recommend using a virtualenv if you do not want to pollute your global Python installation.