Saturday, February 2, 2008

Syntax Highlighting Pager, Reloaded

This comment prompted me to search for an alternative way to list source code with syntax highlighting. So I searched for a Debian package with "highlight" in its description:
aptitude search "~dhighlight"
and sifted though the results for anything interesting. I hit upon highlight, installed it and played with it a bit.

It can highlight many types of files, but out of the box it doesn't highlight some file types (I tried listing emacs lisp files and its own configuration files). By default it reports an error if the file type is not recognized, instead of just listing it (which makes more sense to me) - the --force command line option fixes this. You may also need to edit /etc/highlight/filetypes.conf in order to have more file extensions recognized.

If you just want to dump a file to the console:
highlight --ansi --force <filename>
To page through it:
highlight --ansi --force <filename> | less -R
It also doesn't transparently open gzip/bzip2 compressed files (which is the default behavior of less, vim and emacs on a default Debian user account).

All in all, I find it handy - highlight can generate several output formats (xhtml, LaTeX, etc.), can re-indent some file types, can add line numbers, has color themes and more. My only gripe is that it's somewhat painful to configure and use when compared to vim as a pager.


  1. Thanks a lot, this is exactly what I was looking for!

  2. In my opinion the pygmentize script (sudo apt-get install python-pygments) provides better output than the highlight command. The pygmentize equivalent to 'highlight --ansi --force' would be:

    pygmentize -g

    ...where '-g' means, "guess the file type from its contents and fall back to plaintext if necessary." If no output formatter and no output file are specified it defaults to the terminal formatter (equivalent to --ansi with the highlight command).

    I have following in my ~/.bash_aliases file:

    alias pretty='pygmentize -g'

    So I can just execute 'pretty' in the place of 'cat' when I want 'pretty' syntax-highlighted output =).

    -Dan McDougall
    "Those who choose proprietary software will pay for their decision."

  3. Thanks for the tip, I'll certainly give it a try.

    I've tried using highlight as a pager for a while, but decided to go back to using vim as a pager. vim supports a lot more file types, is more accurate, and handles compressed files.