`cat` syntax highlighting
I use cat
command everyday, it is very useful to take a quick look to a file, but when reading programmatic code, syntax highlighting is welcome.
An easy way to add a real syntax highlighting is to use the Pygments
python package.
1) Install Pygments package
$ easy_install Pygments
2) Create an alias
Add this your .bashrc
or .zshrc
alias cat="pygmentize -g"
3) Source your .rc
file
$ . .zshrc
4) Try it!
$ cat app/autoload.php
Written by Boris Guéry
Related protips
19 Responses

It seems that this pygmentize -g
doesn't works for regular files and doesn't silently fail. I use a ccat
alias instead, any idea for smarter way?
edit I miss the quote around the alias definition in my ~/.profie
file /edit

A similar solution would be to use vim for syntax highlighting: http://hype-free.blogspot.ro/2011/09/using-less-with-syntax-highlight.html

cat
output is a stream which can then be piped. I don't think vim
can do that.

Excellent!
it works!

I did not experiment that, I'm running it with zsh & macosx.
What happens if you use echo "Some normal text" > test && pygmentize -g test
?

@cdman, I already tried that but it was much slower for me.

@borisguery I'm using zsh
too but on GNU/Linux.
Running directly pygmentize -g test
works fine but when using an alias defined in my ~/.profile
, I get this error:
alias ccat=pygmentize -g
$ ccat test
Error: no lexer for filename 'test' found
Direct pygmentize usage works like a charm:
$ pygmentize -g test
Some normal text
Very strange behavior…

Ok, got it, I missed the quotes on the alias definition… works fine now, nice tip!

(my last comment didn't get published…)
Finally, the answer is very simple, I missed the quotes around the command alias definition --'
Works fine now, thanks for the tip.

Btw, could i get html output with pygment?
Very nice tip!

I agree on using ccat instead of cat since pygmentize doesn't work for normal files :)

I agree on using ccat instead of cat since pygmentize doesn't work for normal files :)

I agree on using ccat instead of cat since pygmentize doesn't work for normal files :)

Thanks. I'd been using code-less
(using the Vim trick). Now I have code-cat
for quick dumps.

That's right

Great tip. I wrapped this up in another script where I use pygmentize if the file is recognizable by Pygments, and lolcat (https://github.com/busyloop/lolcat) if the file is not (I called this "cat.sh" and in my bashrc I alias cat to cat.sh):
#!/bin/sh
# if no file specified default to lolcat reading on stdin
if [ $# -eq 0 ]; then
lolcat
else
TYPE=$(pygmentize -N $1)
if [ $TYPE = "text" ]; then
lolcat $1
else
pygmentize $1
fi
fi
It's also in Github: https://github.com/pzelnip/dotfiles/blob/master/bin/cat.sh

Great tip!