Thursday, March 6, 2014

Syntax Highlighting In Linux Terminal

Hi friends,

Today I am going to show how you can highlight your source code file while you are outputting it inside the Linux terminal. As all of us know what the cat command does. It simply concatenates two or more files, and moreover if just provided one file than it simply renders file's content in terminal.

But wait, what if we can use it to show file's contents as syntax highlighted, much like Vim does. But unfortunately it doesn't.

But there is always a way.

I will tell about a python program called Pygments and how to use it. To install you must have python installed on your machine along with Pip. Pip is a program to download, configure and install python programs on your computer.

To install Pip you can use following command if you are on Fedora:
sudo yum install python-pip
And if you are on Debian like systems you can use:
sudo apt-get install python-pip 
Now having Pip installed let us install Pygments program:
sudo pip install Pygments
This command will install new program in your /usr/bin/ directory called pygmentize.

One of the options pygmentize command has in its sleeves is -g. This option tells command to use appropriate lexer for syntax highlighting by checking files content. For example, if you had provided it a C source file by executing following command:
pygmentize -g pointers_arithmetic.c 
 The program will output file's content using C lexer for syntax highlighting.

That is all we had to do to get syntax highlighting right inside the Linux terminal.

Moreover, we can make a alias in our .bashrc file like this so that we don't have to remember whole command:
alias ccat="pygmentize -g"
Now we can render file's content like this:
ccat pointers_arithmetic.c


That's it all about syntax highlighting inside the Linux terminal.

Cheers.