ANSI color capability detection

To decide if your shell application should output ANSI color codes, check if stdout is a tty.

PHP-SQLlint syntax highlighting

PHP-SQLlint does not only check the syntax of SQL files but can format them, syntax-highlighting included.

Outputting ANSI color codes makes only sense when a human is going to see them, not when php-sqllint is used inside a pipe command chain.

To pipe or not to pipe

Shell programs today often check if the stdout pipe of the current process is a tty, which means it is interactive.

If it's interactive, a user is sitting in front of it and we can use colors. If not, it's a pipe or redirection and no colors should be used.

PHP

PHP's POSIX extension has a method for that: posix_isatty. Because it's not available everywhere you have to check if is there:

<?php
if (function_exists('posix_isatty') && posix_isatty(STDOUT)) {
    //enable ANSI colors
}
?>

You could use the Console_Color2 library to generate ANSI color codes.

Highlighting algorithm

tty-autodetection may not work (e.g. on Windows with ANSI.SYS), or you want to pipe the output to less -R, which is able to handle ANSI escape sequences.

Because of that uncertainties I added a command line option --highlight to php-sqllint:

--highlight=auto
Autodetection via isatty. Default if no option is given.
--highlight=ansi
If you want to force ANSI colors, for use with e.g. less -R.
--highlight=none
Disable highlighting, for easier copy+pasting.

Written by Christian Weiske.

Comments? Please send an e-mail.