Embed formatted, syntax-highlighted source code in Keynote

Nov 13, '09 07:30:00AM

Contributed by: wjv

If you have ever given a presentation on any aspect of programming (or webdesign), you may have felt the need to embed some source code (formatted and syntax highlighted to be easily readable) in Keynote. Your options have traditionally been limited:

A much better approach would be to have the source code text (suitably formatted and highlighted) inserted natively in your presentation. Since you can drag Rich Text Format (RTF) text to Keynote, all you need is a way to convert your code to RTF.

Here are three ways of accomplishing this while keeping the formatting intact:

  1. If you have a recent version of the Xcode Developer Tools installed, you already have a Quick Look generator that supports syntax highlighting for a couple of common programming languages. In a Terminal session, type qlmanage -p source_file -o ., where source_file is the file you'd like to have highlighted.

    This will create a subdirectory called source_file.qlpreview, wherein you'll find a file called Preview.rtf. Just drag this file into Keynote; the formatted and highlighted code will appear in a new text box for further manipulation.
  2. While the Quick Look solution is useful in a pinch, it doesnt provide a way for you to customize the formatting of your code, nor does it support more esoteric programming languages. If you need more flexibility, consider installing a highly customisable command-line utility called Highlight (available from Fink and MacPorts) that allows you to convert a plaintext source code file to many formats, including RTF.
  3. Finally, if you want to bypass the command line entirely, here is a third solution that uses MacVim, the OS X port of the UNIX programmer's editor Vim. It assumes no knowledge of Vim (or vi), but if you are familiar with it, you should be able to streamline the procedure and adapt it to your needs (e.g. by changing the highlight colors).

    Install MacVim (I'm using the latest Snapshot 50), and use it to open your source code file. MacVim detects virtually all programming languages, but syntax highlighting is not on by default. To enable it, select Automatic on the Syntax menu.

    Now select Convert to HTML in the Syntax menu. MacVim will open a new buffer populated with HTML code. With this new buffer selected, select Files » Save; this will create a new HTML file in the same directory as the source code file.

    Open this HTML file in Safari. It should appear as a perfect duplicate of the original editing buffer in MacVim, with all formatting (font, indentation, syntax highlighting) options intact. Simply select the code as displayed in Safari and drag it across to a Keynote slide to create a new Text Box.

Comments (5)

Mac OS X Hints