When displaying and
grep-ing text in the Linux terminal, syntax highlighting is very nice to have. In this post I'll give my preferred method, with output like:
My preference is GNU's source-highlight:
Setting it up
The manual suggests setting the
LESSOPEN environment variable in
~/.bashrc in order to get syntax highlighting in the Linux terminal through the
# (This is not my preferred method, read on.)
export LESSOPEN="| /path/to/src-hilite-lesspipe.sh %s"
export LESS=' -R '
However, this will break some other functionality of
less in some distros, e.g. Ubuntu. These distributions define their own
.bashrc, giving extended uses of
less-ing pdf's, images, .deb's, compressed files and more) and depending on which definition is done first, one will override the other.
Can we get both? Yes. Leave the
LESSOPEN untouched. What it does is adding a preprocessor to
less processing, namely
lesspipe/lessfile. Luckily this script allows for additional user-defined pre-processors in the file
~/.lessfilter if it exists.
Create it, give it execution rights, and give it the contents:
file -b -L "$1" | grep -q text && \
This script will be called from
lessfile/lesspipe. If it is a text file it will call the source-highlight script, otherwise it will exit with bad exit status which will leave further processing to the
However we do need to add the line
~/.bash_aliases (if your distro doesn't support this file, add to
less command will now yield the output shown in the images above.
'grep'-ing highlighted source code
grep-ing text in source works as well, and according to the image above, you will get the highlight both from syntax coloring and the
Often you wish to paginate the output from
grep. This requires a trick, for two reasons:
- piping through
lesswill not provide syntax highlighting
- when output from
grepwill not highlight the matches by default
The remedy is to tell
grep to keep the highlighting, although its output is piped, and before
grep-ing send the file through
less for syntax coloring:
Since I often pipe
grep output to
less I have defined the alias
~/.bash_aliases 1. This enables short-hand
grep-ing with colored, paginated output, e.g.
Will source-highlight color my HDL as well?
There is no language definition for VHDL included, but I have created a rudimentary definition file (download) that can be used. Place it in
/usr/share/source-highlight and then edit
lang.map in the same directory and add the lines
vhd = vhdl.lang
Are there other alternatives to GNU's soruce-highlight?
Yes, several. Among them is Vim, with the alias
provides a paginated, source-highlighted output. Vim has built-in support for a large number of file types, including VHDL, Verilog, Tcl and Specman - but unfortunately it won't be possible to
grep on source-highlighted output. That's why I rather prefer GNU's source-highlight.
- Don't be tempted to alias 'grep' to 'grep --color=always'! This might break scripts. ↩