Thursday, December 6, 2012

Putting syntax-highlighted code into presentation slides or documents

Brogramming with Tom

Want to include syntax-highlighted code in your presentation? A project called Pygments provides a very helpful tool for this. First, you need to install Pygments:

  • If you're on OS X and use MacPorts, you can fetch it with
    sudo port install py27-pygments
  • If you're on Ubuntu/Debian, you can get it with apt-get with
    sudo apt-get install python-pygments
  • Or you can fetch it on any platform using pip* with
    sudo pip install pygments

Installing Pygments will also install a command line utility called pygmentize**. We can use this tool to help us format code for use in a presentation or document with the following steps

  1. Open the terminal and do
    pygmentize -f rtf <PATH_TO_CODE_FILE> | pbcopy
    if you're on OS X, replacing <PATH_TO_CODE_FILE> with the actual path to your file of interest (use xsel -b instead of pbcopy if you're on Linux, or clip if you're on Windows). This will copy a colorized markup of your code to your clipboard.
  2. Paste the contents of the clipboard to your document or slide
    • This should be as simple as using Edit → Paste (COMMAND + V on OS X, CTRL + V on anything else)
    • If you're using PowerPoint, you instead need to use Edit → Paste Special (CTRL + COMMAND + V shortcut on Mac Office) and select "Formatted Text (RTF)". Also, you may need to create a new text box first, as the default text box will unhelpfully try to insert bullet points for you. Alternatively, you can just remove the bullet points by highlighting all the code and clicking the bullet point button (sometimes having to do this multiple times...)

That's it! pygmentize can parse files in a wide number of programming languages, as well as output in many different formats; for example, if you use LaTeX/Beamer, you can get TeX output by using -f tex. You can look at the Pygments documentation on lexers and formatters to see the full list of languages and output formats Pygments and pygmentize support.

* Don't have pip? Go get it!
** If you installed with MacPorts, you'll probably have to use pygmentize-2.7 instead of pygmentize.