Terminal – Syntax Highlighting in the Terminal

colorssyntax highlightingterminal

Lots of programming-oriented editors will colorize source code. Is there a command that will colorize source code for viewing in the terminal?

I could open a file with emacs -nw (which opens in the terminal instead of popping up a new window), but I'm looking for something that works like less (or that works with less -R, which passes through color escape sequences in its input).

Best Answer

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