Praveen's Blog

An Eternal Quest for Incremental Improvement

Org-Mode, LaTeX and Minted - Syntax Highlighting

I use Org-Mode excessively for taking notes, publishing, and even presentation. As a programmer, most of the stuff I write has snippets of source code from various languages. I always feel that well formatted, syntax highlighted code is easy to read in published documents. It is possible to mark a block as source code in Org-Mode.

When exporting an Org file to LaTeX, Org-Mode provides options to format the source code block using one of two popular source code formatting TeX packages namely Listings and Minted. I personally was not that thrilled by Listings. Minted uses Pygments, a Python based syntax highlighter. I already use Pygments in a couple of other scenario. Also, Minted looked more modern compared to Listings. So, I decided to use Minted as my primary code highlighting tool for LaTeX.

To use Minted automatically for LaTeX documents that are exported from an Org file, the following has to be added to your Emacs startup file.

(require 'org-latex)
(setq org-export-latex-listings 'minted)
(add-to-list 'org-export-latex-packages-alist '("" "minted"))

Additionally, make sure that you have Pygments installed on your system.

$ easy_install Pygments

With this, code blocks (#+begin_src ... #+end_src) in an Org file will have a Minted (syntax highlighted) LaTeX environment.

Here is how this sample Erlang code will look like in the resulting PDF.

#+begin_src erlang
  %% A process whose only job is to keep a counter.

  -module(counter).
  -export([start/0, codeswitch/1]).

  start() -> loop(0).

  loop(Sum) ->
    receive
       {increment, Count} ->
          loop(Sum+Count);
       reset ->
          loop(0);
       {counter, Pid} ->
          Pid ! {counter, Sum},
          loop(Sum);
       code_switch ->
          ?MODULE:codeswitch(Sum)
    end.

  codeswitch(Sum) -> loop(Sum).
#+end_src
Screenshot of Minted Output

Screenshot


Comments