Wednesday, June 25, 2008

Printing Syntax Highlighted Source Code

Sometimes, reading code from paper can be easier than reading it from the screen. However, if you printed it straight with the 'lpr' command, you'll lose all your syntax highlighting. There is a way of solving this problem by using GNU 'enscript'.

For example, if you wanted to print syntax highlighted ruby code:


enscript --color=1 -Eruby your_source_code.rb


The '-E' flag tells enscript that the code is ruby, while '-color' is self-explanatory. If you wanted to find out what other syntax highlightings are availabe, use this command:


enscript --help-highlight


However enscript is more than just that. For example, if I wanted it with line numbering, landscaped and in two-columned format (thus saving space), I can do this:


enscript --color=1 -Eruby -c2 -C1 -r -j your_source_code.rb


where:
-c2: 2 columns
-C1: start line numbering from 1 onwards
-r: print in landscape
-j: print border around the columns

It can even generate syntax highlighted code in html, which makes it useful when you want to blog about source code:


enscript --color=1 -w html -Eruby your_source_code.rb


Its 'man page' describes it as "convert text files to PostScript, HTML, RTF, ANSI, and overstrikes" probably doesn't do it much justice, given that it's capable of doing much more; my examples have barely skimmed its surface, so I highly recommend you read more into it to find out enscript's full capabilities.

0 comments:

Post a Comment