Quick and dirty hack to get syntax coloring in Keynote

I figured I’d toss this out in the event that someone has a better solution in hand. I tossed this together quickly and it works. It requires that you have Pygments installed and pygmentize on your path (which is silly, because I could have just imported pygments as a library…) It also requires that Safari is running. But, hey, it works.

import os
import sys

def go():
    if len(sys.argv) != 2:
        print "Usage: %s <filename>" % sys.argv[0]
        sys.exit(1)
    output_fn, ext = os.path.splitext(sys.argv[1])
    output_fn += '.html'
    print "Generating %s" % (output_fn)
    os.system("pygmentize -O full -o %s %s" % (output_fn, sys.argv[1]))
    print "Copying to clipboard..."
    fullpath = os.path.abspath(output_fn)
    os.system("""osascript<<END
tell application "Safari"
        activate
        make new document at end of documents
        set url of document 1 to "file://%s"
end tell

tell application "System Events"
        tell process "Safari"
                click menu item "Select All" of menu "Edit" of menu bar 1
                click menu item "Copy" of menu "Edit" of menu bar 1
                click menu item "Close Window" of menu "File" of menu bar 1
        end tell
end tell
END
""" % (fullpath))
    
if __name__ == "__main__":
    go()

3 thoughts on “Quick and dirty hack to get syntax coloring in Keynote”

  1. I’m not clear on what this is doing… are you hacking up your keynote file itself to add the highlighting or generating a new HTML or…?

    In short: what goes in argv[1]?

    I’ve become a huge keynote fan… I dunno if it’s possible (or have any idea how) to write an input manager for keynote to add a “Pygmentize selection” function, but it’d be cool.

  2. Yeah, that wasn’t very clear. It was a quick and dirty hack that was posted quickly and dirtily 🙂

    To use the script, you do:

    that_script.py FILENAME_TO_HIGHLIGHT

    FILENAME_TO_HIGHLIGHT can be any of the languages that pygments supports.

    What you end up with is the highlighted version on the clipboard, which you can then paste into Keynote (or anything that supports pasting of HTML/formatted text that way). In my copy of the script, I also added an os.unlink(output_fn) to the end of the go() function, so that the pygments-generated HTML files weren’t left lying around.

Comments are closed.