Syntax highlighting with less

Everybody knows that less is more, and although that’s not true in strict UNIX terms, semantically I would have to agree.

One reason that I would nonetheless tend to use vi to view files that I didn’t want to edit, though, is because I love its syntax highlighting. But for people that get twitchy and hit ZZ to quit, or for those who just like the added speed of less or its front-to-back buffering, or SUSE users and Co. that have set an alias o=’less’ like me can also profit from syntax highlighting in less.

How, you ask? First, you’ll need the package source-highlight. Install it with apt-get or zypper, whatever you prefer. The package contains the script src-hilite-lesspipe.sh. If you don’t have admin rights, you can just write it into your ~/bin directory – it’s self-contained. Here’s the source:

#! /bin/sh

for source in "$@"; do
    case $source in
        *ChangeLog|*changelog)
        source-highlight --failsafe -f esc --lang-def=changelog.lang --style-file=esc.style -i "$source" ;;
        *Makefile|*makefile)
        source-highlight --failsafe -f esc --lang-def=makefile.lang --style-file=esc.style -i "$source" ;;
        *) source-highlight --failsafe --infer-lang -f esc --style-file=esc.style -i "$source" ;;
    esac
done

Now that you’ve got that, just add the following lines to your .bashrc and you’re good to go:

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

Should you be using less and decide that you would like to edit the file or use vi for some other reason, just press v and vi will open 🙂

Advertisements
About

My name’s Daniel Lee. I’m an enthusiast for open source and sharing. I grew up in the United States and did my doctorate in Germany. I've founded a company for planning solar power. I've worked on analog space suit interfaces, drones and a bunch of other things in my free time. I'm also involved in standards work for meteorological data. Now I work for the German Weather Service on improving forecasts for weather and renewable power production.

Tagged with: , ,
Posted in Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

From the archive