up vote 2 down vote favorite
2
share [g+] share [fb]

If I want to output a C source code file with syntax highlighting, can I use cat?

link|improve this question

74% accept rate
feedback

3 Answers

up vote 6 down vote accepted

A GNU package, source-highlight, seems to do the trick (though isn't using cat -- as John T points out, this isn't possible with cat specifically). It's available via apt-get on Ubuntu, and requires the Boost regex library. Check your package manager to see if both are available, otherwise you can grab them from the web. The GNU page linked earlier has a link to Boost, I think.

After installation, I created a new script in my path called ccat. The script looks like:

#!/bin/bash
src-hilite-lesspipe.sh $1

Nothing fancy, just simplifying the less script they include with source-highlight. It acts just like cat when called in this fashion.

The included less script is a nice script to use as well, though. I just added the following to .bashrc:

export LESSOPEN="| /path/to/src-hilite-lesspipe.sh %s"
export LESS=' -R '

That script is included in the online manual for source-highlight, as well.

I guess you could alias cat to call src-hilite-lesspipe.sh $1 if you felt like ignoring cat altogether, but that might not be desirable.

link|improve this answer
I, personally, prefer an alias to one-line bash scripts ending with $1 :). – mgalgs Sep 29 '11 at 15:55
Yep, mitch_feaster, you're spot on. :] – rgm Dec 23 '11 at 20:56
feedback

No, cat has no syntax highlighting abilities. If you'd like to view source code with syntax highlighting, pop it into vim or your editor of choice (that has syntax highlighting). This way, you can even page through the output if it's a long file using Ctrl + F (forward) and Ctrl + B (backwards).

link|improve this answer
feedback

To output syntax highlighted code with something like cat, I created a ccat command by following the instructions at http://scott.sherrillmix.com/blog/programmer/syntax-highlighting-in-terminal/.

#!/bin/bash
if [ ! -t 0 ];then
  file=/dev/stdin
elif [ -f $1 ];then
  file=$1
else
  echo "Usage: $0 code.c"
  echo "or e.g. head code.c|$0"
  exit 1
fi
pygmentize -f terminal -g $file

To output syntax highlighted code with something like less, I use vim as a less replacement.

alias less='/usr/share/vim/vim72/macros/less.sh'
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.