Saturday, August 27, 2011

Syntax-highlight pager in windows 7 command line

If you are like me, programming under windows command line a lot, you will miss a handy syntax-highlight pager to quickly display beautiful codes under windows command line.

I know, there are a lot of source code editors in windows, like notepad++, source insight, notepad2, editplus, etc.
However, none of them will work under command line.
We both know that pop-up windows will interrupt your work and force you using mouse.
vim for windows might be a nice choice, but it is too "big" and boo complex for simply reading some code snippets.
Yes what we really need is "less" + "syntax highlight", and that's all.

There are many tools (GNU Source-highlight , highlight) on Linux are able to translate source code into some kinds of formatted text.
If we use "GNU Source-highlight" to highlight source code with escaped ANSI code, and pipe them into "less" command, it should do the job.

Under Linux, that is the complete solution (please refer to this article).
But it won't work under windows 7 command line, even with ported version of "Srouce-highlight" and "less".
The point is that windows 7 command line does not support escaped code!
It's tricky, but finally we overcome this by using a patched version of CMD.
Thanks to Jason Hood, we get ansicon, a escaped code enabled CMD for both 32-bit and 64-bit windows.
you can use it to replace system CMD, or call it after you entering CMD; both of them will work.

Okay, now it comes the whole solution for enabling syntax-highlight pager in windows 7.

1. You need to download and install windows ports of
Source-Highlight
,
unix-util (for less command) and
ansicon.
Please to be noted that all these excusables should be added into system PATH.

2. Add a BAT file called "cless.bat" in your system folder,
@ECHO OFF
source-highlight --out-format=esc --style-file=texinfo.style -i %1 -o STDOUT | less -R -N
This file will call source-highlight with your given file, and pipe the escaped code
into "less" command. The option "--style-file=texinfo.style" sets the style of
your syntax-highlight.
For windows command line, I personally prefer "texinfo" simple white-black style (As the picture bellow).

3. when you need to use it, open an "ansicon" command line window and type
"cless your-source-code-file", then enjoy the nice syntax-highlight pager!


This is sample for "texinfo" style syntax-highlight pager.

P.S. If you are using cygwin or MSYS in windows, this solution will not be needed.

No comments:

Post a Comment