I am looking for a program like cat but with syntax highlighting. As an example I would like to display the content of one of my Python script highlighted in the terminal without using a pager like we do with cat filename.py.
3 Answers
bat is cat alternative with syntax highlighting and other functionalities. You can see some previews on the GitHub page. This is a fairly new program and may not be available in your favorite distribution repositories. In that case you will have to build it from source or to download the .deb package.
-
1Excellent. I was using `pygments` but now will switch to `bat`. On Ubuntu 20.04 the package is called `bat` and the binary is `batcat` – GMaster May 21 '20 at 08:37
Try out generic coloriser: http://kassiopeia.juls.savba.sk/~garabik/software/grc.html (or better, the readme on https://github.com/garabik/grc). I looked at a few and this was one that "just worked". You can tweak the hilighting with your own regex, but I found it was really good straight out the box. You can pick whatever you want colorised, or use the automatic aliases provided for bash, zsh or fish.
- 151
- 3
You can use source-highlight. First, install the source-highlight package for your system, if available. On Debian-based systems, you can do this with sudo apt install source-highlight. On Arch, it's sudo pacman -S source-highlight.
You can now do:
source-highlight --failsafe --out-format=esc -o STDOUT -i foo.sh
Which looks like:
There are many options you can use to adapt the output to your preferences, see man source-highlight. And you can write a little wrapper function that makes it work as a cat alternative:
colorCat(){
for f; do
source-highlight --failsafe --out-format=esc -o STDOUT -i "$f"
done
}
If you add those lines to your shell's initialization file (e.g. ~/.bashrc for bash), you can then do:
colorCat file1 file2 ... fileN
Personally, I find it more useful as an alternative to less and not cat since source code files tend to be large and it's nice to have the ability to scroll back, search etc. To do that, you can use:
cless(){
LESSOPEN='| source-highlight --failsafe --out-format=esc -o STDOUT -i %s 2>/dev/null ' LESS=-R less "$@"
}
If you use this one with multiple files, you can move to the next file with :n.
- 234,489
- 66
- 447
- 667