This is a little snippet that's been sitting in my .zshrc for
years, and which people always seem to like. With a little bit of aliasing and
with the help of the pygmentize utility from
pygments, we can get stodgy old cat to produce colourful
listings with syntax highlighting.
First, we'll need pygmentize. In Debian (at least), it's
available through the python-pygments or python3-pygments
packages. Then, we just need to add this to our shell config file,
like .zshrc or .bashrc:
function pygmentize_cat {
for arg in "$@"; do
pygmentize -g "${arg}" 2> /dev/null || /bin/cat "${arg}"
done
}
command -v pygmentize > /dev/null && alias cat=pygmentize_cat
This first defines a new function called pygmentize_cat that
does what we want: each argument is in turn run through pygmentize,
with instructions to attempt to guess what kind of file it is. If there are
any errors (like if we can't guess the right file type), we silently supress
them and fall back to plain unadorned cat.
Next, we make sure pygmentize is actually available before we alias
cat to point to pygmentize_cat. This will save your bacon
if you copy your configuration files over to a new machine before installing
pygmentize.
I leave mine as-is, but you can further configure this by passing additional
arguments to pygmentize. For example, you could choose a different
colour scheme. Have a look at pygmentize --help to get an idea for
what's possible.