Code syntax highlighting

For source code snippets included in LaTeX

There are a few ways to include code fragments in a LaTeX document. Two good ones are the listing package that comes with the standard installation of LaTeX. Listings does not do color highlighting without some extra work. And the mintex package which is more modern. Minted however, requires installation of additional software that is albeit involved. For example, I use TextMate to author my research papers and I really like the workflow I have going on right now. It integrates Skim very nicely, and I can hyperlink from the PDF directly back to TextMate smoothly. Therefore, when I reached the point in the minted install that asked me to change how LaTeX is invoked I decided that I had enough play for one day.

But I was not willing to give up source code highlighting. After a long web search I arrive to two conclusion: (1) I'm not the only one having this problem; and (2) There is no effortless way of doing it. Well. I decided to change that.

The process described below is for OS X. It allows you use your the favorite code editor. After all, it already does syntax highlighting, and you know how to use it. This approach keeps your source code snippets properly indented and syntax colored. And its stupid simple. There is nothing to install or to mess up with. What makes it work is really the process; Favoring simplicity to full automation.

The process

Start by authoring the code snippet or algorithm in your regular code editor or IDE.

When you are done writing the code go to print (⌘P) but instead of printing, select "Open PDF in Preview" (circled in red in the image below):
Open PDF in Preview

Now in Preview, click "Show Markup Toolbar" icon (circled in green) and click the Rectangular Selection icon (cyan).
Preview markup toolbar
Drag to create a rectangle around the part of the code you want to save as the syntax highlighted figure.
You can still drag the rectangle edges or move it around to fit the code snippet after you have placed the rectangle.
Preview mark rectangle for copying

Copy the rectangular area to the clipboard with the regular copy command (⌘C).

Still in Preview, select File -> New from Clipboard, or simply press ⌘N and save the resulting document as PDF.

You are done. All that you need to do now it to simply include the PDF file you save as you include any other figure in LaTeX.

Note that if you were to save the original source code file as PDF you will end up with the source code in the top-left side of a PDF that is mostly empty white space. It would not be something that will be able to directly include in LaTeX. The document we saved will include only the bounding rectangle you marked.

Back to code page