Monday, October 8, 2007

Syntax Highlighting Pager

I use a pager (less) to view files at the console all the time. One feature that's missing with the pager programs I'm aware of (less, more), is syntax highlighting. I find myself opening shell scripts and programs in an editor in order to view them properly with all keywords, strings and numbers color coded and easy to spot. This is cumbersome.

I had an idea: add syntax highlighting to less! A quick internet search after the idea hit me revealed that vim comes equipped with a script that does exactly that by using vim as the pager.

The script is not as feature complete as less, but it's cool - I have the following snippet of code in my .bashrc to define the character - (dash) as a syntax highlighting pager:

# syntax highlighting pager
- () {
/usr/share/vim/vim71/macros/ "$*"

to use it just type at the console
- some_code_file
(it can also accept text from a pipe).


  1. Great idea, but as I use /cat/ much more than /more/ to display files, do you have any idea to adapt this idea to syntax-highlight cat ?

  2. I have an account on multiple machines (with different versions of Vi) and changing the Vim directory with a wildcard makes it work on them all!

    /usr/share/vim/vim*/macros/ "$*"

  3. I had a few problems with the shipped less.vim, so I modified and released it on github:

  4. Looks nice. I'll give it a try. Thanks!

  5. Zung!, thanks for the great and useful tip! Do you know how to add the same thing to zsh?

    Adding "function -() {
    /usr/share/vim/vim71/macros/ "$*"
    }" to .zshrc, and then running "- .zshrc" produces: "cd:cd:10: string not in pwd: -"

    1. I just typed the function definition at the prompt of a freshly configured zsh (under cygwin), using vim73 instead of vim71, and then tried "- .zshrc" - seems to work just fine. So, it can work, but I have no clue as to what's wrong at your end. Sorry.

    2. Zung!, thanks for the response. It must be an issue with my zsh configs then. Maybe, it's because I'm using oh-my-zsh.