Colorful source code in Terminal
Often it is quicker to take a look at a source code file in Terminal using the
less commands, instead of starting up an editor, especially if you don’t need to make changes. However, like myself, most developers are used to syntax highlighting, or presenting source code in various colours. It makes the different elements in the source code stand out, and helps with comprehension. I find that the older I become, the more I need syntax highlighting, and I think back to a time when it was not so common, amazed that I could make sense of anything. (Of course younger brains have more cycles to burn.)
An easy way to get syntax highlighting to your macOS Terminal is to install Pygments. It is a Python-based source code colorizer library with a command-line interface.
First, if necessary, install Python 3 with Homebrew, make sure your
pip3 tool is up to date, and then install Pygments:
brew install python3 pip3 install --upgrade pip setuptools pip3 install pygments
Now you should have the
pygmentize command in your system, and
will give you an overview.
Pygments supports many programming languages and has several built-in styles. Since I work with Xcode a lot, I like to see similar syntax highlighting in the Terminal, so a typical command for me would use the
xcode style like this:
pygmentize -f terminal256 -O style=xcode -g somefile.py
Pygments tries to infer the correct formatting from the file extension, but the
-g flag makes it also look at the contents of the file. The
-f terminal256 option directs Pygments to output 256-color ANSI escape sequences.
These options are a little too much to type every time I need syntax highlighting, so I’ve defined an alias in my
alias pcat='pygmentize -f terminal256 -O style=xcode -g'
so that I can just say
If you need paging, you’ll probably use the
less utility, but you need to use the
-R option to interpret the ANSI codes emitted by Pygments:
cat somefile.py | less -R
If this doesn’t make your Terminal colourful enough, you can always install lolcat!