Syntax highlighting in the terminal

With highlight on a terminal that supports the same colour escape sequences as xterm:

highlight -O xterm256 your-file | less -R

With ruby-rouge:

rougify your-file | less -R

With python-pygments:

pygmentize your-file | less -R

With GNU source-highlight:

source-highlight -f esc256 -i your-file | less -R

You can also use vim as a pager with the help of macros/less.sh script shipped with vim (see :h less within vim for details):

On my system:

sh /usr/share/vim/vim74/macros/less.sh your-file

Or you could use any of the syntax highlighters that support HTML output and use elinks or w3m as the pager (or elinks -dump -dump-color-mode 3 | less -R) like with GNU source-highlight:

source-highlight -o STDOUT -i your-file | elinks -dump -dump-color-mode 3 | less -R

I use GNU source-highlight combined with less -R for this. Add the following lines to your shell's initialization file (~/.bashrc, for example):

cless(){
 LESSOPEN='| source-highlight --failsafe --out-format=esc256 -o STDOUT -i %s 2>/dev/null ' less -R "$@"
}

That should automatically color source code according to the language used and, if it can't, it will launch less on its input directly.


If you're interested in colors in less more generally, you might want to look at lesspipe.sh. See, for example, http://freecode.com/projects/lesspipe.

lesspipe.sh is an input filter for the pager less as described in less's man page. The script runs under a ksh-compatible shell (e.g. bash, zsh) and allows you to use less to view files with binary content, compressed files, archives, and files contained in archives.

It will also colorize shell scripts, perl scripts, etc. similarly to a text editor, but without the use of any "preprocessing" program to do the colorizing.